From a5a2c237e3193164f479332365c2b8b2a671f99a Mon Sep 17 00:00:00 2001 From: GregorioMonari <102193750+GregorioMonari@users.noreply.github.com> Date: Tue, 7 Mar 2023 17:49:38 +0100 Subject: [PATCH] loopback-fix --- .../{lib/UserInfo => CSS}/UserInterface.css | 0 .../{lib/BugReportPanel => CSS}/bugreport.css | 0 .../embeddedDashboard.css | 0 .../reusableComponents.css | 0 .../TasksConsumer => CSS}/taskdashboard.css | 0 .../updateInterface.css | 0 .../{lib => JS}/BugReportPanel/BugReport.js | 0 .../AwApiUpdateManager.js | 23 +- .../ScanManager.js} | 68 +- .../PacModules}/AwManager.js | 8 +- .../PacModules}/AwProducer.js | 44 +- .../PacModules}/tasksConsumer.js | 7 +- .../{lib => JS}/UserInfo/UserInfoConsumer.js | 8 +- 1_ActivityWatchProducer/JS/greglogs.js | 115 - 1_ActivityWatchProducer/JS/main.js | 467 +- .../{lib => Resources}/my2sec-FULL_271022.js | 0 .../my2sec-jena_251122.jsap.js | 0 .../my2sec-jena_251122.jsap.txt | 0 .../my2sec_19-1-2023.jsap.js | 10 + .../Resources/my2sec_7-3-2023.jsap | 717 ++ 1_ActivityWatchProducer/SECURITY/preload2.js | 1 + .../electron_main_modules/AwApiRouter.js | 191 + .../JsapConfigurationManager.js | 104 + .../electron_main_modules/MongoDbClient.js | 49 + .../electron_main_modules/MongoDbRouter.js | 47 + .../electron_main_modules/PythonApiRunner.js | 26 + 1_ActivityWatchProducer/index.html | 49 +- .../lib/{AwUpdateFlowControl => }/AwClient.js | 39 +- .../AwUpdateFlowControl/AwClient_BACKUP.js | 260 - .../lib/AwUpdateFlowControl/jsap.js | 37 - .../lib/PacFactoryJs/GregLogs.js | 17 +- .../gregnet-grid-script.js | 106 - .../gregnet-grid-style.css | 139 - .../lib/gregnet-grid-plugin/readme.txt | 33 - .../superset-embed.js | 16 +- 1_ActivityWatchProducer/main.js | 301 +- .../node_modules/.package-lock.json | 143 +- .../@types/webidl-conversions/LICENSE | 21 + .../@types/webidl-conversions/README.md | 16 + .../@types/webidl-conversions/index.d.ts | 97 + .../@types/webidl-conversions/package.json | 30 + .../node_modules/@types/whatwg-url/LICENSE | 21 + .../node_modules/@types/whatwg-url/README.md | 16 + .../@types/whatwg-url/dist/URL-impl.d.ts | 23 + .../@types/whatwg-url/dist/URL.d.ts | 76 + .../whatwg-url/dist/URLSearchParams-impl.d.ts | 23 + .../whatwg-url/dist/URLSearchParams.d.ts | 91 + .../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/bson/LICENSE.md | 201 + .../node_modules/bson/README.md | 368 + .../node_modules/bson/bson.d.ts | 1225 ++++ .../node_modules/bson/etc/prepare.js | 19 + .../node_modules/bson/lib/bson.bundle.js | 4090 +++++++++++ .../node_modules/bson/lib/bson.bundle.js.map | 1 + .../node_modules/bson/lib/bson.cjs | 4085 +++++++++++ .../node_modules/bson/lib/bson.cjs.map | 1 + .../node_modules/bson/lib/bson.mjs | 4057 +++++++++++ .../node_modules/bson/lib/bson.mjs.map | 1 + .../node_modules/bson/package.json | 115 + .../node_modules/bson/src/binary.ts | 485 ++ .../node_modules/bson/src/bson.ts | 250 + .../node_modules/bson/src/bson_value.ts | 18 + .../node_modules/bson/src/code.ts | 69 + .../node_modules/bson/src/constants.ts | 141 + .../node_modules/bson/src/db_ref.ts | 127 + .../node_modules/bson/src/decimal128.ts | 777 ++ .../node_modules/bson/src/double.ts | 83 + .../node_modules/bson/src/error.ts | 85 + .../node_modules/bson/src/extended_json.ts | 495 ++ .../node_modules/bson/src/index.ts | 19 + .../node_modules/bson/src/int_32.ts | 70 + .../node_modules/bson/src/long.ts | 1067 +++ .../node_modules/bson/src/max_key.ts | 36 + .../node_modules/bson/src/min_key.ts | 36 + .../node_modules/bson/src/objectid.ts | 317 + .../bson/src/parser/calculate_size.ts | 211 + .../bson/src/parser/deserializer.ts | 726 ++ .../bson/src/parser/serializer.ts | 988 +++ .../node_modules/bson/src/parser/utils.ts | 29 + .../node_modules/bson/src/regexp.ts | 114 + .../node_modules/bson/src/symbol.ts | 58 + .../node_modules/bson/src/timestamp.ts | 150 + .../node_modules/bson/src/utils/byte_utils.ts | 61 + .../bson/src/utils/node_byte_utils.ts | 141 + .../bson/src/utils/web_byte_utils.ts | 190 + .../node_modules/bson/src/uuid_utils.ts | 33 + .../node_modules/bson/src/validate_utf8.ts | 47 + .../node_modules/memory-pager/.travis.yml | 4 + .../node_modules/memory-pager/LICENSE | 21 + .../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 + .../.esm-wrapper.mjs | 6 + .../mongodb-connection-string-url/LICENSE | 192 + .../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 | 86 + .../lib/redact.js.map | 1 + .../package.json | 62 + .../node_modules/mongodb/LICENSE.md | 201 + .../node_modules/mongodb/README.md | 295 + .../node_modules/mongodb/etc/prepare.js | 12 + .../node_modules/mongodb/lib/admin.js | 131 + .../node_modules/mongodb/lib/admin.js.map | 1 + .../node_modules/mongodb/lib/bson.js | 61 + .../node_modules/mongodb/lib/bson.js.map | 1 + .../node_modules/mongodb/lib/bulk/common.js | 874 +++ .../mongodb/lib/bulk/common.js.map | 1 + .../node_modules/mongodb/lib/bulk/ordered.js | 67 + .../mongodb/lib/bulk/ordered.js.map | 1 + .../mongodb/lib/bulk/unordered.js | 92 + .../mongodb/lib/bulk/unordered.js.map | 1 + .../node_modules/mongodb/lib/change_stream.js | 397 ++ .../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 | 188 + .../mongodb/lib/cmap/auth/gssapi.js.map | 1 + .../lib/cmap/auth/mongo_credentials.js | 145 + .../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 | 238 + .../mongodb/lib/cmap/auth/mongodb_aws.js.map | 1 + .../mongodb/lib/cmap/auth/mongodb_oidc.js | 3 + .../mongodb/lib/cmap/auth/mongodb_oidc.js.map | 1 + .../mongodb/lib/cmap/auth/plain.js | 27 + .../mongodb/lib/cmap/auth/plain.js.map | 1 + .../mongodb/lib/cmap/auth/providers.js | 24 + .../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 | 242 + .../lib/cmap/command_monitoring_events.js.map | 1 + .../node_modules/mongodb/lib/cmap/commands.js | 487 ++ .../mongodb/lib/cmap/commands.js.map | 1 + .../node_modules/mongodb/lib/cmap/connect.js | 394 ++ .../mongodb/lib/cmap/connect.js.map | 1 + .../mongodb/lib/cmap/connection.js | 496 ++ .../mongodb/lib/cmap/connection.js.map | 1 + .../mongodb/lib/cmap/connection_pool.js | 591 ++ .../mongodb/lib/cmap/connection_pool.js.map | 1 + .../lib/cmap/connection_pool_events.js | 160 + .../lib/cmap/connection_pool_events.js.map | 1 + .../node_modules/mongodb/lib/cmap/errors.js | 64 + .../mongodb/lib/cmap/errors.js.map | 1 + .../mongodb/lib/cmap/message_stream.js | 156 + .../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 | 81 + .../lib/cmap/wire_protocol/compression.js.map | 1 + .../lib/cmap/wire_protocol/constants.js | 15 + .../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 | 576 ++ .../mongodb/lib/collection.js.map | 1 + .../mongodb/lib/connection_string.js | 1106 +++ .../mongodb/lib/connection_string.js.map | 1 + .../node_modules/mongodb/lib/constants.js | 131 + .../node_modules/mongodb/lib/constants.js.map | 1 + .../mongodb/lib/cursor/abstract_cursor.js | 678 ++ .../mongodb/lib/cursor/abstract_cursor.js.map | 1 + .../mongodb/lib/cursor/aggregation_cursor.js | 168 + .../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 | 381 + .../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 | 349 + .../node_modules/mongodb/lib/db.js.map | 1 + .../node_modules/mongodb/lib/deps.js | 69 + .../node_modules/mongodb/lib/deps.js.map | 1 + .../node_modules/mongodb/lib/encrypter.js | 103 + .../node_modules/mongodb/lib/encrypter.js.map | 1 + .../node_modules/mongodb/lib/error.js | 801 +++ .../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/download.js | 313 + .../mongodb/lib/gridfs/download.js.map | 1 + .../node_modules/mongodb/lib/gridfs/index.js | 128 + .../mongodb/lib/gridfs/index.js.map | 1 + .../node_modules/mongodb/lib/gridfs/upload.js | 342 + .../mongodb/lib/gridfs/upload.js.map | 1 + .../node_modules/mongodb/lib/index.js | 161 + .../node_modules/mongodb/lib/index.js.map | 1 + .../node_modules/mongodb/lib/mongo_client.js | 292 + .../mongodb/lib/mongo_client.js.map | 1 + .../node_modules/mongodb/lib/mongo_logger.js | 113 + .../mongodb/lib/mongo_logger.js.map | 1 + .../node_modules/mongodb/lib/mongo_types.js | 17 + .../mongodb/lib/mongo_types.js.map | 1 + .../mongodb/lib/operations/add_user.js | 74 + .../mongodb/lib/operations/add_user.js.map | 1 + .../mongodb/lib/operations/aggregate.js | 91 + .../mongodb/lib/operations/aggregate.js.map | 1 + .../mongodb/lib/operations/bulk_write.js | 36 + .../mongodb/lib/operations/bulk_write.js.map | 1 + .../mongodb/lib/operations/collections.js | 32 + .../mongodb/lib/operations/collections.js.map | 1 + .../mongodb/lib/operations/command.js | 78 + .../mongodb/lib/operations/command.js.map | 1 + .../lib/operations/common_functions.js | 69 + .../lib/operations/common_functions.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 | 101 + .../lib/operations/create_collection.js.map | 1 + .../mongodb/lib/operations/delete.js | 119 + .../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 | 83 + .../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 | 181 + .../lib/operations/execute_operation.js.map | 1 + .../mongodb/lib/operations/find.js | 156 + .../mongodb/lib/operations/find.js.map | 1 + .../mongodb/lib/operations/find_and_modify.js | 151 + .../lib/operations/find_and_modify.js.map | 1 + .../mongodb/lib/operations/get_more.js | 58 + .../mongodb/lib/operations/get_more.js.map | 1 + .../mongodb/lib/operations/indexes.js | 270 + .../mongodb/lib/operations/indexes.js.map | 1 + .../mongodb/lib/operations/insert.js | 95 + .../mongodb/lib/operations/insert.js.map | 1 + .../mongodb/lib/operations/is_capped.js | 28 + .../mongodb/lib/operations/is_capped.js.map | 1 + .../mongodb/lib/operations/kill_cursors.js | 32 + .../lib/operations/kill_cursors.js.map | 1 + .../lib/operations/list_collections.js | 47 + .../lib/operations/list_collections.js.map | 1 + .../mongodb/lib/operations/list_databases.js | 35 + .../lib/operations/list_databases.js.map | 1 + .../mongodb/lib/operations/operation.js | 73 + .../mongodb/lib/operations/operation.js.map | 1 + .../lib/operations/options_operation.js | 28 + .../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 | 183 + .../mongodb/lib/operations/update.js.map | 1 + .../lib/operations/validate_collection.js | 41 + .../lib/operations/validate_collection.js.map | 1 + .../node_modules/mongodb/lib/read_concern.js | 73 + .../mongodb/lib/read_concern.js.map | 1 + .../mongodb/lib/read_preference.js | 195 + .../mongodb/lib/read_preference.js.map | 1 + .../node_modules/mongodb/lib/sdam/common.js | 56 + .../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 | 417 ++ .../mongodb/lib/sdam/monitor.js.map | 1 + .../node_modules/mongodb/lib/sdam/server.js | 369 + .../mongodb/lib/sdam/server.js.map | 1 + .../mongodb/lib/sdam/server_description.js | 189 + .../lib/sdam/server_description.js.map | 1 + .../mongodb/lib/sdam/server_selection.js | 226 + .../mongodb/lib/sdam/server_selection.js.map | 1 + .../mongodb/lib/sdam/srv_polling.js | 117 + .../mongodb/lib/sdam/srv_polling.js.map | 1 + .../node_modules/mongodb/lib/sdam/topology.js | 636 ++ .../mongodb/lib/sdam/topology.js.map | 1 + .../mongodb/lib/sdam/topology_description.js | 360 + .../lib/sdam/topology_description.js.map | 1 + .../node_modules/mongodb/lib/sessions.js | 738 ++ .../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/transactions.js | 138 + .../mongodb/lib/transactions.js.map | 1 + .../node_modules/mongodb/lib/utils.js | 1055 +++ .../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 | 6239 +++++++++++++++++ .../node_modules/mongodb/package.json | 156 + .../node_modules/mongodb/src/admin.ts | 174 + .../node_modules/mongodb/src/bson.ts | 117 + .../node_modules/mongodb/src/bulk/common.ts | 1282 ++++ .../node_modules/mongodb/src/bulk/ordered.ts | 83 + .../mongodb/src/bulk/unordered.ts | 110 + .../node_modules/mongodb/src/change_stream.ts | 958 +++ .../mongodb/src/cmap/auth/auth_provider.ts | 60 + .../mongodb/src/cmap/auth/gssapi.ts | 239 + .../src/cmap/auth/mongo_credentials.ts | 236 + .../mongodb/src/cmap/auth/mongocr.ts | 47 + .../mongodb/src/cmap/auth/mongodb_aws.ts | 336 + .../mongodb/src/cmap/auth/mongodb_oidc.ts | 39 + .../mongodb/src/cmap/auth/plain.ts | 25 + .../mongodb/src/cmap/auth/providers.ts | 24 + .../mongodb/src/cmap/auth/scram.ts | 384 + .../mongodb/src/cmap/auth/x509.ts | 53 + .../src/cmap/command_monitoring_events.ts | 301 + .../node_modules/mongodb/src/cmap/commands.ts | 712 ++ .../node_modules/mongodb/src/cmap/connect.ts | 523 ++ .../mongodb/src/cmap/connection.ts | 743 ++ .../mongodb/src/cmap/connection_pool.ts | 841 +++ .../src/cmap/connection_pool_events.ts | 201 + .../node_modules/mongodb/src/cmap/errors.ts | 75 + .../mongodb/src/cmap/message_stream.ts | 230 + .../node_modules/mongodb/src/cmap/metrics.ts | 58 + .../mongodb/src/cmap/stream_description.ts | 76 + .../src/cmap/wire_protocol/compression.ts | 104 + .../src/cmap/wire_protocol/constants.ts | 11 + .../mongodb/src/cmap/wire_protocol/shared.ts | 76 + .../node_modules/mongodb/src/collection.ts | 983 +++ .../mongodb/src/connection_string.ts | 1301 ++++ .../node_modules/mongodb/src/constants.ts | 136 + .../mongodb/src/cursor/abstract_cursor.ts | 927 +++ .../mongodb/src/cursor/aggregation_cursor.ts | 208 + .../src/cursor/change_stream_cursor.ts | 194 + .../mongodb/src/cursor/find_cursor.ts | 456 ++ .../src/cursor/list_collections_cursor.ts | 52 + .../mongodb/src/cursor/list_indexes_cursor.ts | 41 + .../node_modules/mongodb/src/db.ts | 524 ++ .../node_modules/mongodb/src/deps.ts | 394 ++ .../node_modules/mongodb/src/encrypter.ts | 131 + .../node_modules/mongodb/src/error.ts | 932 +++ .../node_modules/mongodb/src/explain.ts | 52 + .../mongodb/src/gridfs/download.ts | 474 ++ .../node_modules/mongodb/src/gridfs/index.ts | 209 + .../node_modules/mongodb/src/gridfs/upload.ts | 523 ++ .../node_modules/mongodb/src/index.ts | 472 ++ .../node_modules/mongodb/src/mongo_client.ts | 729 ++ .../node_modules/mongodb/src/mongo_logger.ts | 201 + .../node_modules/mongodb/src/mongo_types.ts | 561 ++ .../mongodb/src/operations/add_user.ts | 118 + .../mongodb/src/operations/aggregate.ts | 144 + .../mongodb/src/operations/bulk_write.ts | 62 + .../mongodb/src/operations/collections.ts | 50 + .../mongodb/src/operations/command.ts | 159 + .../src/operations/common_functions.ts | 105 + .../mongodb/src/operations/count.ts | 68 + .../mongodb/src/operations/count_documents.ts | 57 + .../src/operations/create_collection.ts | 201 + .../mongodb/src/operations/delete.ts | 174 + .../mongodb/src/operations/distinct.ts | 90 + .../mongodb/src/operations/drop.ts | 120 + .../operations/estimated_document_count.ts | 62 + .../mongodb/src/operations/eval.ts | 82 + .../src/operations/execute_operation.ts | 287 + .../mongodb/src/operations/find.ts | 272 + .../mongodb/src/operations/find_and_modify.ts | 286 + .../mongodb/src/operations/get_more.ts | 106 + .../mongodb/src/operations/indexes.ts | 518 ++ .../mongodb/src/operations/insert.ts | 158 + .../mongodb/src/operations/is_capped.ts | 44 + .../mongodb/src/operations/kill_cursors.ts | 53 + .../src/operations/list_collections.ts | 99 + .../mongodb/src/operations/list_databases.ts | 65 + .../mongodb/src/operations/operation.ts | 139 + .../src/operations/options_operation.ts | 45 + .../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 | 306 + .../src/operations/validate_collection.ts | 59 + .../node_modules/mongodb/src/read_concern.ts | 88 + .../mongodb/src/read_preference.ts | 262 + .../node_modules/mongodb/src/sdam/common.ts | 79 + .../node_modules/mongodb/src/sdam/events.ts | 182 + .../node_modules/mongodb/src/sdam/monitor.ts | 595 ++ .../node_modules/mongodb/src/sdam/server.ts | 563 ++ .../mongodb/src/sdam/server_description.ts | 262 + .../mongodb/src/sdam/server_selection.ts | 324 + .../mongodb/src/sdam/srv_polling.ts | 157 + .../node_modules/mongodb/src/sdam/topology.ts | 1011 +++ .../mongodb/src/sdam/topology_description.ts | 511 ++ .../node_modules/mongodb/src/sessions.ts | 1044 +++ .../node_modules/mongodb/src/sort.ts | 132 + .../node_modules/mongodb/src/transactions.ts | 188 + .../node_modules/mongodb/src/utils.ts | 1353 ++++ .../node_modules/mongodb/src/write_concern.ts | 114 + .../node_modules/mongodb/tsconfig.json | 46 + .../node_modules/punycode/LICENSE-MIT.txt | 20 + .../node_modules/punycode/README.md | 126 + .../node_modules/punycode/package.json | 58 + .../node_modules/punycode/punycode.es6.js | 444 ++ .../node_modules/punycode/punycode.js | 443 ++ .../node_modules/saslprep/.editorconfig | 10 + .../node_modules/saslprep/.gitattributes | 1 + .../node_modules/saslprep/.travis.yml | 10 + .../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 + .../socks/build/client/socksclient.js | 8 +- .../socks/build/client/socksclient.js.map | 2 +- .../node_modules/socks/package.json | 2 +- .../node_modules/sparse-bitfield/.npmignore | 1 + .../node_modules/sparse-bitfield/.travis.yml | 6 + .../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/tr46/LICENSE.md | 21 + .../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 + .../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 + 1_ActivityWatchProducer/package-lock.json | 252 +- 1_ActivityWatchProducer/package.json | 3 +- 2_PAC/Apps/OpAdapter.js | 11 +- .../PacFactory/MongoDbClient.js | 65 + .../PacFactory/OpenProjectClient.js | 10 + .../PacFactory/SupersetClient.js | 35 + 2_PAC/node_modules/.package-lock.json | 1981 +++++- 2_PAC/node_modules/@types/node/LICENSE | 21 + 2_PAC/node_modules/@types/node/README.md | 16 + 2_PAC/node_modules/@types/node/assert.d.ts | 961 +++ .../@types/node/assert/strict.d.ts | 8 + .../node_modules/@types/node/async_hooks.d.ts | 513 ++ 2_PAC/node_modules/@types/node/buffer.d.ts | 2258 ++++++ .../@types/node/child_process.d.ts | 1369 ++++ 2_PAC/node_modules/@types/node/cluster.d.ts | 410 ++ 2_PAC/node_modules/@types/node/console.d.ts | 412 ++ 2_PAC/node_modules/@types/node/constants.d.ts | 18 + 2_PAC/node_modules/@types/node/crypto.d.ts | 3964 +++++++++++ 2_PAC/node_modules/@types/node/dgram.d.ts | 545 ++ .../@types/node/diagnostics_channel.d.ts | 153 + 2_PAC/node_modules/@types/node/dns.d.ts | 659 ++ .../@types/node/dns/promises.d.ts | 370 + .../node_modules/@types/node/dom-events.d.ts | 126 + 2_PAC/node_modules/@types/node/domain.d.ts | 170 + 2_PAC/node_modules/@types/node/events.d.ts | 678 ++ 2_PAC/node_modules/@types/node/fs.d.ts | 3872 ++++++++++ .../node_modules/@types/node/fs/promises.d.ts | 1138 +++ 2_PAC/node_modules/@types/node/globals.d.ts | 300 + .../@types/node/globals.global.d.ts | 1 + 2_PAC/node_modules/@types/node/http.d.ts | 1651 +++++ 2_PAC/node_modules/@types/node/http2.d.ts | 2134 ++++++ 2_PAC/node_modules/@types/node/https.d.ts | 542 ++ 2_PAC/node_modules/@types/node/index.d.ts | 134 + 2_PAC/node_modules/@types/node/inspector.d.ts | 2741 ++++++++ 2_PAC/node_modules/@types/node/module.d.ts | 115 + 2_PAC/node_modules/@types/node/net.d.ts | 877 +++ 2_PAC/node_modules/@types/node/os.d.ts | 466 ++ 2_PAC/node_modules/@types/node/package.json | 237 + 2_PAC/node_modules/@types/node/path.d.ts | 191 + .../node_modules/@types/node/perf_hooks.d.ts | 625 ++ 2_PAC/node_modules/@types/node/process.d.ts | 1482 ++++ 2_PAC/node_modules/@types/node/punycode.d.ts | 117 + .../node_modules/@types/node/querystring.d.ts | 131 + 2_PAC/node_modules/@types/node/readline.d.ts | 653 ++ .../@types/node/readline/promises.d.ts | 143 + 2_PAC/node_modules/@types/node/repl.d.ts | 424 ++ 2_PAC/node_modules/@types/node/stream.d.ts | 1340 ++++ .../@types/node/stream/consumers.d.ts | 12 + .../@types/node/stream/promises.d.ts | 42 + .../node_modules/@types/node/stream/web.d.ts | 330 + .../@types/node/string_decoder.d.ts | 67 + 2_PAC/node_modules/@types/node/test.d.ts | 455 ++ 2_PAC/node_modules/@types/node/timers.d.ts | 94 + .../@types/node/timers/promises.d.ts | 93 + 2_PAC/node_modules/@types/node/tls.d.ts | 1107 +++ .../@types/node/trace_events.d.ts | 171 + .../@types/node/ts4.8/assert.d.ts | 961 +++ .../@types/node/ts4.8/assert/strict.d.ts | 8 + .../@types/node/ts4.8/async_hooks.d.ts | 513 ++ .../@types/node/ts4.8/buffer.d.ts | 2259 ++++++ .../@types/node/ts4.8/child_process.d.ts | 1369 ++++ .../@types/node/ts4.8/cluster.d.ts | 410 ++ .../@types/node/ts4.8/console.d.ts | 412 ++ .../@types/node/ts4.8/constants.d.ts | 18 + .../@types/node/ts4.8/crypto.d.ts | 3964 +++++++++++ .../node_modules/@types/node/ts4.8/dgram.d.ts | 545 ++ .../node/ts4.8/diagnostics_channel.d.ts | 153 + 2_PAC/node_modules/@types/node/ts4.8/dns.d.ts | 659 ++ .../@types/node/ts4.8/dns/promises.d.ts | 370 + .../@types/node/ts4.8/dom-events.d.ts | 126 + .../@types/node/ts4.8/domain.d.ts | 170 + .../@types/node/ts4.8/events.d.ts | 678 ++ 2_PAC/node_modules/@types/node/ts4.8/fs.d.ts | 3872 ++++++++++ .../@types/node/ts4.8/fs/promises.d.ts | 1138 +++ .../@types/node/ts4.8/globals.d.ts | 294 + .../@types/node/ts4.8/globals.global.d.ts | 1 + .../node_modules/@types/node/ts4.8/http.d.ts | 1651 +++++ .../node_modules/@types/node/ts4.8/http2.d.ts | 2134 ++++++ .../node_modules/@types/node/ts4.8/https.d.ts | 542 ++ .../node_modules/@types/node/ts4.8/index.d.ts | 88 + .../@types/node/ts4.8/inspector.d.ts | 2741 ++++++++ .../@types/node/ts4.8/module.d.ts | 115 + 2_PAC/node_modules/@types/node/ts4.8/net.d.ts | 877 +++ 2_PAC/node_modules/@types/node/ts4.8/os.d.ts | 466 ++ .../node_modules/@types/node/ts4.8/path.d.ts | 191 + .../@types/node/ts4.8/perf_hooks.d.ts | 625 ++ .../@types/node/ts4.8/process.d.ts | 1482 ++++ .../@types/node/ts4.8/punycode.d.ts | 117 + .../@types/node/ts4.8/querystring.d.ts | 131 + .../@types/node/ts4.8/readline.d.ts | 653 ++ .../@types/node/ts4.8/readline/promises.d.ts | 143 + .../node_modules/@types/node/ts4.8/repl.d.ts | 424 ++ .../@types/node/ts4.8/stream.d.ts | 1340 ++++ .../@types/node/ts4.8/stream/consumers.d.ts | 12 + .../@types/node/ts4.8/stream/promises.d.ts | 42 + .../@types/node/ts4.8/stream/web.d.ts | 330 + .../@types/node/ts4.8/string_decoder.d.ts | 67 + .../node_modules/@types/node/ts4.8/test.d.ts | 446 ++ .../@types/node/ts4.8/timers.d.ts | 94 + .../@types/node/ts4.8/timers/promises.d.ts | 93 + 2_PAC/node_modules/@types/node/ts4.8/tls.d.ts | 1107 +++ .../@types/node/ts4.8/trace_events.d.ts | 171 + 2_PAC/node_modules/@types/node/ts4.8/tty.d.ts | 206 + 2_PAC/node_modules/@types/node/ts4.8/url.d.ts | 897 +++ .../node_modules/@types/node/ts4.8/util.d.ts | 2011 ++++++ 2_PAC/node_modules/@types/node/ts4.8/v8.d.ts | 396 ++ 2_PAC/node_modules/@types/node/ts4.8/vm.d.ts | 509 ++ .../node_modules/@types/node/ts4.8/wasi.d.ts | 158 + .../@types/node/ts4.8/worker_threads.d.ts | 689 ++ .../node_modules/@types/node/ts4.8/zlib.d.ts | 517 ++ 2_PAC/node_modules/@types/node/tty.d.ts | 206 + 2_PAC/node_modules/@types/node/url.d.ts | 897 +++ 2_PAC/node_modules/@types/node/util.d.ts | 2011 ++++++ 2_PAC/node_modules/@types/node/v8.d.ts | 396 ++ 2_PAC/node_modules/@types/node/vm.d.ts | 509 ++ 2_PAC/node_modules/@types/node/wasi.d.ts | 158 + .../@types/node/worker_threads.d.ts | 689 ++ 2_PAC/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 | 97 + .../@types/webidl-conversions/package.json | 30 + 2_PAC/node_modules/@types/whatwg-url/LICENSE | 21 + .../node_modules/@types/whatwg-url/README.md | 16 + .../@types/whatwg-url/dist/URL-impl.d.ts | 23 + .../@types/whatwg-url/dist/URL.d.ts | 76 + .../whatwg-url/dist/URLSearchParams-impl.d.ts | 23 + .../whatwg-url/dist/URLSearchParams.d.ts | 91 + .../node_modules/@types/whatwg-url/index.d.ts | 162 + .../@types/whatwg-url/package.json | 33 + .../@types/whatwg-url/webidl2js-wrapper.d.ts | 4 + 2_PAC/node_modules/bson/LICENSE.md | 201 + 2_PAC/node_modules/bson/README.md | 368 + 2_PAC/node_modules/bson/bson.d.ts | 1204 ++++ 2_PAC/node_modules/bson/etc/prepare.js | 19 + 2_PAC/node_modules/bson/lib/bson.bundle.js | 4072 +++++++++++ .../node_modules/bson/lib/bson.bundle.js.map | 1 + 2_PAC/node_modules/bson/lib/bson.cjs | 4067 +++++++++++ 2_PAC/node_modules/bson/lib/bson.cjs.map | 1 + 2_PAC/node_modules/bson/lib/bson.mjs | 4040 +++++++++++ 2_PAC/node_modules/bson/lib/bson.mjs.map | 1 + 2_PAC/node_modules/bson/package.json | 103 + 2_PAC/node_modules/bson/src/binary.ts | 485 ++ 2_PAC/node_modules/bson/src/bson.ts | 250 + 2_PAC/node_modules/bson/src/bson_value.ts | 18 + 2_PAC/node_modules/bson/src/code.ts | 69 + 2_PAC/node_modules/bson/src/constants.ts | 141 + 2_PAC/node_modules/bson/src/db_ref.ts | 127 + 2_PAC/node_modules/bson/src/decimal128.ts | 777 ++ 2_PAC/node_modules/bson/src/double.ts | 83 + 2_PAC/node_modules/bson/src/error.ts | 60 + 2_PAC/node_modules/bson/src/extended_json.ts | 488 ++ 2_PAC/node_modules/bson/src/index.ts | 19 + 2_PAC/node_modules/bson/src/int_32.ts | 70 + 2_PAC/node_modules/bson/src/long.ts | 1064 +++ 2_PAC/node_modules/bson/src/max_key.ts | 36 + 2_PAC/node_modules/bson/src/min_key.ts | 36 + 2_PAC/node_modules/bson/src/objectid.ts | 317 + .../bson/src/parser/calculate_size.ts | 211 + .../bson/src/parser/deserializer.ts | 726 ++ .../bson/src/parser/serializer.ts | 988 +++ 2_PAC/node_modules/bson/src/parser/utils.ts | 29 + 2_PAC/node_modules/bson/src/regexp.ts | 114 + 2_PAC/node_modules/bson/src/symbol.ts | 58 + 2_PAC/node_modules/bson/src/timestamp.ts | 150 + .../node_modules/bson/src/utils/byte_utils.ts | 61 + .../bson/src/utils/node_byte_utils.ts | 141 + .../bson/src/utils/web_byte_utils.ts | 190 + 2_PAC/node_modules/bson/src/uuid_utils.ts | 33 + 2_PAC/node_modules/bson/src/validate_utf8.ts | 47 + 2_PAC/node_modules/ip/README.md | 90 + 2_PAC/node_modules/ip/lib/ip.js | 422 ++ 2_PAC/node_modules/ip/package.json | 25 + 2_PAC/node_modules/memory-pager/.travis.yml | 4 + 2_PAC/node_modules/memory-pager/LICENSE | 21 + 2_PAC/node_modules/memory-pager/README.md | 65 + 2_PAC/node_modules/memory-pager/index.js | 160 + 2_PAC/node_modules/memory-pager/package.json | 24 + 2_PAC/node_modules/memory-pager/test.js | 80 + .../.esm-wrapper.mjs | 6 + .../mongodb-connection-string-url/LICENSE | 192 + .../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 | 86 + .../lib/redact.js.map | 1 + .../node_modules/tr46/LICENSE.md | 21 + .../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 + .../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 + .../package.json | 62 + 2_PAC/node_modules/mongodb/LICENSE.md | 201 + 2_PAC/node_modules/mongodb/README.md | 295 + 2_PAC/node_modules/mongodb/etc/prepare.js | 12 + 2_PAC/node_modules/mongodb/lib/admin.js | 131 + 2_PAC/node_modules/mongodb/lib/admin.js.map | 1 + 2_PAC/node_modules/mongodb/lib/bson.js | 59 + 2_PAC/node_modules/mongodb/lib/bson.js.map | 1 + 2_PAC/node_modules/mongodb/lib/bulk/common.js | 874 +++ .../mongodb/lib/bulk/common.js.map | 1 + .../node_modules/mongodb/lib/bulk/ordered.js | 67 + .../mongodb/lib/bulk/ordered.js.map | 1 + .../mongodb/lib/bulk/unordered.js | 92 + .../mongodb/lib/bulk/unordered.js.map | 1 + .../node_modules/mongodb/lib/change_stream.js | 396 ++ .../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 | 188 + .../mongodb/lib/cmap/auth/gssapi.js.map | 1 + .../lib/cmap/auth/mongo_credentials.js | 126 + .../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 | 237 + .../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 | 242 + .../lib/cmap/command_monitoring_events.js.map | 1 + .../node_modules/mongodb/lib/cmap/commands.js | 479 ++ .../mongodb/lib/cmap/commands.js.map | 1 + .../node_modules/mongodb/lib/cmap/connect.js | 394 ++ .../mongodb/lib/cmap/connect.js.map | 1 + .../mongodb/lib/cmap/connection.js | 498 ++ .../mongodb/lib/cmap/connection.js.map | 1 + .../mongodb/lib/cmap/connection_pool.js | 591 ++ .../mongodb/lib/cmap/connection_pool.js.map | 1 + .../lib/cmap/connection_pool_events.js | 160 + .../lib/cmap/connection_pool_events.js.map | 1 + 2_PAC/node_modules/mongodb/lib/cmap/errors.js | 64 + .../mongodb/lib/cmap/errors.js.map | 1 + .../mongodb/lib/cmap/message_stream.js | 156 + .../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 | 81 + .../lib/cmap/wire_protocol/compression.js.map | 1 + .../lib/cmap/wire_protocol/constants.js | 15 + .../lib/cmap/wire_protocol/constants.js.map | 1 + .../mongodb/lib/cmap/wire_protocol/shared.js | 55 + .../lib/cmap/wire_protocol/shared.js.map | 1 + 2_PAC/node_modules/mongodb/lib/collection.js | 576 ++ .../mongodb/lib/collection.js.map | 1 + .../mongodb/lib/connection_string.js | 1086 +++ .../mongodb/lib/connection_string.js.map | 1 + 2_PAC/node_modules/mongodb/lib/constants.js | 131 + .../node_modules/mongodb/lib/constants.js.map | 1 + .../mongodb/lib/cursor/abstract_cursor.js | 672 ++ .../mongodb/lib/cursor/abstract_cursor.js.map | 1 + .../mongodb/lib/cursor/aggregation_cursor.js | 168 + .../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 | 381 + .../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 + 2_PAC/node_modules/mongodb/lib/db.js | 348 + 2_PAC/node_modules/mongodb/lib/db.js.map | 1 + 2_PAC/node_modules/mongodb/lib/deps.js | 69 + 2_PAC/node_modules/mongodb/lib/deps.js.map | 1 + 2_PAC/node_modules/mongodb/lib/encrypter.js | 103 + .../node_modules/mongodb/lib/encrypter.js.map | 1 + 2_PAC/node_modules/mongodb/lib/error.js | 801 +++ 2_PAC/node_modules/mongodb/lib/error.js.map | 1 + 2_PAC/node_modules/mongodb/lib/explain.js | 35 + 2_PAC/node_modules/mongodb/lib/explain.js.map | 1 + .../mongodb/lib/gridfs/download.js | 313 + .../mongodb/lib/gridfs/download.js.map | 1 + .../node_modules/mongodb/lib/gridfs/index.js | 128 + .../mongodb/lib/gridfs/index.js.map | 1 + .../node_modules/mongodb/lib/gridfs/upload.js | 342 + .../mongodb/lib/gridfs/upload.js.map | 1 + 2_PAC/node_modules/mongodb/lib/index.js | 161 + 2_PAC/node_modules/mongodb/lib/index.js.map | 1 + .../node_modules/mongodb/lib/mongo_client.js | 292 + .../mongodb/lib/mongo_client.js.map | 1 + .../node_modules/mongodb/lib/mongo_logger.js | 113 + .../mongodb/lib/mongo_logger.js.map | 1 + 2_PAC/node_modules/mongodb/lib/mongo_types.js | 17 + .../mongodb/lib/mongo_types.js.map | 1 + .../mongodb/lib/operations/add_user.js | 74 + .../mongodb/lib/operations/add_user.js.map | 1 + .../mongodb/lib/operations/aggregate.js | 88 + .../mongodb/lib/operations/aggregate.js.map | 1 + .../mongodb/lib/operations/bulk_write.js | 36 + .../mongodb/lib/operations/bulk_write.js.map | 1 + .../mongodb/lib/operations/collections.js | 32 + .../mongodb/lib/operations/collections.js.map | 1 + .../mongodb/lib/operations/command.js | 78 + .../mongodb/lib/operations/command.js.map | 1 + .../lib/operations/common_functions.js | 69 + .../lib/operations/common_functions.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 | 119 + .../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 | 83 + .../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 | 181 + .../lib/operations/execute_operation.js.map | 1 + .../mongodb/lib/operations/find.js | 155 + .../mongodb/lib/operations/find.js.map | 1 + .../mongodb/lib/operations/find_and_modify.js | 151 + .../lib/operations/find_and_modify.js.map | 1 + .../mongodb/lib/operations/get_more.js | 58 + .../mongodb/lib/operations/get_more.js.map | 1 + .../mongodb/lib/operations/indexes.js | 269 + .../mongodb/lib/operations/indexes.js.map | 1 + .../mongodb/lib/operations/insert.js | 95 + .../mongodb/lib/operations/insert.js.map | 1 + .../mongodb/lib/operations/is_capped.js | 28 + .../mongodb/lib/operations/is_capped.js.map | 1 + .../mongodb/lib/operations/kill_cursors.js | 32 + .../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/operation.js | 73 + .../mongodb/lib/operations/operation.js.map | 1 + .../lib/operations/options_operation.js | 28 + .../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 | 183 + .../mongodb/lib/operations/update.js.map | 1 + .../lib/operations/validate_collection.js | 41 + .../lib/operations/validate_collection.js.map | 1 + .../node_modules/mongodb/lib/read_concern.js | 73 + .../mongodb/lib/read_concern.js.map | 1 + .../mongodb/lib/read_preference.js | 195 + .../mongodb/lib/read_preference.js.map | 1 + 2_PAC/node_modules/mongodb/lib/sdam/common.js | 56 + .../mongodb/lib/sdam/common.js.map | 1 + 2_PAC/node_modules/mongodb/lib/sdam/events.js | 125 + .../mongodb/lib/sdam/events.js.map | 1 + .../node_modules/mongodb/lib/sdam/monitor.js | 416 ++ .../mongodb/lib/sdam/monitor.js.map | 1 + 2_PAC/node_modules/mongodb/lib/sdam/server.js | 367 + .../mongodb/lib/sdam/server.js.map | 1 + .../mongodb/lib/sdam/server_description.js | 189 + .../lib/sdam/server_description.js.map | 1 + .../mongodb/lib/sdam/server_selection.js | 226 + .../mongodb/lib/sdam/server_selection.js.map | 1 + .../mongodb/lib/sdam/srv_polling.js | 117 + .../mongodb/lib/sdam/srv_polling.js.map | 1 + .../node_modules/mongodb/lib/sdam/topology.js | 643 ++ .../mongodb/lib/sdam/topology.js.map | 1 + .../mongodb/lib/sdam/topology_description.js | 360 + .../lib/sdam/topology_description.js.map | 1 + 2_PAC/node_modules/mongodb/lib/sessions.js | 737 ++ .../node_modules/mongodb/lib/sessions.js.map | 1 + 2_PAC/node_modules/mongodb/lib/sort.js | 97 + 2_PAC/node_modules/mongodb/lib/sort.js.map | 1 + .../node_modules/mongodb/lib/transactions.js | 138 + .../mongodb/lib/transactions.js.map | 1 + 2_PAC/node_modules/mongodb/lib/utils.js | 1055 +++ 2_PAC/node_modules/mongodb/lib/utils.js.map | 1 + .../node_modules/mongodb/lib/write_concern.js | 71 + .../mongodb/lib/write_concern.js.map | 1 + 2_PAC/node_modules/mongodb/mongodb.d.ts | 6203 ++++++++++++++++ 2_PAC/node_modules/mongodb/package.json | 155 + 2_PAC/node_modules/mongodb/src/admin.ts | 174 + 2_PAC/node_modules/mongodb/src/bson.ts | 115 + 2_PAC/node_modules/mongodb/src/bulk/common.ts | 1282 ++++ .../node_modules/mongodb/src/bulk/ordered.ts | 83 + .../mongodb/src/bulk/unordered.ts | 110 + .../node_modules/mongodb/src/change_stream.ts | 950 +++ .../mongodb/src/cmap/auth/auth_provider.ts | 60 + .../mongodb/src/cmap/auth/gssapi.ts | 239 + .../src/cmap/auth/mongo_credentials.ts | 181 + .../mongodb/src/cmap/auth/mongocr.ts | 47 + .../mongodb/src/cmap/auth/mongodb_aws.ts | 335 + .../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 | 301 + .../node_modules/mongodb/src/cmap/commands.ts | 702 ++ .../node_modules/mongodb/src/cmap/connect.ts | 523 ++ .../mongodb/src/cmap/connection.ts | 753 ++ .../mongodb/src/cmap/connection_pool.ts | 841 +++ .../src/cmap/connection_pool_events.ts | 201 + 2_PAC/node_modules/mongodb/src/cmap/errors.ts | 75 + .../mongodb/src/cmap/message_stream.ts | 230 + .../node_modules/mongodb/src/cmap/metrics.ts | 58 + .../mongodb/src/cmap/stream_description.ts | 76 + .../src/cmap/wire_protocol/compression.ts | 104 + .../src/cmap/wire_protocol/constants.ts | 11 + .../mongodb/src/cmap/wire_protocol/shared.ts | 76 + 2_PAC/node_modules/mongodb/src/collection.ts | 983 +++ .../mongodb/src/connection_string.ts | 1279 ++++ 2_PAC/node_modules/mongodb/src/constants.ts | 136 + .../mongodb/src/cursor/abstract_cursor.ts | 920 +++ .../mongodb/src/cursor/aggregation_cursor.ts | 208 + .../src/cursor/change_stream_cursor.ts | 194 + .../mongodb/src/cursor/find_cursor.ts | 456 ++ .../src/cursor/list_collections_cursor.ts | 52 + .../mongodb/src/cursor/list_indexes_cursor.ts | 41 + 2_PAC/node_modules/mongodb/src/db.ts | 523 ++ 2_PAC/node_modules/mongodb/src/deps.ts | 377 + 2_PAC/node_modules/mongodb/src/encrypter.ts | 131 + 2_PAC/node_modules/mongodb/src/error.ts | 932 +++ 2_PAC/node_modules/mongodb/src/explain.ts | 52 + .../mongodb/src/gridfs/download.ts | 474 ++ .../node_modules/mongodb/src/gridfs/index.ts | 209 + .../node_modules/mongodb/src/gridfs/upload.ts | 523 ++ 2_PAC/node_modules/mongodb/src/index.ts | 466 ++ .../node_modules/mongodb/src/mongo_client.ts | 729 ++ .../node_modules/mongodb/src/mongo_logger.ts | 201 + 2_PAC/node_modules/mongodb/src/mongo_types.ts | 560 ++ .../mongodb/src/operations/add_user.ts | 118 + .../mongodb/src/operations/aggregate.ts | 142 + .../mongodb/src/operations/bulk_write.ts | 62 + .../mongodb/src/operations/collections.ts | 50 + .../mongodb/src/operations/command.ts | 159 + .../src/operations/common_functions.ts | 105 + .../mongodb/src/operations/count.ts | 68 + .../mongodb/src/operations/count_documents.ts | 57 + .../src/operations/create_collection.ts | 200 + .../mongodb/src/operations/delete.ts | 174 + .../mongodb/src/operations/distinct.ts | 90 + .../mongodb/src/operations/drop.ts | 120 + .../operations/estimated_document_count.ts | 62 + .../mongodb/src/operations/eval.ts | 82 + .../src/operations/execute_operation.ts | 287 + .../mongodb/src/operations/find.ts | 263 + .../mongodb/src/operations/find_and_modify.ts | 286 + .../mongodb/src/operations/get_more.ts | 106 + .../mongodb/src/operations/indexes.ts | 510 ++ .../mongodb/src/operations/insert.ts | 158 + .../mongodb/src/operations/is_capped.ts | 44 + .../mongodb/src/operations/kill_cursors.ts | 53 + .../src/operations/list_collections.ts | 91 + .../mongodb/src/operations/list_databases.ts | 65 + .../mongodb/src/operations/operation.ts | 139 + .../src/operations/options_operation.ts | 45 + .../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 | 306 + .../src/operations/validate_collection.ts | 59 + .../node_modules/mongodb/src/read_concern.ts | 88 + .../mongodb/src/read_preference.ts | 262 + 2_PAC/node_modules/mongodb/src/sdam/common.ts | 79 + 2_PAC/node_modules/mongodb/src/sdam/events.ts | 182 + .../node_modules/mongodb/src/sdam/monitor.ts | 594 ++ 2_PAC/node_modules/mongodb/src/sdam/server.ts | 560 ++ .../mongodb/src/sdam/server_description.ts | 262 + .../mongodb/src/sdam/server_selection.ts | 324 + .../mongodb/src/sdam/srv_polling.ts | 157 + .../node_modules/mongodb/src/sdam/topology.ts | 1020 +++ .../mongodb/src/sdam/topology_description.ts | 511 ++ 2_PAC/node_modules/mongodb/src/sessions.ts | 1043 +++ 2_PAC/node_modules/mongodb/src/sort.ts | 132 + .../node_modules/mongodb/src/transactions.ts | 188 + 2_PAC/node_modules/mongodb/src/utils.ts | 1353 ++++ .../node_modules/mongodb/src/write_concern.ts | 114 + 2_PAC/node_modules/mongodb/tsconfig.json | 46 + 2_PAC/node_modules/saslprep/.editorconfig | 10 + 2_PAC/node_modules/saslprep/.gitattributes | 1 + 2_PAC/node_modules/saslprep/.travis.yml | 10 + 2_PAC/node_modules/saslprep/CHANGELOG.md | 19 + 2_PAC/node_modules/saslprep/LICENSE | 22 + 2_PAC/node_modules/saslprep/code-points.mem | Bin 0 -> 419864 bytes .../saslprep/generate-code-points.js | 51 + 2_PAC/node_modules/saslprep/index.js | 157 + .../node_modules/saslprep/lib/code-points.js | 996 +++ .../saslprep/lib/memory-code-points.js | 39 + 2_PAC/node_modules/saslprep/lib/util.js | 21 + 2_PAC/node_modules/saslprep/package.json | 72 + 2_PAC/node_modules/saslprep/readme.md | 31 + 2_PAC/node_modules/saslprep/test/index.js | 76 + 2_PAC/node_modules/saslprep/test/util.js | 16 + .../smart-buffer/.prettierrc.yaml | 5 + 2_PAC/node_modules/smart-buffer/.travis.yml | 13 + 2_PAC/node_modules/smart-buffer/LICENSE | 20 + 2_PAC/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 2_PAC/node_modules/smart-buffer/package.json | 79 + .../smart-buffer/typings/smartbuffer.d.ts | 755 ++ .../smart-buffer/typings/utils.d.ts | 66 + 2_PAC/node_modules/socks/.eslintrc.cjs | 11 + 2_PAC/node_modules/socks/.prettierrc.yaml | 7 + 2_PAC/node_modules/socks/LICENSE | 20 + 2_PAC/node_modules/socks/README.md | 686 ++ .../socks/build/client/socksclient.js | 793 +++ .../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 + 2_PAC/node_modules/socks/build/common/util.js | 25 + .../socks/build/common/util.js.map | 1 + 2_PAC/node_modules/socks/build/index.js | 18 + 2_PAC/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 + 2_PAC/node_modules/socks/docs/index.md | 5 + .../socks/docs/migratingFromV1.md | 86 + 2_PAC/node_modules/socks/package.json | 58 + .../socks/typings/client/socksclient.d.ts | 162 + .../socks/typings/common/constants.d.ts | 152 + .../socks/typings/common/helpers.d.ts | 13 + .../socks/typings/common/receivebuffer.d.ts | 12 + .../socks/typings/common/util.d.ts | 17 + 2_PAC/node_modules/socks/typings/index.d.ts | 1 + 2_PAC/node_modules/sparse-bitfield/.npmignore | 1 + .../node_modules/sparse-bitfield/.travis.yml | 6 + 2_PAC/node_modules/sparse-bitfield/LICENSE | 21 + 2_PAC/node_modules/sparse-bitfield/README.md | 62 + 2_PAC/node_modules/sparse-bitfield/index.js | 95 + .../node_modules/sparse-bitfield/package.json | 27 + 2_PAC/node_modules/sparse-bitfield/test.js | 79 + 2_PAC/package-lock.json | 3532 +++++++++- 2_PAC/package.json | 15 + 1059 files changed, 261522 insertions(+), 1518 deletions(-) rename 1_ActivityWatchProducer/{lib/UserInfo => CSS}/UserInterface.css (100%) rename 1_ActivityWatchProducer/{lib/BugReportPanel => CSS}/bugreport.css (100%) rename 1_ActivityWatchProducer/{lib/SupersetEmbeddedDashboard => CSS}/embeddedDashboard.css (100%) rename 1_ActivityWatchProducer/{lib/ReusableComponents => CSS}/reusableComponents.css (100%) rename 1_ActivityWatchProducer/{lib/TasksConsumer => CSS}/taskdashboard.css (100%) rename 1_ActivityWatchProducer/{lib/AwUpdateFlowControl => CSS}/updateInterface.css (100%) rename 1_ActivityWatchProducer/{lib => JS}/BugReportPanel/BugReport.js (100%) rename 1_ActivityWatchProducer/JS/{Modules => ControlPanel}/AwApiUpdateManager.js (95%) rename 1_ActivityWatchProducer/JS/{Modules/AwApiStartStopManager.js => ControlPanel/ScanManager.js} (66%) rename 1_ActivityWatchProducer/{lib/AwUpdateFlowControl => JS/PacModules}/AwManager.js (99%) rename 1_ActivityWatchProducer/{lib/AwUpdateFlowControl => JS/PacModules}/AwProducer.js (92%) rename 1_ActivityWatchProducer/{lib/TasksConsumer => JS/PacModules}/tasksConsumer.js (93%) rename 1_ActivityWatchProducer/{lib => JS}/UserInfo/UserInfoConsumer.js (94%) delete mode 100644 1_ActivityWatchProducer/JS/greglogs.js rename 1_ActivityWatchProducer/{lib => Resources}/my2sec-FULL_271022.js (100%) rename 1_ActivityWatchProducer/{lib => Resources}/my2sec-jena_251122.jsap.js (100%) rename 1_ActivityWatchProducer/{lib => Resources}/my2sec-jena_251122.jsap.txt (100%) rename 1_ActivityWatchProducer/{lib => Resources}/my2sec_19-1-2023.jsap.js (99%) create mode 100644 1_ActivityWatchProducer/Resources/my2sec_7-3-2023.jsap create mode 100644 1_ActivityWatchProducer/electron_main_modules/AwApiRouter.js create mode 100644 1_ActivityWatchProducer/electron_main_modules/JsapConfigurationManager.js create mode 100644 1_ActivityWatchProducer/electron_main_modules/MongoDbClient.js create mode 100644 1_ActivityWatchProducer/electron_main_modules/MongoDbRouter.js create mode 100644 1_ActivityWatchProducer/electron_main_modules/PythonApiRunner.js rename 1_ActivityWatchProducer/lib/{AwUpdateFlowControl => }/AwClient.js (91%) delete mode 100644 1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwClient_BACKUP.js delete mode 100644 1_ActivityWatchProducer/lib/AwUpdateFlowControl/jsap.js delete mode 100644 1_ActivityWatchProducer/lib/gregnet-grid-plugin/gregnet-grid-script.js delete mode 100644 1_ActivityWatchProducer/lib/gregnet-grid-plugin/gregnet-grid-style.css delete mode 100644 1_ActivityWatchProducer/lib/gregnet-grid-plugin/readme.txt rename 1_ActivityWatchProducer/lib/{SupersetEmbeddedDashboard => }/superset-embed.js (89%) create mode 100644 1_ActivityWatchProducer/node_modules/@types/webidl-conversions/LICENSE create mode 100644 1_ActivityWatchProducer/node_modules/@types/webidl-conversions/README.md create mode 100644 1_ActivityWatchProducer/node_modules/@types/webidl-conversions/index.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/@types/webidl-conversions/package.json create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/LICENSE create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/README.md create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URL-impl.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URL.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URLSearchParams-impl.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URLSearchParams.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/index.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/package.json create mode 100644 1_ActivityWatchProducer/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/LICENSE.md create mode 100644 1_ActivityWatchProducer/node_modules/bson/README.md create mode 100644 1_ActivityWatchProducer/node_modules/bson/bson.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/etc/prepare.js create mode 100644 1_ActivityWatchProducer/node_modules/bson/lib/bson.bundle.js create mode 100644 1_ActivityWatchProducer/node_modules/bson/lib/bson.bundle.js.map create mode 100644 1_ActivityWatchProducer/node_modules/bson/lib/bson.cjs create mode 100644 1_ActivityWatchProducer/node_modules/bson/lib/bson.cjs.map create mode 100644 1_ActivityWatchProducer/node_modules/bson/lib/bson.mjs create mode 100644 1_ActivityWatchProducer/node_modules/bson/lib/bson.mjs.map create mode 100644 1_ActivityWatchProducer/node_modules/bson/package.json create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/binary.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/bson.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/bson_value.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/code.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/constants.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/db_ref.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/decimal128.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/double.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/error.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/extended_json.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/index.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/int_32.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/long.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/max_key.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/min_key.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/objectid.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/parser/calculate_size.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/parser/deserializer.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/parser/serializer.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/parser/utils.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/regexp.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/symbol.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/timestamp.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/utils/byte_utils.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/utils/node_byte_utils.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/utils/web_byte_utils.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/uuid_utils.ts create mode 100644 1_ActivityWatchProducer/node_modules/bson/src/validate_utf8.ts create mode 100644 1_ActivityWatchProducer/node_modules/memory-pager/.travis.yml create mode 100644 1_ActivityWatchProducer/node_modules/memory-pager/LICENSE create mode 100644 1_ActivityWatchProducer/node_modules/memory-pager/README.md create mode 100644 1_ActivityWatchProducer/node_modules/memory-pager/index.js create mode 100644 1_ActivityWatchProducer/node_modules/memory-pager/package.json create mode 100644 1_ActivityWatchProducer/node_modules/memory-pager/test.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/LICENSE create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/README.md create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/package.json create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/LICENSE.md create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/README.md create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/etc/prepare.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/admin.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/admin.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/bson.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/bson.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/common.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/common.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/ordered.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/unordered.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/change_stream.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/change_stream.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/auth_provider.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/gssapi.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/gssapi.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongocr.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongocr.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/plain.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/plain.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/providers.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/providers.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/scram.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/scram.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/x509.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/x509.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/command_monitoring_events.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/commands.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/commands.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connect.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connect.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool_events.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool_events.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/errors.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/errors.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/message_stream.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/message_stream.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/metrics.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/metrics.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/stream_description.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/stream_description.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/compression.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/constants.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/shared.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/collection.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/collection.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/connection_string.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/connection_string.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/constants.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/constants.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/abstract_cursor.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/abstract_cursor.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/aggregation_cursor.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/change_stream_cursor.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/find_cursor.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/find_cursor.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_collections_cursor.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_indexes_cursor.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/db.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/db.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/deps.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/deps.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/encrypter.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/encrypter.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/error.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/error.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/explain.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/explain.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/download.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/download.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/index.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/index.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/upload.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/upload.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/index.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/index.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_client.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_client.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_logger.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_logger.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_types.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_types.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/add_user.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/add_user.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/aggregate.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/aggregate.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/bulk_write.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/bulk_write.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/collections.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/collections.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/command.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/command.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/common_functions.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/common_functions.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count_documents.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count_documents.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/create_collection.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/create_collection.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/delete.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/delete.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/distinct.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/distinct.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/drop.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/drop.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/estimated_document_count.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/estimated_document_count.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/eval.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/eval.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/execute_operation.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/execute_operation.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find_and_modify.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find_and_modify.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/get_more.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/get_more.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/indexes.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/indexes.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/insert.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/insert.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/is_capped.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/is_capped.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/kill_cursors.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/kill_cursors.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_collections.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_collections.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_databases.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_databases.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/operation.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/operation.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/options_operation.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/options_operation.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/profiling_level.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/profiling_level.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/remove_user.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/remove_user.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/rename.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/rename.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/run_command.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/run_command.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/set_profiling_level.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/set_profiling_level.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/stats.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/stats.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/update.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/update.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/validate_collection.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/operations/validate_collection.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/read_concern.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/read_concern.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/read_preference.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/read_preference.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/common.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/common.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/events.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/events.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/monitor.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/monitor.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_description.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_description.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_selection.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_selection.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/srv_polling.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/srv_polling.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology_description.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology_description.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sessions.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sessions.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sort.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/sort.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/transactions.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/transactions.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/utils.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/utils.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/write_concern.js create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/lib/write_concern.js.map create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/mongodb.d.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/package.json create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/admin.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/bson.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/bulk/common.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/bulk/ordered.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/bulk/unordered.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/change_stream.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/auth_provider.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/gssapi.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongocr.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongodb_oidc.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/plain.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/providers.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/scram.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/x509.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/command_monitoring_events.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/commands.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connect.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection_pool.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection_pool_events.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/errors.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/message_stream.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/metrics.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/stream_description.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/compression.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/constants.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/shared.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/collection.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/connection_string.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/constants.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cursor/abstract_cursor.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cursor/aggregation_cursor.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cursor/change_stream_cursor.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cursor/find_cursor.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cursor/list_collections_cursor.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/cursor/list_indexes_cursor.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/db.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/deps.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/encrypter.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/error.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/explain.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/download.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/index.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/upload.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/index.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/mongo_client.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/mongo_logger.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/mongo_types.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/add_user.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/aggregate.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/bulk_write.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/collections.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/command.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/common_functions.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/count.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/count_documents.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/create_collection.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/delete.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/distinct.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/drop.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/estimated_document_count.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/eval.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/execute_operation.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/find.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/find_and_modify.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/get_more.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/indexes.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/insert.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/is_capped.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/kill_cursors.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/list_collections.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/list_databases.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/operation.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/options_operation.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/profiling_level.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/remove_user.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/rename.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/run_command.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/set_profiling_level.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/stats.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/update.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/operations/validate_collection.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/read_concern.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/read_preference.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/common.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/events.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/monitor.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server_description.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server_selection.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/srv_polling.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/topology.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sdam/topology_description.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sessions.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/sort.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/transactions.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/utils.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/src/write_concern.ts create mode 100644 1_ActivityWatchProducer/node_modules/mongodb/tsconfig.json create mode 100644 1_ActivityWatchProducer/node_modules/punycode/LICENSE-MIT.txt create mode 100644 1_ActivityWatchProducer/node_modules/punycode/README.md create mode 100644 1_ActivityWatchProducer/node_modules/punycode/package.json create mode 100644 1_ActivityWatchProducer/node_modules/punycode/punycode.es6.js create mode 100644 1_ActivityWatchProducer/node_modules/punycode/punycode.js create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/.editorconfig create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/.gitattributes create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/.travis.yml create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/CHANGELOG.md create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/LICENSE create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/code-points.mem create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/generate-code-points.js create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/index.js create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/lib/code-points.js create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/lib/memory-code-points.js create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/lib/util.js create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/package.json create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/readme.md create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/test/index.js create mode 100644 1_ActivityWatchProducer/node_modules/saslprep/test/util.js create mode 100644 1_ActivityWatchProducer/node_modules/sparse-bitfield/.npmignore create mode 100644 1_ActivityWatchProducer/node_modules/sparse-bitfield/.travis.yml create mode 100644 1_ActivityWatchProducer/node_modules/sparse-bitfield/LICENSE create mode 100644 1_ActivityWatchProducer/node_modules/sparse-bitfield/README.md create mode 100644 1_ActivityWatchProducer/node_modules/sparse-bitfield/index.js create mode 100644 1_ActivityWatchProducer/node_modules/sparse-bitfield/package.json create mode 100644 1_ActivityWatchProducer/node_modules/sparse-bitfield/test.js create mode 100644 1_ActivityWatchProducer/node_modules/tr46/LICENSE.md create mode 100644 1_ActivityWatchProducer/node_modules/tr46/README.md create mode 100644 1_ActivityWatchProducer/node_modules/tr46/index.js create mode 100644 1_ActivityWatchProducer/node_modules/tr46/lib/mappingTable.json create mode 100644 1_ActivityWatchProducer/node_modules/tr46/lib/regexes.js create mode 100644 1_ActivityWatchProducer/node_modules/tr46/lib/statusMapping.js create mode 100644 1_ActivityWatchProducer/node_modules/tr46/package.json create mode 100644 1_ActivityWatchProducer/node_modules/webidl-conversions/LICENSE.md create mode 100644 1_ActivityWatchProducer/node_modules/webidl-conversions/README.md create mode 100644 1_ActivityWatchProducer/node_modules/webidl-conversions/lib/index.js create mode 100644 1_ActivityWatchProducer/node_modules/webidl-conversions/package.json create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/LICENSE.txt create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/README.md create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/index.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/Function.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/URL-impl.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/URL.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/URLSearchParams-impl.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/URLSearchParams.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/VoidFunction.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/encoding.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/infra.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/percent-encoding.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/url-state-machine.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/urlencoded.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/lib/utils.js create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/package.json create mode 100644 1_ActivityWatchProducer/node_modules/whatwg-url/webidl2js-wrapper.js create mode 100644 2_PAC/gregnet_modules/PacFactory/MongoDbClient.js create mode 100644 2_PAC/gregnet_modules/PacFactory/SupersetClient.js create mode 100644 2_PAC/node_modules/@types/node/LICENSE create mode 100644 2_PAC/node_modules/@types/node/README.md create mode 100644 2_PAC/node_modules/@types/node/assert.d.ts create mode 100644 2_PAC/node_modules/@types/node/assert/strict.d.ts create mode 100644 2_PAC/node_modules/@types/node/async_hooks.d.ts create mode 100644 2_PAC/node_modules/@types/node/buffer.d.ts create mode 100644 2_PAC/node_modules/@types/node/child_process.d.ts create mode 100644 2_PAC/node_modules/@types/node/cluster.d.ts create mode 100644 2_PAC/node_modules/@types/node/console.d.ts create mode 100644 2_PAC/node_modules/@types/node/constants.d.ts create mode 100644 2_PAC/node_modules/@types/node/crypto.d.ts create mode 100644 2_PAC/node_modules/@types/node/dgram.d.ts create mode 100644 2_PAC/node_modules/@types/node/diagnostics_channel.d.ts create mode 100644 2_PAC/node_modules/@types/node/dns.d.ts create mode 100644 2_PAC/node_modules/@types/node/dns/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/dom-events.d.ts create mode 100644 2_PAC/node_modules/@types/node/domain.d.ts create mode 100644 2_PAC/node_modules/@types/node/events.d.ts create mode 100644 2_PAC/node_modules/@types/node/fs.d.ts create mode 100644 2_PAC/node_modules/@types/node/fs/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/globals.d.ts create mode 100644 2_PAC/node_modules/@types/node/globals.global.d.ts create mode 100644 2_PAC/node_modules/@types/node/http.d.ts create mode 100644 2_PAC/node_modules/@types/node/http2.d.ts create mode 100644 2_PAC/node_modules/@types/node/https.d.ts create mode 100644 2_PAC/node_modules/@types/node/index.d.ts create mode 100644 2_PAC/node_modules/@types/node/inspector.d.ts create mode 100644 2_PAC/node_modules/@types/node/module.d.ts create mode 100644 2_PAC/node_modules/@types/node/net.d.ts create mode 100644 2_PAC/node_modules/@types/node/os.d.ts create mode 100644 2_PAC/node_modules/@types/node/package.json create mode 100644 2_PAC/node_modules/@types/node/path.d.ts create mode 100644 2_PAC/node_modules/@types/node/perf_hooks.d.ts create mode 100644 2_PAC/node_modules/@types/node/process.d.ts create mode 100644 2_PAC/node_modules/@types/node/punycode.d.ts create mode 100644 2_PAC/node_modules/@types/node/querystring.d.ts create mode 100644 2_PAC/node_modules/@types/node/readline.d.ts create mode 100644 2_PAC/node_modules/@types/node/readline/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/repl.d.ts create mode 100644 2_PAC/node_modules/@types/node/stream.d.ts create mode 100644 2_PAC/node_modules/@types/node/stream/consumers.d.ts create mode 100644 2_PAC/node_modules/@types/node/stream/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/stream/web.d.ts create mode 100644 2_PAC/node_modules/@types/node/string_decoder.d.ts create mode 100644 2_PAC/node_modules/@types/node/test.d.ts create mode 100644 2_PAC/node_modules/@types/node/timers.d.ts create mode 100644 2_PAC/node_modules/@types/node/timers/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/tls.d.ts create mode 100644 2_PAC/node_modules/@types/node/trace_events.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/assert.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/assert/strict.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/async_hooks.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/buffer.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/child_process.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/cluster.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/console.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/constants.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/crypto.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/dgram.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/dns.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/dns/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/dom-events.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/domain.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/events.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/fs.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/fs/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/globals.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/globals.global.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/http.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/http2.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/https.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/index.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/inspector.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/module.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/net.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/os.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/path.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/perf_hooks.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/process.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/punycode.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/querystring.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/readline.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/readline/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/repl.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/stream.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/stream/consumers.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/stream/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/stream/web.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/string_decoder.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/test.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/timers.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/timers/promises.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/tls.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/trace_events.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/tty.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/url.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/util.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/v8.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/vm.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/wasi.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/worker_threads.d.ts create mode 100644 2_PAC/node_modules/@types/node/ts4.8/zlib.d.ts create mode 100644 2_PAC/node_modules/@types/node/tty.d.ts create mode 100644 2_PAC/node_modules/@types/node/url.d.ts create mode 100644 2_PAC/node_modules/@types/node/util.d.ts create mode 100644 2_PAC/node_modules/@types/node/v8.d.ts create mode 100644 2_PAC/node_modules/@types/node/vm.d.ts create mode 100644 2_PAC/node_modules/@types/node/wasi.d.ts create mode 100644 2_PAC/node_modules/@types/node/worker_threads.d.ts create mode 100644 2_PAC/node_modules/@types/node/zlib.d.ts create mode 100644 2_PAC/node_modules/@types/webidl-conversions/LICENSE create mode 100644 2_PAC/node_modules/@types/webidl-conversions/README.md create mode 100644 2_PAC/node_modules/@types/webidl-conversions/index.d.ts create mode 100644 2_PAC/node_modules/@types/webidl-conversions/package.json create mode 100644 2_PAC/node_modules/@types/whatwg-url/LICENSE create mode 100644 2_PAC/node_modules/@types/whatwg-url/README.md create mode 100644 2_PAC/node_modules/@types/whatwg-url/dist/URL-impl.d.ts create mode 100644 2_PAC/node_modules/@types/whatwg-url/dist/URL.d.ts create mode 100644 2_PAC/node_modules/@types/whatwg-url/dist/URLSearchParams-impl.d.ts create mode 100644 2_PAC/node_modules/@types/whatwg-url/dist/URLSearchParams.d.ts create mode 100644 2_PAC/node_modules/@types/whatwg-url/index.d.ts create mode 100644 2_PAC/node_modules/@types/whatwg-url/package.json create mode 100644 2_PAC/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts create mode 100644 2_PAC/node_modules/bson/LICENSE.md create mode 100644 2_PAC/node_modules/bson/README.md create mode 100644 2_PAC/node_modules/bson/bson.d.ts create mode 100644 2_PAC/node_modules/bson/etc/prepare.js create mode 100644 2_PAC/node_modules/bson/lib/bson.bundle.js create mode 100644 2_PAC/node_modules/bson/lib/bson.bundle.js.map create mode 100644 2_PAC/node_modules/bson/lib/bson.cjs create mode 100644 2_PAC/node_modules/bson/lib/bson.cjs.map create mode 100644 2_PAC/node_modules/bson/lib/bson.mjs create mode 100644 2_PAC/node_modules/bson/lib/bson.mjs.map create mode 100644 2_PAC/node_modules/bson/package.json create mode 100644 2_PAC/node_modules/bson/src/binary.ts create mode 100644 2_PAC/node_modules/bson/src/bson.ts create mode 100644 2_PAC/node_modules/bson/src/bson_value.ts create mode 100644 2_PAC/node_modules/bson/src/code.ts create mode 100644 2_PAC/node_modules/bson/src/constants.ts create mode 100644 2_PAC/node_modules/bson/src/db_ref.ts create mode 100644 2_PAC/node_modules/bson/src/decimal128.ts create mode 100644 2_PAC/node_modules/bson/src/double.ts create mode 100644 2_PAC/node_modules/bson/src/error.ts create mode 100644 2_PAC/node_modules/bson/src/extended_json.ts create mode 100644 2_PAC/node_modules/bson/src/index.ts create mode 100644 2_PAC/node_modules/bson/src/int_32.ts create mode 100644 2_PAC/node_modules/bson/src/long.ts create mode 100644 2_PAC/node_modules/bson/src/max_key.ts create mode 100644 2_PAC/node_modules/bson/src/min_key.ts create mode 100644 2_PAC/node_modules/bson/src/objectid.ts create mode 100644 2_PAC/node_modules/bson/src/parser/calculate_size.ts create mode 100644 2_PAC/node_modules/bson/src/parser/deserializer.ts create mode 100644 2_PAC/node_modules/bson/src/parser/serializer.ts create mode 100644 2_PAC/node_modules/bson/src/parser/utils.ts create mode 100644 2_PAC/node_modules/bson/src/regexp.ts create mode 100644 2_PAC/node_modules/bson/src/symbol.ts create mode 100644 2_PAC/node_modules/bson/src/timestamp.ts create mode 100644 2_PAC/node_modules/bson/src/utils/byte_utils.ts create mode 100644 2_PAC/node_modules/bson/src/utils/node_byte_utils.ts create mode 100644 2_PAC/node_modules/bson/src/utils/web_byte_utils.ts create mode 100644 2_PAC/node_modules/bson/src/uuid_utils.ts create mode 100644 2_PAC/node_modules/bson/src/validate_utf8.ts create mode 100644 2_PAC/node_modules/ip/README.md create mode 100644 2_PAC/node_modules/ip/lib/ip.js create mode 100644 2_PAC/node_modules/ip/package.json create mode 100644 2_PAC/node_modules/memory-pager/.travis.yml create mode 100644 2_PAC/node_modules/memory-pager/LICENSE create mode 100644 2_PAC/node_modules/memory-pager/README.md create mode 100644 2_PAC/node_modules/memory-pager/index.js create mode 100644 2_PAC/node_modules/memory-pager/package.json create mode 100644 2_PAC/node_modules/memory-pager/test.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/LICENSE create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/README.md create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/lib/index.d.ts create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/lib/index.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/lib/index.js.map create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/lib/redact.d.ts create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/lib/redact.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/lib/redact.js.map create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/LICENSE.md create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/README.md create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/index.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/mappingTable.json create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/regexes.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/statusMapping.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/package.json create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/LICENSE.md create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/README.md create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/lib/index.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/package.json create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/LICENSE.txt create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/README.md create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/index.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/Function.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URL-impl.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URL.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URLSearchParams-impl.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URLSearchParams.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/VoidFunction.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/encoding.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/infra.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/percent-encoding.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/url-state-machine.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/urlencoded.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/utils.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/package.json create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/webidl2js-wrapper.js create mode 100644 2_PAC/node_modules/mongodb-connection-string-url/package.json create mode 100644 2_PAC/node_modules/mongodb/LICENSE.md create mode 100644 2_PAC/node_modules/mongodb/README.md create mode 100644 2_PAC/node_modules/mongodb/etc/prepare.js create mode 100644 2_PAC/node_modules/mongodb/lib/admin.js create mode 100644 2_PAC/node_modules/mongodb/lib/admin.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/bson.js create mode 100644 2_PAC/node_modules/mongodb/lib/bson.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/bulk/common.js create mode 100644 2_PAC/node_modules/mongodb/lib/bulk/common.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 2_PAC/node_modules/mongodb/lib/bulk/ordered.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 2_PAC/node_modules/mongodb/lib/bulk/unordered.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/change_stream.js create mode 100644 2_PAC/node_modules/mongodb/lib/change_stream.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/auth_provider.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/gssapi.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/gssapi.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/mongocr.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/mongocr.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/plain.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/plain.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/providers.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/providers.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/scram.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/scram.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/x509.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/auth/x509.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/command_monitoring_events.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/commands.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/commands.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/connect.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/connect.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/connection.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/connection.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/connection_pool.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/connection_pool.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/connection_pool_events.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/connection_pool_events.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/errors.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/errors.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/message_stream.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/message_stream.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/metrics.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/metrics.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/stream_description.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/stream_description.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/compression.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/constants.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/shared.js create mode 100644 2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/collection.js create mode 100644 2_PAC/node_modules/mongodb/lib/collection.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/connection_string.js create mode 100644 2_PAC/node_modules/mongodb/lib/connection_string.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/constants.js create mode 100644 2_PAC/node_modules/mongodb/lib/constants.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/abstract_cursor.js create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/abstract_cursor.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/aggregation_cursor.js create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/change_stream_cursor.js create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/find_cursor.js create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/find_cursor.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/list_collections_cursor.js create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/list_indexes_cursor.js create mode 100644 2_PAC/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/db.js create mode 100644 2_PAC/node_modules/mongodb/lib/db.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/deps.js create mode 100644 2_PAC/node_modules/mongodb/lib/deps.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/encrypter.js create mode 100644 2_PAC/node_modules/mongodb/lib/encrypter.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/error.js create mode 100644 2_PAC/node_modules/mongodb/lib/error.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/explain.js create mode 100644 2_PAC/node_modules/mongodb/lib/explain.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/gridfs/download.js create mode 100644 2_PAC/node_modules/mongodb/lib/gridfs/download.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/gridfs/index.js create mode 100644 2_PAC/node_modules/mongodb/lib/gridfs/index.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/gridfs/upload.js create mode 100644 2_PAC/node_modules/mongodb/lib/gridfs/upload.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/index.js create mode 100644 2_PAC/node_modules/mongodb/lib/index.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/mongo_client.js create mode 100644 2_PAC/node_modules/mongodb/lib/mongo_client.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/mongo_logger.js create mode 100644 2_PAC/node_modules/mongodb/lib/mongo_logger.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/mongo_types.js create mode 100644 2_PAC/node_modules/mongodb/lib/mongo_types.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/add_user.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/add_user.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/aggregate.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/aggregate.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/bulk_write.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/bulk_write.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/collections.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/collections.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/command.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/command.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/common_functions.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/common_functions.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/count.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/count.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/count_documents.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/count_documents.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/create_collection.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/create_collection.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/delete.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/delete.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/distinct.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/distinct.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/drop.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/drop.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/estimated_document_count.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/estimated_document_count.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/eval.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/eval.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/execute_operation.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/execute_operation.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/find.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/find.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/find_and_modify.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/find_and_modify.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/get_more.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/get_more.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/indexes.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/indexes.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/insert.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/insert.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/is_capped.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/is_capped.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/kill_cursors.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/kill_cursors.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/list_collections.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/list_collections.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/list_databases.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/list_databases.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/operation.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/operation.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/options_operation.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/options_operation.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/profiling_level.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/profiling_level.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/remove_user.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/remove_user.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/rename.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/rename.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/run_command.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/run_command.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/set_profiling_level.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/set_profiling_level.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/stats.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/stats.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/update.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/update.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/operations/validate_collection.js create mode 100644 2_PAC/node_modules/mongodb/lib/operations/validate_collection.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/read_concern.js create mode 100644 2_PAC/node_modules/mongodb/lib/read_concern.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/read_preference.js create mode 100644 2_PAC/node_modules/mongodb/lib/read_preference.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/common.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/common.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/events.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/events.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/monitor.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/monitor.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/server.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/server.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/server_description.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/server_description.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/server_selection.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/server_selection.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/srv_polling.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/srv_polling.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/topology.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/topology.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/topology_description.js create mode 100644 2_PAC/node_modules/mongodb/lib/sdam/topology_description.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sessions.js create mode 100644 2_PAC/node_modules/mongodb/lib/sessions.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/sort.js create mode 100644 2_PAC/node_modules/mongodb/lib/sort.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/transactions.js create mode 100644 2_PAC/node_modules/mongodb/lib/transactions.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/utils.js create mode 100644 2_PAC/node_modules/mongodb/lib/utils.js.map create mode 100644 2_PAC/node_modules/mongodb/lib/write_concern.js create mode 100644 2_PAC/node_modules/mongodb/lib/write_concern.js.map create mode 100644 2_PAC/node_modules/mongodb/mongodb.d.ts create mode 100644 2_PAC/node_modules/mongodb/package.json create mode 100644 2_PAC/node_modules/mongodb/src/admin.ts create mode 100644 2_PAC/node_modules/mongodb/src/bson.ts create mode 100644 2_PAC/node_modules/mongodb/src/bulk/common.ts create mode 100644 2_PAC/node_modules/mongodb/src/bulk/ordered.ts create mode 100644 2_PAC/node_modules/mongodb/src/bulk/unordered.ts create mode 100644 2_PAC/node_modules/mongodb/src/change_stream.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/auth_provider.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/gssapi.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/mongocr.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/plain.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/providers.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/scram.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/auth/x509.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/command_monitoring_events.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/commands.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/connect.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/connection.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/connection_pool.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/connection_pool_events.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/errors.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/message_stream.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/metrics.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/stream_description.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/wire_protocol/compression.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/wire_protocol/constants.ts create mode 100644 2_PAC/node_modules/mongodb/src/cmap/wire_protocol/shared.ts create mode 100644 2_PAC/node_modules/mongodb/src/collection.ts create mode 100644 2_PAC/node_modules/mongodb/src/connection_string.ts create mode 100644 2_PAC/node_modules/mongodb/src/constants.ts create mode 100644 2_PAC/node_modules/mongodb/src/cursor/abstract_cursor.ts create mode 100644 2_PAC/node_modules/mongodb/src/cursor/aggregation_cursor.ts create mode 100644 2_PAC/node_modules/mongodb/src/cursor/change_stream_cursor.ts create mode 100644 2_PAC/node_modules/mongodb/src/cursor/find_cursor.ts create mode 100644 2_PAC/node_modules/mongodb/src/cursor/list_collections_cursor.ts create mode 100644 2_PAC/node_modules/mongodb/src/cursor/list_indexes_cursor.ts create mode 100644 2_PAC/node_modules/mongodb/src/db.ts create mode 100644 2_PAC/node_modules/mongodb/src/deps.ts create mode 100644 2_PAC/node_modules/mongodb/src/encrypter.ts create mode 100644 2_PAC/node_modules/mongodb/src/error.ts create mode 100644 2_PAC/node_modules/mongodb/src/explain.ts create mode 100644 2_PAC/node_modules/mongodb/src/gridfs/download.ts create mode 100644 2_PAC/node_modules/mongodb/src/gridfs/index.ts create mode 100644 2_PAC/node_modules/mongodb/src/gridfs/upload.ts create mode 100644 2_PAC/node_modules/mongodb/src/index.ts create mode 100644 2_PAC/node_modules/mongodb/src/mongo_client.ts create mode 100644 2_PAC/node_modules/mongodb/src/mongo_logger.ts create mode 100644 2_PAC/node_modules/mongodb/src/mongo_types.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/add_user.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/aggregate.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/bulk_write.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/collections.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/command.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/common_functions.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/count.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/count_documents.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/create_collection.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/delete.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/distinct.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/drop.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/estimated_document_count.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/eval.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/execute_operation.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/find.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/find_and_modify.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/get_more.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/indexes.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/insert.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/is_capped.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/kill_cursors.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/list_collections.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/list_databases.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/operation.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/options_operation.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/profiling_level.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/remove_user.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/rename.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/run_command.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/set_profiling_level.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/stats.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/update.ts create mode 100644 2_PAC/node_modules/mongodb/src/operations/validate_collection.ts create mode 100644 2_PAC/node_modules/mongodb/src/read_concern.ts create mode 100644 2_PAC/node_modules/mongodb/src/read_preference.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/common.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/events.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/monitor.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/server.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/server_description.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/server_selection.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/srv_polling.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/topology.ts create mode 100644 2_PAC/node_modules/mongodb/src/sdam/topology_description.ts create mode 100644 2_PAC/node_modules/mongodb/src/sessions.ts create mode 100644 2_PAC/node_modules/mongodb/src/sort.ts create mode 100644 2_PAC/node_modules/mongodb/src/transactions.ts create mode 100644 2_PAC/node_modules/mongodb/src/utils.ts create mode 100644 2_PAC/node_modules/mongodb/src/write_concern.ts create mode 100644 2_PAC/node_modules/mongodb/tsconfig.json create mode 100644 2_PAC/node_modules/saslprep/.editorconfig create mode 100644 2_PAC/node_modules/saslprep/.gitattributes create mode 100644 2_PAC/node_modules/saslprep/.travis.yml create mode 100644 2_PAC/node_modules/saslprep/CHANGELOG.md create mode 100644 2_PAC/node_modules/saslprep/LICENSE create mode 100644 2_PAC/node_modules/saslprep/code-points.mem create mode 100644 2_PAC/node_modules/saslprep/generate-code-points.js create mode 100644 2_PAC/node_modules/saslprep/index.js create mode 100644 2_PAC/node_modules/saslprep/lib/code-points.js create mode 100644 2_PAC/node_modules/saslprep/lib/memory-code-points.js create mode 100644 2_PAC/node_modules/saslprep/lib/util.js create mode 100644 2_PAC/node_modules/saslprep/package.json create mode 100644 2_PAC/node_modules/saslprep/readme.md create mode 100644 2_PAC/node_modules/saslprep/test/index.js create mode 100644 2_PAC/node_modules/saslprep/test/util.js create mode 100644 2_PAC/node_modules/smart-buffer/.prettierrc.yaml create mode 100644 2_PAC/node_modules/smart-buffer/.travis.yml create mode 100644 2_PAC/node_modules/smart-buffer/LICENSE create mode 100644 2_PAC/node_modules/smart-buffer/README.md create mode 100644 2_PAC/node_modules/smart-buffer/build/smartbuffer.js create mode 100644 2_PAC/node_modules/smart-buffer/build/smartbuffer.js.map create mode 100644 2_PAC/node_modules/smart-buffer/build/utils.js create mode 100644 2_PAC/node_modules/smart-buffer/build/utils.js.map create mode 100644 2_PAC/node_modules/smart-buffer/docs/CHANGELOG.md create mode 100644 2_PAC/node_modules/smart-buffer/docs/README_v3.md create mode 100644 2_PAC/node_modules/smart-buffer/docs/ROADMAP.md create mode 100644 2_PAC/node_modules/smart-buffer/package.json create mode 100644 2_PAC/node_modules/smart-buffer/typings/smartbuffer.d.ts create mode 100644 2_PAC/node_modules/smart-buffer/typings/utils.d.ts create mode 100644 2_PAC/node_modules/socks/.eslintrc.cjs create mode 100644 2_PAC/node_modules/socks/.prettierrc.yaml create mode 100644 2_PAC/node_modules/socks/LICENSE create mode 100644 2_PAC/node_modules/socks/README.md create mode 100644 2_PAC/node_modules/socks/build/client/socksclient.js create mode 100644 2_PAC/node_modules/socks/build/client/socksclient.js.map create mode 100644 2_PAC/node_modules/socks/build/common/constants.js create mode 100644 2_PAC/node_modules/socks/build/common/constants.js.map create mode 100644 2_PAC/node_modules/socks/build/common/helpers.js create mode 100644 2_PAC/node_modules/socks/build/common/helpers.js.map create mode 100644 2_PAC/node_modules/socks/build/common/receivebuffer.js create mode 100644 2_PAC/node_modules/socks/build/common/receivebuffer.js.map create mode 100644 2_PAC/node_modules/socks/build/common/util.js create mode 100644 2_PAC/node_modules/socks/build/common/util.js.map create mode 100644 2_PAC/node_modules/socks/build/index.js create mode 100644 2_PAC/node_modules/socks/build/index.js.map create mode 100644 2_PAC/node_modules/socks/docs/examples/index.md create mode 100644 2_PAC/node_modules/socks/docs/examples/javascript/associateExample.md create mode 100644 2_PAC/node_modules/socks/docs/examples/javascript/bindExample.md create mode 100644 2_PAC/node_modules/socks/docs/examples/javascript/connectExample.md create mode 100644 2_PAC/node_modules/socks/docs/examples/typescript/associateExample.md create mode 100644 2_PAC/node_modules/socks/docs/examples/typescript/bindExample.md create mode 100644 2_PAC/node_modules/socks/docs/examples/typescript/connectExample.md create mode 100644 2_PAC/node_modules/socks/docs/index.md create mode 100644 2_PAC/node_modules/socks/docs/migratingFromV1.md create mode 100644 2_PAC/node_modules/socks/package.json create mode 100644 2_PAC/node_modules/socks/typings/client/socksclient.d.ts create mode 100644 2_PAC/node_modules/socks/typings/common/constants.d.ts create mode 100644 2_PAC/node_modules/socks/typings/common/helpers.d.ts create mode 100644 2_PAC/node_modules/socks/typings/common/receivebuffer.d.ts create mode 100644 2_PAC/node_modules/socks/typings/common/util.d.ts create mode 100644 2_PAC/node_modules/socks/typings/index.d.ts create mode 100644 2_PAC/node_modules/sparse-bitfield/.npmignore create mode 100644 2_PAC/node_modules/sparse-bitfield/.travis.yml create mode 100644 2_PAC/node_modules/sparse-bitfield/LICENSE create mode 100644 2_PAC/node_modules/sparse-bitfield/README.md create mode 100644 2_PAC/node_modules/sparse-bitfield/index.js create mode 100644 2_PAC/node_modules/sparse-bitfield/package.json create mode 100644 2_PAC/node_modules/sparse-bitfield/test.js diff --git a/1_ActivityWatchProducer/lib/UserInfo/UserInterface.css b/1_ActivityWatchProducer/CSS/UserInterface.css similarity index 100% rename from 1_ActivityWatchProducer/lib/UserInfo/UserInterface.css rename to 1_ActivityWatchProducer/CSS/UserInterface.css diff --git a/1_ActivityWatchProducer/lib/BugReportPanel/bugreport.css b/1_ActivityWatchProducer/CSS/bugreport.css similarity index 100% rename from 1_ActivityWatchProducer/lib/BugReportPanel/bugreport.css rename to 1_ActivityWatchProducer/CSS/bugreport.css diff --git a/1_ActivityWatchProducer/lib/SupersetEmbeddedDashboard/embeddedDashboard.css b/1_ActivityWatchProducer/CSS/embeddedDashboard.css similarity index 100% rename from 1_ActivityWatchProducer/lib/SupersetEmbeddedDashboard/embeddedDashboard.css rename to 1_ActivityWatchProducer/CSS/embeddedDashboard.css diff --git a/1_ActivityWatchProducer/lib/ReusableComponents/reusableComponents.css b/1_ActivityWatchProducer/CSS/reusableComponents.css similarity index 100% rename from 1_ActivityWatchProducer/lib/ReusableComponents/reusableComponents.css rename to 1_ActivityWatchProducer/CSS/reusableComponents.css diff --git a/1_ActivityWatchProducer/lib/TasksConsumer/taskdashboard.css b/1_ActivityWatchProducer/CSS/taskdashboard.css similarity index 100% rename from 1_ActivityWatchProducer/lib/TasksConsumer/taskdashboard.css rename to 1_ActivityWatchProducer/CSS/taskdashboard.css diff --git a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/updateInterface.css b/1_ActivityWatchProducer/CSS/updateInterface.css similarity index 100% rename from 1_ActivityWatchProducer/lib/AwUpdateFlowControl/updateInterface.css rename to 1_ActivityWatchProducer/CSS/updateInterface.css diff --git a/1_ActivityWatchProducer/lib/BugReportPanel/BugReport.js b/1_ActivityWatchProducer/JS/BugReportPanel/BugReport.js similarity index 100% rename from 1_ActivityWatchProducer/lib/BugReportPanel/BugReport.js rename to 1_ActivityWatchProducer/JS/BugReportPanel/BugReport.js diff --git a/1_ActivityWatchProducer/JS/Modules/AwApiUpdateManager.js b/1_ActivityWatchProducer/JS/ControlPanel/AwApiUpdateManager.js similarity index 95% rename from 1_ActivityWatchProducer/JS/Modules/AwApiUpdateManager.js rename to 1_ActivityWatchProducer/JS/ControlPanel/AwApiUpdateManager.js index cb35a01c..24897022 100644 --- a/1_ActivityWatchProducer/JS/Modules/AwApiUpdateManager.js +++ b/1_ActivityWatchProducer/JS/ControlPanel/AwApiUpdateManager.js @@ -1,11 +1,11 @@ class AwApiUpdateManager { constructor(jsap_file,awmanager,userinfoconsumer,tasksconsumer){ + this.log=new Greglogs(); this.awManager=awmanager; this.userInfoConsumer=userinfoconsumer; this.tasksConsumer=tasksconsumer; this.vpanel=document.getElementById("validation_wrapper"); this.opanel=document.getElementById("validation_obscurer"); - this.log=new Greglogs(); this.usergraph="http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail; //MESSAGES this.awMessagesProducer=new SynchronousProducer( @@ -159,12 +159,19 @@ class AwApiUpdateManager { console.log(success) //ON SUCCESS... - await this.awManager.uploadQuery() + await this.awManager.uploadQuery() //dentro di se ora awmanager ha gli eventi + //non mi piace, voglio che ritorni una variabile e che fai il ciclo for prima + //if mongo -> qui invia sia sepa che mongo + //else solo sepa await this.send_messages_to_sepa() } + async send_messages_to_mongo(){ + + } + async send_messages_to_sepa(){ - consoleLog(1,"### BUTTON PRESSED, STARTING SEPA UPLOAD ###") + this.log.info("### BUTTON PRESSED, STARTING SEPA UPLOAD ###") this.change_update_status(3)//activate loading spinner console.log(" ") @@ -194,12 +201,12 @@ class AwApiUpdateManager { msgtimestamp: msgtimestamp, msgvalue: this.awManager.eventsRawJson[key] } - consoleLog(0,"Usergraph: "+data.usergraph) - consoleLog(0,"Source: "+data.source) - consoleLog(0,"Timestamp: "+data.msgtimestamp) - consoleLog(0,"Message: "+data.msgvalue) + this.log.debug("Usergraph: "+data.usergraph) + this.log.debug("Source: "+data.source) + this.log.debug("Timestamp: "+data.msgtimestamp) + this.log.debug("Message: "+data.msgvalue) response=await this.awManager.sepaClient.SEND_MESSAGE(data) - consoleLog(0,"RESPONSE: "+JSON.stringify(response)) + this.log.debug("RESPONSE: "+JSON.stringify(response)) data={}//wipe data }catch(e){ console.log(e); diff --git a/1_ActivityWatchProducer/JS/Modules/AwApiStartStopManager.js b/1_ActivityWatchProducer/JS/ControlPanel/ScanManager.js similarity index 66% rename from 1_ActivityWatchProducer/JS/Modules/AwApiStartStopManager.js rename to 1_ActivityWatchProducer/JS/ControlPanel/ScanManager.js index 9cee80ff..12c88502 100644 --- a/1_ActivityWatchProducer/JS/Modules/AwApiStartStopManager.js +++ b/1_ActivityWatchProducer/JS/ControlPanel/ScanManager.js @@ -1,22 +1,39 @@ -class AwApiStartStopManager { - constructor(){ +class ScanManager extends AwMy2SecClient{ + constructor(jsap){ + super(jsap); this.scan_started=false; this.time_scanned=0; this.currentSection=0; this.updatebutton=document.getElementById("update-procedure-button") this.explorerbutton=document.getElementById("explorer-button") this.startbutton=document.getElementById("start-stop-innertext") - this.awManager= new AwClient(); } - async start_button(){ + async getStatus(){ + var start_event=await this.get_producer_event("last_start") + var update_event=await this.get_producer_event("last_update") + var data={ + scanStarted:this.scan_started, + timeScanned:time_scanned, + lastStartEvent:start_event.data.last_start, + lastUpdateEvent:update_event.data.last_update + } + //this.log.info_table(data); + return data; + } + async logStatus(){ + var data=await this.getStatus(); + this.log.info_table(data); + } + + async onStartButtonPressed(){ try{ if(!scan_started){ this.currentSection=0; console.log("Starting scan...") - var res= await this.awManager.startWatchers() + var res= await this.startWatchers() console.log(res) - await this.awManager.update_start_flag() + await this.update_start_flag() updatebutton.className="default-button-deactivated" startbutton.innerHTML=`Stop Scan  ` explorerbutton.className="default-button" @@ -25,7 +42,7 @@ class AwApiStartStopManager { }else{ this.currentSection=0; console.log("stopping scan...") - var res=await this.awManager.stopWatchers() + var res=await this.stopWatchers() console.log(res) updatebutton.className="default-button" startbutton.innerHTML=`Resume Scan  ` @@ -41,43 +58,6 @@ class AwApiStartStopManager { } -//################### -//# START-STOP SCAN # -//################### -//update ia knowledge -var currentSection=0; -var scan_started=false; -var time_scanned=0; -var updatebutton=document.getElementById("update-procedure-button") -var explorerbutton=document.getElementById("explorer-button") -var startbutton=document.getElementById("start-stop-innertext") -async function start_button(){ - try{ - if(!scan_started){ - currentSection=0; - console.log("Starting scan...") - var res= await awManager.startWatchers() - console.log(res) - await awManager.update_start_flag() - updatebutton.className="default-button-deactivated" - startbutton.innerHTML=`Stop Scan  ` - explorerbutton.className="default-button" - scan_started=true - timer("ready_status") - }else{ - currentSection=0; - console.log("stopping scan...") - var res=await awManager.stopWatchers() - console.log(res) - updatebutton.className="default-button" - startbutton.innerHTML=`Resume Scan  ` - scan_started=false - } - }catch(e){ - console.log(e) - change_update_status(2) - } -} async function init_update_button(){ var start_event=await awManager.get_producer_event("last_start") if(Object.keys(start_event).length===0){ diff --git a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwManager.js b/1_ActivityWatchProducer/JS/PacModules/AwManager.js similarity index 99% rename from 1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwManager.js rename to 1_ActivityWatchProducer/JS/PacModules/AwManager.js index c98123dd..34401242 100644 --- a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwManager.js +++ b/1_ActivityWatchProducer/JS/PacModules/AwManager.js @@ -13,8 +13,8 @@ events_title = document.getElementById("events-title"); class AwManager extends AwProducer{ - constructor(){ - super() + constructor(jsap){ + super(jsap) this.current_watcher_index=0; this.tm=new TableManager("validation_body") this.atm= new ActivityTableManager("validation_body") @@ -164,7 +164,7 @@ class AwManager extends AwProducer{ //WRITE DATA INTO THE RAW TABLE //print_raw_json_to_textarea("raw_events_wrapper",json_object) //WRITE DATA INTO FORMATTED TABLE - consoleLog(0,json_object.length) + log.debug(json_object.length) //SE NON E' VUOTO ESEGUI if(json_object.length!=0){ //console.log(json_object) @@ -221,7 +221,7 @@ class AwManager extends AwProducer{ tablerows.appendChild(row); } }else{ - consoleLog(1,"skipped empty json") + log.info("skipped empty json") } } diff --git a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwProducer.js b/1_ActivityWatchProducer/JS/PacModules/AwProducer.js similarity index 92% rename from 1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwProducer.js rename to 1_ActivityWatchProducer/JS/PacModules/AwProducer.js index c245a20c..890c9769 100644 --- a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwProducer.js +++ b/1_ActivityWatchProducer/JS/PacModules/AwProducer.js @@ -12,11 +12,12 @@ const JsapApi = Sepajs.Jsap; //console.log(JSON.stringify(default_jsap)) class AwProducer extends AwMy2SecClient{ - constructor(){ - super("127.0.0.1:5000") + constructor(jsap){ + super(jsap) //this.mc= new My2secClient() - this.queryBenchClient= new Sepajs.SEPA(default_jsap) - this.sepaClient= new JsapApi(default_jsap) + this.sepa_host_string=jsap.host + this.queryBenchClient= new Sepajs.SEPA(jsap) + this.sepaClient= new JsapApi(jsap) this.whitelistedWatchers="aw-watcher-working,aw-watcher-afk,aw-watcher-notshutdown,aw-watcher-start-stop"//"aw-watcher-working,aw-watcher-afk,aw-watcher-scan"; this.watchersJson={}; this.eventsRawJson=[]; @@ -28,10 +29,10 @@ class AwProducer extends AwMy2SecClient{ } async startTests(){ - log.info("testing connections...") - log.debug("log_level set to error to avoid console cluttering") - var temp=log.loglevel - log.loglevel=1 + this.log.info("testing connections...") + this.log.debug("log_level set to error to avoid console cluttering") + var temp=this.log.loglevel + this.log.loglevel=1 var results={ "sepa":"", "aw":"", @@ -55,7 +56,7 @@ class AwProducer extends AwMy2SecClient{ results.aw="not-passed" } //test my2sec - log.loglevel=temp + this.log.loglevel=temp return results } @@ -93,10 +94,10 @@ class AwProducer extends AwMy2SecClient{ this.queryBenchClient.query("select ?time where { ?time}") .then((data)=>{ log.info("Connected to SEPA!"); - sepa_cbox.innerHTML="Connected to SEPA ("+default_jsap.host /*+":"+jsap.sparql11protocol.port*/ +")" + sepa_cbox.innerHTML="Connected to SEPA ("+this.sepa_host_string /*+":"+jsap.sparql11protocol.port*/ +")" resolve(data); - document.getElementById("row-2").style.display="flex"; + //document.getElementById("row-2").style.display="flex"; }); }); } @@ -129,7 +130,6 @@ class AwProducer extends AwMy2SecClient{ console.log(this.start_time_json) this.eventsRawJson=await this.get_filtered_watchers_events() for(var key in this.watchersJson){ - this.eventsJson[key] = JSON.parse(this.eventsRawJson[key]); this.eventsRawJson[key]=this.eventsRawJson[key].replace(/\\/g,"\\\\");//BUGFIX this.eventsRawJson[key]=this.eventsRawJson[key].replace(/\"/g,"\\\"");//BUGFIX @@ -259,17 +259,17 @@ class AwProducer extends AwMy2SecClient{ } //alert(number_of_filtered_watchers) if(filtering_active==1){ - consoleLog(0,"FILTERED WATCHERS!") + log.debug("FILTERED WATCHERS!") //OVERRIDE GLOBAL VARIABLE watchers_json=filtered_watchers_json; }else{ - consoleLog(2,"USING UNFILTERED WATCHERS, MAY LEAD TO INSTABILITY") + log.warning("USING UNFILTERED WATCHERS, MAY LEAD TO INSTABILITY") } //consoleLog(0,JSON.stringify(watchers_json)); //alert("ciao") //[0.1] CREATE AW PRODUCER BUCKET IF IT DOES NOT EXISTS if(aw_producer_exists==0){ - consoleLog(0,"FIRST RUN, CREATING AW PRODUCER") + log.debug("FIRST RUN, CREATING AW PRODUCER") await this.create_producer_bucket(); } //RETURN WATCHERS JSON OBJECT @@ -309,7 +309,7 @@ class AwProducer extends AwMy2SecClient{ }else{ //GET ALL EVENTS - consoleLog(1,"first run, fetching all events") + log.info("first run, fetching all events") end_time = get_current_timestamp();//FIX BUG ON FIRST START for(key in this.watchersJson){ try{ @@ -365,10 +365,10 @@ class AwProducer extends AwMy2SecClient{ function update_sepa_message(jsonMessage,watcher_client,watcher_hostname){ //var string="insert { '''"+JSON.stringify(jsonMessage)+"'''} where{}" var string="insert { _:b '''"+JSON.stringify(jsonMessage)+"'''; '''"+watcher_client+"'''; '''"+watcher_hostname+"'''} where{}" - consoleLog(0,string) + log.debug(string) client.update(string) .then(()=>{ - consoleLog(1,"update_sepa_message: "+watcher_client +" EVENTS UPLOADED CORRECTLY!") + log.info("update_sepa_message: "+watcher_client +" EVENTS UPLOADED CORRECTLY!") }); } @@ -378,10 +378,10 @@ function update_user_sepa_message(jsonMessage,watcher_client,username){ //var string="insert { '''"+JSON.stringify(jsonMessage)+"'''} where{}" return new Promise(resolve=>{ var string="insert { graph {_:b '''"+jsonMessage+"'''}} where{}" - consoleLog(0,string) + log.debug(string) client.update(string) .then(()=>{ - consoleLog(1,"update_sepa_message: "+watcher_client +" EVENTS UPLOADED CORRECTLY!") + log.info("update_sepa_message: "+watcher_client +" EVENTS UPLOADED CORRECTLY!") resolve("updated"); }); @@ -394,10 +394,10 @@ function update_user_timed_sepa_message(jsonMessage,watcher_client,username,time //var string="insert { '''"+JSON.stringify(jsonMessage)+"'''} where{}" return new Promise(resolve=>{ var string="insert { graph {_:b '''"+jsonMessage+"''' ; ; '''"+timestamp+"'''}} where{}" - consoleLog(0,string) + log.debug(string) client.update(string) .then(()=>{ - consoleLog(1,"update_sepa_message: "+watcher_client +" EVENTS UPLOADED CORRECTLY!") + log.info("update_sepa_message: "+watcher_client +" EVENTS UPLOADED CORRECTLY!") resolve("updated"); }); diff --git a/1_ActivityWatchProducer/lib/TasksConsumer/tasksConsumer.js b/1_ActivityWatchProducer/JS/PacModules/tasksConsumer.js similarity index 93% rename from 1_ActivityWatchProducer/lib/TasksConsumer/tasksConsumer.js rename to 1_ActivityWatchProducer/JS/PacModules/tasksConsumer.js index 373e1c7c..7e4f9d1e 100644 --- a/1_ActivityWatchProducer/lib/TasksConsumer/tasksConsumer.js +++ b/1_ActivityWatchProducer/JS/PacModules/tasksConsumer.js @@ -1,7 +1,8 @@ class TasksConsumer{ - constructor(email){ - this.queryBenchClient= new Sepajs.SEPA(default_jsap) - this.sepaClient= new JsapApi(default_jsap) + constructor(jsap,email){ + var log=new Greglogs(); + this.queryBenchClient= new Sepajs.SEPA(jsap) + this.sepaClient= new JsapApi(jsap) this.sub; this.tasksCache=[] this.email=email; diff --git a/1_ActivityWatchProducer/lib/UserInfo/UserInfoConsumer.js b/1_ActivityWatchProducer/JS/UserInfo/UserInfoConsumer.js similarity index 94% rename from 1_ActivityWatchProducer/lib/UserInfo/UserInfoConsumer.js rename to 1_ActivityWatchProducer/JS/UserInfo/UserInfoConsumer.js index 34d45178..e85b3ebf 100644 --- a/1_ActivityWatchProducer/lib/UserInfo/UserInfoConsumer.js +++ b/1_ActivityWatchProducer/JS/UserInfo/UserInfoConsumer.js @@ -1,6 +1,7 @@ class UserInfoConsumer { - constructor(usermail){ - this.sepaConsumer= new Sepajs.SEPA(default_jsap) + constructor(jsap,usermail){ + var log=new Greglogs(); + this.sepaConsumer= new Sepajs.SEPA(jsap) this.userName=""; this.usermail=usermail; //log.info("New UserInfoConsumer created!") @@ -19,12 +20,11 @@ class UserInfoConsumer { } logspan_subEventsCount(element){ - consoleLog(1,"SUBSCRIBING TO EVENTS COUNT") + log.debug("SUBSCRIBING TO EVENTS COUNT") var counter_el=document.getElementById(element); const sub = this.sepaConsumer.subscribe("select (COUNT(?nodeid) AS ?nevents) where { graph {?nodeid }} ") //[0]ON SUBSCRIBE sub.on("subscribed",console.log) - //g.consoleLog(1,"#### LISTENING TO NOTIFICATIONS ###\n") //[1]ON NOTIFICATION sub.on("notification", not => { var bindings=this.extract_bindings(not); diff --git a/1_ActivityWatchProducer/JS/greglogs.js b/1_ActivityWatchProducer/JS/greglogs.js deleted file mode 100644 index 06616641..00000000 --- a/1_ActivityWatchProducer/JS/greglogs.js +++ /dev/null @@ -1,115 +0,0 @@ -//CREATE DATE OBJECT -+ new Date(); -//LOG LEVELS -var log_level=0; //debug=0, essential=1, error/warning=2 - - -class GregLogs{ - constructor() { - this.loglevel=0; - //this.info("New Greglogs logger created!") - } - //========= - //[3] LOG - //logLevel(level){ - // this.loglevel=level; - //} - - //TABLES - trace_table(table){ - if(this.loglevel<1){ - console.table(table); - } - } - debug_table(table){ - if(this.loglevel<2){ - console.table(table); - } - } - info_table(table){ - if(this.loglevel<3){ - console.table(table); - } - } - - //TEXT - trace(text){ - if(this.loglevel<1){ - console.log(this.get_current_timestamp()+" | [trace] "+text); - } - } - debug(text){ - if(this.loglevel<2){ - console.log(this.get_current_timestamp()+" | [debug] "+text); - } - } - info(text){ - if(this.loglevel<3){ - console.log(this.get_current_timestamp()+" | [info] "+text); - } - } - warning(text){ - if(this.loglevel<4){ - console.log(this.get_current_timestamp()+" | [warning] "+text); - } - } - error(text){ - console.log(this.get_current_timestamp()+" | [error] "+text); - } - - //---------------------- - //NAME: GET CURRENT TIME - //DESCRIPTION: returns the current formatted time - get_current_timestamp(){ - const date=new Date(); - var string_timestamp=date.toISOString() - //console.log(stringa) - return string_timestamp - }//get_current_timestamp() -} - -log = new GregLogs(0) - - - - - - -//============================================ - -function consoleLog(level,argument){ - if (level>=log_level){ - - if(level==0){ - console.log(get_time()+" [DEBUG] "+argument) - }else{ - if(level==1){ - console.log(get_time()+" [INFO] "+argument) - }else{ - console.log(get_time()+" [WARNING] "+argument) - } - } - - - } -} - -function get_time(){ - var UTC=2; - var t_seconds=Math.floor(Date.now() / 1000); - var t_days=(t_seconds/(3600*24)); - - var float_h=(t_days-Math.floor(t_days))*24; - var hours=Math.floor(float_h); - var utc_hours=hours+UTC; - - var float_m=(float_h-hours)*60; - var minutes=Math.floor(float_m); - - var float_s=(float_m-minutes)*60; - var seconds=Math.floor(float_s); - - var timestring=utc_hours+":"+minutes+":"+seconds - //console.log(timestring) - return timestring -} \ No newline at end of file diff --git a/1_ActivityWatchProducer/JS/main.js b/1_ActivityWatchProducer/JS/main.js index 03a80e0d..8c610060 100644 --- a/1_ActivityWatchProducer/JS/main.js +++ b/1_ActivityWatchProducer/JS/main.js @@ -5,9 +5,11 @@ || DESCRIPTION: initializes the application and defines || some major functions \\---------------------------------------------------------*/ +var log=new Greglogs(); var cache=[] //CLIENTS let awManager; +let scanManager; let userInfoConsumer; let awApiUpdateManager; //GLOBAL @@ -26,47 +28,53 @@ console.log("|| ActivityWatch PRODUCER ||") console.log("\\\\------------------------//") //INITIAL CONFIGURATION init(); - //================================== // init: INITIALIZES THE APPLICATION // modules: user credentials, superset dashboard, tasks async function init(){ - log.info("Initializing App Modules") + log.info("Initializing Application") + var json_package=await window.versions.request_user_credentials(); + json_package=JSON.parse(json_package)//contains jsap and user credentials + console.log(json_package) + + + log.info("----------< Init ACTIVITYWATCH Client, test datasources >----------") //IF THIS SECTION FAILS, THE APP EXECUTION MUST STOP - awManager = new AwManager(); - log.info("------TEST DATASOURCES----------------------") + awManager = new AwManager(json_package["my2sec_jsap"]); + log.info("** TEST DATASOURCES **") var test_results=await awManager.startTests(); - console.log(test_results) + console.table(test_results) Object.keys(test_results).forEach(k=>{ if(test_results[k]=="not-passed"){ throw new Error("Datasource error: ") } }) - log.info("-------TEST COMPLETE------------------------") - console.log(" ") + log.info("** TEST PASSED, DATASOURCES ONLINE! **") + //TRY TO STOP WATCHERS AT STARTUP TO AVOID BUGS console.log("PROVO A SPEGNERE I WATCHERS") awManager.stopWatchers() - + console.log(" ") //THIS SECTION MUST ALSO NOT FAIL, SO I WILL NOT CATCH ANY ERROR - log.info("# KEYCLOAK #") + log.info("----------< Init UserInfoManager >----------") log.debug("getting keycloak user credentials from node...") - const user_credentials_string = await window.versions.request_user_credentials() - const user_credentials_json=JSON.parse(user_credentials_string) - log.trace_table(user_credentials_json) + //const user_credentials_string = await window.versions.request_user_credentials() + //const user_credentials_json=JSON.parse(user_credentials_string) + const user_credentials_json=json_package["user_login_json"]; + log.info_table(user_credentials_json) log.info("Fetched user information correctly") - userInfoConsumer= new UserInfoConsumer(user_credentials_json.email) + userInfoConsumer= new UserInfoConsumer(json_package["my2sec_jsap"],user_credentials_json.email) await userInfoConsumer.sepa_getUserName(); log.debug("User info consumer initialized with data: Email("+userInfoConsumer.usermail+"), username("+userInfoConsumer.userName+")") // prints out 'pong' userInfoConsumer.logspan_username("user_name_welcome") userInfoConsumer.logspan_usermail("user_name"); - userInfoConsumer.logspan_subEventsCount("sub_counter") - + //userInfoConsumer.logspan_subEventsCount("sub_counter") + console.log(" ") - log.info("# SUPERSET DASHBOARD #") + log.info("----------< Init SUPERSET dashboard >----------") try{ var dash_id=await userInfoConsumer.sepa_getUserDashboard();//"755f0434-6ac6-4d4f-8415-3b2b80c571e9"; log.info("Fetched dashboard_id of "+userInfoConsumer.userName+" :"+dash_id) @@ -76,105 +84,45 @@ async function init(){ }catch(e){ console.log(e) } + console.log(" ") - log.info("### LOADING TASKS ###") + log.info("----------< Init TASKS dashboard >----------") let tasksConsumer; try{ - tasksConsumer = new TasksConsumer(userInfoConsumer.usermail); + tasksConsumer = new TasksConsumer(json_package["my2sec_jsap"],userInfoConsumer.usermail); + log.info("** start task consumer **") tasksConsumer.start() //tasksConsumer.generate_tasks_template("task-wrapper") + //log.info("tasks consumed") }catch(e){ console.log(e) } + console.log(" ") //INIT THE CLASS OF THE UPDATE BUTTON + log.info("----------< Init CONTROL PANEL >----------") + //await initControlPanel(); + + scanManager=new ScanManager(json_package["my2sec_jsap"]); + scanManager.logStatus(); + init_update_button() //INIT VALIDATION PROCEDURE //awApiUpdateManager=new AwApiUpdateManager(default_jsap,awManager,userInfoConsumer,tasksConsumer) //awApiUpdateManager.start(); - awApiUpdateManager=new AwApiUpdateManager(default_jsap,awManager,userInfoConsumer,tasksConsumer) + awApiUpdateManager=new AwApiUpdateManager(json_package["my2sec_jsap"],awManager,userInfoConsumer,tasksConsumer) //test() - /* - let flagsub=awManager.sepaClient.GET_USER_SYNCHRONIZATION_FLAG({ - flag_type:"http://www.vaimee.it/my2sec/trainingactivitiesflag", - usergraph:"http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail - }) - var firstTime=true - flagsub.on("notification",not=>{console.log(not)}) - */ - - //DA QUI INIZIAVA - /* - let trainingactivitiessub=awManager.sepaClient.USER_TRAINING_ACTIVITIES({ - usergraph:"http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail - }) - let flagsub=awManager.sepaClient.GET_SYNCHRONIZATION_FLAG({ - flag_type:"http://www.vaimee.it/my2sec/trainingactivitiesflag" - //usergraph:"http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail - }) - - var firstActivity=true; - trainingactivitiessub.on("notification",not=>{ - if(firstActivity){ - firstActivity=false; - }else{ - console.log("ACTIVITIES RECEIVED!") - console.log(not) - if(not.removedResults.results.bindings.length==0){ //on added results - //trainingactivitiessub.unsubscribe(); - var bindings=not.addedResults.results.bindings - for(var i in bindings){ - for(var k in bindings[i]){ - bindings[i][k]=bindings[i][k].value - } - cache.push(bindings[i]) - } - }else{ - console.log("ignored removed activities") - } - } - }) - var firstTime=true - flagsub.on("notification",not=>{ - console.log("FLAG NOTIFICATION: "+JSON.stringify(not)) - if(firstTime){ - console.log("first flag") - firstTime=false; - }else{ - - try{ - console.log("FLAG RECEIVED!") - console.log(not) - if(not.removedResults.results.bindings.length==0){ - if(not.addedResults.results.bindings[0].usergraph.value=="http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail){ - var syncresponse=awManager.sepaClient.RESET_SYNCHRONIZATION_FLAG({ - flag:not.addedResults.results.bindings[0].flag.value - }) - //flagsub.unsubscribe() - console.log("calling on_received_training_activities, cache: "+JSON.stringify(cache)) - on_received_training_activities(cache) - cache=[]; - //console.log(e) - }else{ - console.log("ignored flag") - } - }else{ - console.log("ignored removed flag") - } - }catch(e){console.log(e)} - } - //}//END OF IF - }) - */ - } + + + /* async function test(){ console.log("TESTING") @@ -368,313 +316,6 @@ function set_all_rows_to_value(value){ awApiUpdateManager.awManager.tm.set_all_rows_to_value(value) } -/* -var vpanel=document.getElementById("validation_wrapper"); -var opanel=document.getElementById("validation_obscurer"); -//open validation panel -async function start_update_procedure(){ - if(updatebutton.className=="default-button-deactivated"){ - throw new Error("Error: button is deactivated. Start and then stop a scan to activate this function") - } - vpanel.style.display="block" - opanel.style.display="block" - awManager.initialize_validation_procedure() -} -async function abort_update_procedure(){ - vpanel.style.display="none" - opanel.style.display="none" -} -*/ -/* -async function on_validation_button_pressed(){ - if(currentSection==0){ - confirm_and_upload() - }else{ - send_validated_activities() - } - currentSection++ -} -*/ -/* -async function confirm_and_upload(){ - if(!confirm("Are you sure?")){ - throw new Error("UPLOAD ABORTED!") - } - - console.log("### STARTING AI UPLOAD ###") - - var arr=awManager.tm.logicalArray//Json styled csv - console.log("proceeding to send: ") - console.table(arr) - if(!(Object.keys(arr).length===0)){ - console.log(arr) - var newKnowledgeCell={} - for(var k in arr){ - var field=[] - for(var i in arr[k]){ - field.push(arr[k][i]) - } - newKnowledgeCell[k]=field; - } - newKnowledgeCell=JSON.stringify(newKnowledgeCell) - console.log(newKnowledgeCell) - await awManager.setWorkEvents(newKnowledgeCell) - - var success=await awManager.getCsvNone() - console.log(success) - if(success=="True"){ - throw new Error("None events are present in Csv") - } - }else{ - console.log("NOTHING TO SHOW, PROCEEDING WITH SENDING EVENTS") - } - - var success=await awManager.sendCurrentCsv() - console.log(success) - - //ON SUCCESS... - await awManager.uploadQuery() - await send_messages_to_sepa() - -} -*/ -//update verfied data to sepa -/* -async function send_messages_to_sepa(){ - consoleLog(1,"### BUTTON PRESSED, STARTING SEPA UPLOAD ###") - change_update_status(3)//activate loading spinner - - console.log(" ") - - //UPDATE MESSAGE - var update_success_flag=1; - var response; - var data={}; - for (var key in awManager.watchersJson) { - try{ - var msgtimestamp=get_current_timestamp(); - //response=await update_user_timed_sepa_message(EVENTS_RAWJSON[key],WATCHERS_JSON[key].client,curruser,msgtimestamp); - - //BUGFIX - if(!awManager.watchersJson[key].id.includes(awManager.watchersJson[key].client)){ - //l'id e il client name sono diversi, seleziona l'id - log.warning("id and clientname of watcher do not match, using sliced id as clientname...") - var index=awManager.watchersJson[key].id.lastIndexOf("_") - awManager.watchersJson[key].client=awManager.watchersJson[key].id.slice(0,index) - log.warning(awManager.watchersJson[key].client) - } - - data={ - message_graph: "http://www.vaimee.it/my2sec/messages/activitywatch", - usergraph: "http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail, - source: "http://www.vaimee.it/sources/"+awManager.watchersJson[key].client, - msgtimestamp: msgtimestamp, - msgvalue: awManager.eventsRawJson[key] - } - consoleLog(0,"Usergraph: "+data.usergraph) - consoleLog(0,"Source: "+data.source) - consoleLog(0,"Timestamp: "+data.msgtimestamp) - consoleLog(0,"Message: "+data.msgvalue) - response=await awManager.sepaClient.SEND_MESSAGE(data) - consoleLog(0,"RESPONSE: "+JSON.stringify(response)) - data={}//wipe data - }catch(e){ - console.log(e); - update_success_flag=0; - } - } - - if(update_success_flag==1){ - change_update_status(1) - if(silent_update==0){ - begin_activities_validation(); - //WHEN ALL UPDATES ARE DONE, CREATE UPDATE EVENT - //UNCOMMENT TO RESUME UPDATE - var syncresponse=await awManager.sepaClient.SET_SYNCHRONIZATION_FLAG({ - flag_type:"http://www.vaimee.it/my2sec/awproducerflag", - usergraph:"http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail - }) - console.log("Sync flag response: "+JSON.stringify(syncresponse)) - console.log("UPDATING TIMESTAMP") - await awManager.update_event("{ \"timestamp\": \""+get_current_timestamp()+"\", \"duration\": 0, \"data\": {\"last_update\":\""+get_current_timestamp()+"\"} }") - //alert("UPDATED!"); - init_update_button() - console.log("SUCCESS!") - - - - - //var loadingbar=document.getElementById("loading_bar"); - //loadingbar.style.animation="load 1s linear" - }else{ - console.log("SILENT UPDATE, PRODUCER TIMESTAMP DID NOT CHANGE") - change_update_status(1) - } - - - }else{ - //alert("UPDATE FAILED!") - change_update_status(2) - } - -} -*/ -var dt=[{ - "usergraph": { - "type": "uri", - "value": "http://www.vaimee.it/defuser" - }, - "event_type": { - "type": "uri", - "value": "my2sec:windowEvent" - }, - "datetimestamp": { - "type": "literal", - "value": "2022-08-10T15:33:42.503000+00:00" - }, - "app": { - "type": "literal", - "value": "chrome.exe" - }, - "title": { - "type": "literal", - "value": "youtube" - }, - "activity_type": { - "type": "uri", - "value": "my2sec:Developing" - }, - "task": { - "type": "literal", - "value": "WP2-IMPLEMENTAZIONE COMPONENTI" - }, - "duration": { - "type": "literal", - "value": "16.0" - } -}, -{ - "usergraph": { - "type": "uri", - "value": "http://www.vaimee.it/defuser" - }, - "event_type": { - "type": "uri", - "value": "my2sec:windowEvent" - }, - "datetimestamp": { - "type": "literal", - "value": "2022-08-10T15:33:42.503000+00:00" - }, - "app": { - "type": "literal", - "value": "chrome.exe" - }, - "title": { - "type": "literal", - "value": "youtube" - }, - "activity_type": { - "type": "uri", - "value": "my2sec:Developing" - }, - "task": { - "type": "literal", - "value": "WP2-IMPLEMENTAZIONE COMPONENTI" - }, - "duration": { - "type": "literal", - "value": "16.0" - } -} -] - -//on_received_training_activities(dt) -//ACTIVITIES VALIDATION -/* -function begin_activities_validation(){ - document.getElementById("vs1").className="validation_section"; - document.getElementById("vs2").className="validation_section-selected"; - document.getElementById("validation_body").innerHTML=""; - console.log("BEGINNING ACTIVITIES PROCEDURE") - change_update_status(0); -} - -function on_received_training_activities(bindings){ - console.log("Setting original bindings:") - console.log(bindings) - awManager.atm.originalBindings=bindings; - var known_categories="Developing,Meeting,Researching,Testing,Other,Email" - console.log("Injecting table") - awManager.atm.injectTable(bindings,"activity_type,app,title,duration,datetimestamp",known_categories) - if(!awManager._jsonEmpty(bindings)){ - $(document).ready( function () { - var events_table=$("#wst").DataTable(); - } ); - }else{ - console.log("ERROR: JSON CAN'T BE EMPTY") - change_update_status(2) - } - //on_validated_activities() -} - -async function send_validated_activities(){ - change_update_status(3); - var arr=awManager.atm.logicalArray//Json styled csv - console.log(arr) - //throw new Error("MAO") - var ok=0; - try{ - for(var i in arr){ - arr[i]["usergraph"]="http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail - - var title=arr[i]["title"].replace(/\\/g,"\\\\");//PRIMA LE DOPPIE SBARRE - title=title.replace(/\'/g,"\\\'"); //POI GLI ASTERISCHI - arr[i]["title"]=title; - console.log(arr[i]) - - var syncresponse=await awManager.sepaClient.ADD_VALIDATED_ACTIVITY(arr[i]) - console.log("Add validated activity response: "+JSON.stringify(syncresponse)) - } - - try{ - - - var toRemove=awManager.atm.originalBindings; - console.log("REMOVING: ") - console.log(toRemove) - for(var i in toRemove){ - var syncresponse=await awManager.sepaClient.REMOVE_TRAINING_ACTIVITY({ - activity: toRemove[i].nodeid - }) - console.log("Remove training activity response: "+JSON.stringify(syncresponse)) - } - - }catch(e){ - console.log(e) - } - - var syncresponse=await awManager.sepaClient.SET_SYNCHRONIZATION_FLAG({ - flag_type:"http://www.vaimee.it/my2sec/validatedactivitiesflag", - usergraph:"http://www.vaimee.it/my2sec/"+userInfoConsumer.usermail - }) - console.log("Sync flag response: "+JSON.stringify(syncresponse)) - ok=1; - }catch(e){ - console.log(e) - ok=0; - } - if(ok==1){ - change_update_status(1) - document.getElementById("success_status").innerHTML="Success! You can view your tasks on OpenProject" - }else{ - change_update_status(2) - } - -} -*/ - - //===================== // UTILITIES FUNCTIONS @@ -696,34 +337,6 @@ function fake_send(){ alert("this button is outdated, please use the update button in the home screen") } -/* -function change_update_status(type){ - //$("ready_status").style.display="none"; - //HIDE ALL - //document.getElementById("ready_status").style.display="none"; - document.getElementById("success_status").style.display="none"; - document.getElementById("error_status").style.display="none"; - document.getElementById("update_spinner").style.display="none"; - //0 ready, 1 success, 2 error, 3 spinner - switch (type) { - case 0: - console.log("status box removed") - //document.getElementById("ready_status").style.display="block"; - break; - case 1: - document.getElementById("success_status").style.display="block"; - break; - case 2: - document.getElementById("error_status").style.display="block"; - break; - case 3: - document.getElementById("update_spinner").style.display="block"; - break; - default: - break; - } -}*/ - async function timer(span){ while(scan_started){ await wait("1000") diff --git a/1_ActivityWatchProducer/lib/my2sec-FULL_271022.js b/1_ActivityWatchProducer/Resources/my2sec-FULL_271022.js similarity index 100% rename from 1_ActivityWatchProducer/lib/my2sec-FULL_271022.js rename to 1_ActivityWatchProducer/Resources/my2sec-FULL_271022.js diff --git a/1_ActivityWatchProducer/lib/my2sec-jena_251122.jsap.js b/1_ActivityWatchProducer/Resources/my2sec-jena_251122.jsap.js similarity index 100% rename from 1_ActivityWatchProducer/lib/my2sec-jena_251122.jsap.js rename to 1_ActivityWatchProducer/Resources/my2sec-jena_251122.jsap.js diff --git a/1_ActivityWatchProducer/lib/my2sec-jena_251122.jsap.txt b/1_ActivityWatchProducer/Resources/my2sec-jena_251122.jsap.txt similarity index 100% rename from 1_ActivityWatchProducer/lib/my2sec-jena_251122.jsap.txt rename to 1_ActivityWatchProducer/Resources/my2sec-jena_251122.jsap.txt diff --git a/1_ActivityWatchProducer/lib/my2sec_19-1-2023.jsap.js b/1_ActivityWatchProducer/Resources/my2sec_19-1-2023.jsap.js similarity index 99% rename from 1_ActivityWatchProducer/lib/my2sec_19-1-2023.jsap.js rename to 1_ActivityWatchProducer/Resources/my2sec_19-1-2023.jsap.js index 3989c2ee..3ab9b3e0 100644 --- a/1_ActivityWatchProducer/lib/my2sec_19-1-2023.jsap.js +++ b/1_ActivityWatchProducer/Resources/my2sec_19-1-2023.jsap.js @@ -45,6 +45,16 @@ default_jsap={ }, "extended": { + "AwProducer": { + "endpoints":{ + "Keycloak": "https://keycloak.vaimee.org", + "ActivityWatch": "http://localhost:5000", + "My2secApi": "http://localhost:5600", + "MongoDb": "mongodb://root:Gregnet-99@dld.arces.unibo.it:27017/" + }, + "loglevel":0 + } + }, "updates": { "CREATE_USERNAMES_GRAPH":{ diff --git a/1_ActivityWatchProducer/Resources/my2sec_7-3-2023.jsap b/1_ActivityWatchProducer/Resources/my2sec_7-3-2023.jsap new file mode 100644 index 00000000..0d5e9d92 --- /dev/null +++ b/1_ActivityWatchProducer/Resources/my2sec_7-3-2023.jsap @@ -0,0 +1,717 @@ +{ + "host": "dld.arces.unibo.it", + "oauth": { + "enable": false, + "register": "https://localhost:8443/oauth/register", + "tokenRequest": "https://localhost:8443/oauth/token" + }, + "sparql11protocol": { + "protocol": "http", + "port": 8551, + "query": { + "path": "/query", + "method": "POST", + "format": "JSON" + }, + "update": { + "path": "/update", + "method": "POST", + "format": "JSON" + } + }, + "sparql11seprotocol": { + "protocol": "ws", + "availableProtocols": { + "ws": { + "port": 9551, + "path": "/subscribe" + }, + "wss": { + "port": 9443, + "path": "/secure/subscribe" + } + } + }, + "graphs": { + + }, + "namespaces": { + "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "rdfs": "http://www.w3.org/2000/01/rdf-schema#", + "xsd": "http://www.w3.org/2001/XMLSchema#", + "owl": "http://www.w3.org/2002/07/owl#", + "time":"http://www.w3.org/2006/time#", + "my2sec": "http://www.vaimee.it/ontology/my2sec#" + }, + "extended": { + + "AwProducer": { + "endpoints":{ + "Keycloak": "https://keycloak.vaimee.org", + "ActivityWatch": "http://localhost:5600", + "AwApiRouter": "http://localhost:1340", + "My2secApi": "http://localhost:5000", + "MongoDb": "mongodb://root:Gregnet-99@dld.arces.unibo.it:27017/", + "MongoDbRouter": "http://localhost:1341" + }, + "loglevel":0 + } + + }, + "updates": { + "CREATE_USERNAMES_GRAPH":{ + "sparql": "CREATE GRAPH " + }, + "DROP_USERNAMES_GRAPH":{ + "sparql":"DROP GRAPH " + }, + "ADD_USER":{ + "sparql":"INSERT DATA { GRAPH { ?usergraph my2sec:username ?username_literal }}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + }, + "username_literal": { + "type": "literal", + "value": "defuser" + } + } + }, + "CREATE_USER_PRIVATE_GRAPH":{ + "sparql":"CREATE GRAPH ?usergraph", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + } + } + }, + "REMOVE_USER":{ + "sparql":"DELETE {?s ?p ?o} WHERE { GRAPH { ?p ?o }}" + }, + "DELETE_USER_PRIVATE_GRAPH":{ + "sparql":"DROP GRAPH " + }, + + "DELETE_ALL_USER_DATA":{ + "sparql":"DELETE { GRAPH ?usergraph {?s ?p ?o}} WHERE { GRAPH ?usergraph { ?s ?p ?o }}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + } + } + }, + "SEND_MESSAGE":{ + "sparql":"INSERT { GRAPH ?message_graph {?b rdf:type my2sec:Message ; my2sec:hasMember ?usergraph ; my2sec:messageValue ?msgvalue; my2sec:messageSource ?source ; time:inXSDDateTimeStamp ?msgtimestamp }} WHERE {BIND(UUID() AS ?b)}", + "forcedBindings": { + "message_graph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/messages/activitywatch" + }, + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + }, + "source": { + "type": "uri", + "value": "http://www.vaimee.it/sources/aw-watcher-window" + }, + "msgtimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "msgvalue": { + "type": "literal", + "value": "{}" + } + } + }, + "DELETE_MESSAGE":{ + "sparql":"DELETE { GRAPH ?message_graph {?message ?p ?o }} WHERE { GRAPH ?message_graph {?message ?p ?o} }", + "forcedBindings": { + "message_graph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/messages/activitywatch" + }, + "message": { + "type": "uri", + "value": "urn:uuid:MessageUri" + } + } + }, + "ADD_TRAINING_EVENT":{ + "sparql":"INSERT {GRAPH { ?b rdf:type my2sec:TrainingEvent ; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:hasActivityType ?activity_type; my2sec:taskTitle ?task; my2sec:hasTimeInterval _:d . _:d rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration }} WHERE {BIND(UUID() AS ?b )}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + }, + "event_type": { + "type": "uri", + "value": "my2sec:WindowEvent" + }, + "datetimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "app": { + "type": "literal", + "value": "chrome.exe" + }, + "title": { + "type": "literal", + "value": "Portainer" + }, + "activity_type": { + "type": "uri", + "value": "my2sec:Developing" + }, + "task": { + "type": "literal", + "value": "WP2-IMPLEMENTAZIONE COMPONENTI" + }, + "duration": { + "type": "literal", + "value": "16.0" + } + } + }, + "ADD_EVENT":{ + "sparql":"INSERT {GRAPH { ?b rdf:type my2sec:Event ; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp}} WHERE {BIND(UUID() AS ?b)}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + }, + "event_type": { + "type": "uri", + "value": "my2sec:WindowEvent" + }, + "datetimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "app": { + "type": "literal", + "value": "chrome.exe" + }, + "title": { + "type": "literal", + "value": "youtube" + } + } + }, + "REMOVE_EVENT":{ + "sparql":"DELETE {GRAPH {?event ?p ?o} } WHERE{ GRAPH { ?event ?p ?o }}", + "forcedBindings": { + "event": { + "type": "uri", + "value": "urn:uuid:EventX" + } + } + }, + "REMOVE_TRAINING_EVENT":{ + "sparql":"DELETE {GRAPH {?event ?p ?o ; my2sec:hasTimeInterval ?d . ?d ?p1 ?o1} } WHERE{ GRAPH {?event ?p ?o ; my2sec:hasTimeInterval ?d . ?d ?p1 ?o1}}", + "forcedBindings": { + "event": { + "type": "uri", + "value": "urn:uuid:EventX" + } + } + }, + "ADD_ACTIVITY":{ + "sparql":"INSERT {GRAPH {?b rdf:type my2sec:Activity ; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:taskTitle ?task; my2sec:hasTimeInterval _:d . _:d rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration }} WHERE {BIND(UUID() AS ?b)}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + }, + "event_type": { + "type": "uri", + "value": "my2sec:windowEvent" + }, + "datetimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "app": { + "type": "literal", + "value": "chrome.exe" + }, + "title": { + "type": "literal", + "value": "Portainer" + }, + "activity_type": { + "type": "uri", + "value": "my2sec:Developing" + }, + "task": { + "type": "literal", + "value": "WP2-IMPLEMENTAZIONE COMPONENTI" + }, + "duration": { + "type": "literal", + "value": "16.0" + } + } + }, + "ADD_VALIDATED_ACTIVITY":{ + "sparql":"INSERT {GRAPH {?b rdf:type my2sec:ValidatedActivity ; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:taskTitle ?task; my2sec:hasTimeInterval _:d . _:d rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration }} WHERE {BIND(UUID() AS ?b)}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/defuser" + }, + "event_type": { + "type": "uri", + "value": "my2sec:windowEvent" + }, + "datetimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "app": { + "type": "literal", + "value": "chrome.exe" + }, + "title": { + "type": "literal", + "value": "youtube" + }, + "activity_type": { + "type": "uri", + "value": "my2sec:developement" + }, + "task": { + "type": "literal", + "value": "WP2-IMPLEMENTAZIONE COMPONENTI" + }, + "duration": { + "type": "literal", + "value": "16.0" + } + } + }, + "ADD_TRAINING_ACTIVITY":{ + "sparql":"INSERT {GRAPH {?b rdf:type my2sec:TrainingActivity ; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:taskTitle ?task; my2sec:hasTimeInterval _:d . _:d rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration }} WHERE {BIND(UUID() AS ?b)}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/defuser" + }, + "event_type": { + "type": "uri", + "value": "my2sec:windowEvent" + }, + "datetimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "app": { + "type": "literal", + "value": "chrome.exe" + }, + "title": { + "type": "literal", + "value": "youtube" + }, + "activity_type": { + "type": "uri", + "value": "my2sec:developement" + }, + "task": { + "type": "literal", + "value": "WP2-IMPLEMENTAZIONE COMPONENTI" + }, + "duration": { + "type": "literal", + "value": "16.0" + } + } + }, + + + + "REMOVE_ACTIVITY":{ + "sparql":"DELETE {GRAPH {?activity ?p ?o ; my2sec:hasTimeInterval ?d . ?d ?p1 ?o1} } WHERE{ GRAPH {?activity ?p ?o ; my2sec:hasTimeInterval ?d . ?d ?p1 ?o1}}", + "forcedBindings": { + "activity": { + "type": "uri", + "value": "urn:uuid:ActivityX" + } + } + }, + "REMOVE_TRAINING_ACTIVITY":{ + "sparql":"DELETE {GRAPH {?activity ?p ?o ; my2sec:hasTimeInterval ?d . ?d ?p1 ?o1} } WHERE{ GRAPH {?activity ?p ?o ; my2sec:hasTimeInterval ?d . ?d ?p1 ?o1}}", + "forcedBindings": { + "activity": { + "type": "uri", + "value": "urn:uuid:ActivityX" + } + } + }, + "REMOVE_VALIDATED_ACTIVITY":{ + "sparql":"DELETE {GRAPH {?activity ?p ?o ; my2sec:hasTimeInterval ?d . ?d ?p1 ?o1} } WHERE{ GRAPH {?activity ?p ?o ; my2sec:hasTimeInterval ?d . ?d ?p1 ?o1}}", + "forcedBindings": { + "activity": { + "type": "uri", + "value": "urn:uuid:ActivityX" + } + } + }, + + "OLD_REMOVE_ACTIVITY":{ + "sparql":"DELETE{ GRAPH { ?bnode rdf:type my2sec:Activity; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:taskTitle ?task; my2sec:hasTimeInterval ?d . ?d rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration }} WHERE{ GRAPH { ?bnode rdf:type my2sec:Activity; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:taskTitle ?task; my2sec:hasTimeInterval ?d . ?d rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration }}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "" + }, + "event_type": { + "type": "uri", + "value": "my2sec:windowEvent" + }, + "datetimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "app": { + "type": "literal", + "value": "chrome.exe" + }, + "title": { + "type": "literal", + "value": "youtube" + }, + "activity_type": { + "type": "uri", + "value": "my2sec:developement" + }, + "task": { + "type": "literal", + "value": "WP2-IMPLEMENTAZIONE COMPONENTI" + }, + "duration": { + "type": "literal", + "value": "16.0" + } + } + }, + "SEND_OP_MESSAGE":{ + "sparql":"INSERT { GRAPH ?usergraph {?b rdf:type my2sec:Message ; my2sec:messageValue ?msgvalue; my2sec:messageSource ?source ; time:inXSDDateTimeStamp ?msgtimestamp}} WHERE {BIND(UUID() AS ?b)} ", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/admin@vaimee.it" + }, + "source": { + "type": "uri", + "value": "http://www.vaimee.it/sources/open-project" + }, + "msgtimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "msgvalue": { + "type": "literal", + "value": "{}" + } + } + }, + "CREATE_PROJECTS_GRAPH":{ + "sparql":"CREATE GRAPH " + }, + "UPDATE_PROJECT":{ + "sparql":"WITH DELETE { ?projecturi rdf:type my2sec:Project; my2sec:projectId ?del_project_id; my2sec:projectIdentifier ?del_project_identifier } INSERT { ?projecturi rdf:type my2sec:Project; my2sec:projectId ?projectid; my2sec:projectIdentifier ?project_identifier } WHERE { OPTIONAL { ?projecturi rdf:type my2sec:Project; my2sec:projectId ?del_project_id; my2sec:projectIdentifier ?del_project_identifier}}", + "forcedBindings": { + "projecturi": { + "type": "uri", + "value": "http://www.vaimee.it/projects#demo-project" + }, + "projectid": { + "type": "literal", + "value": 1, + "datatype": "xsd:integer" + }, + "project_identifier": { + "type": "literal", + "value": "Demo Project" + } + } + }, + "ADD_TASK":{ + "sparql":"INSERT { GRAPH ?graph { ?b rdf:type my2sec:Task ; my2sec:hasProject ?projecturi ; my2sec:taskId ?task_id; my2sec:taskTitle ?task_title; my2sec:hasMember ?assignee; my2sec:spentTime _:timenode . _:timenode rdf:type time:Duration; time:unitType time:unitHour ; time:numericDuration ?spent_time }} WHERE {BIND(UUID() AS ?b)}", + "forcedBindings": { + "graph": { + "type": "uri", + "value": "http://www.vaimee.it/projects#" + }, + "projecturi": { + "type": "uri", + "value": "http://www.vaimee.it/projects#demo-project" + }, + "task_id": { + "type": "literal", + "value": 1, + "datatype": "xsd:integer" + }, + "task_title": { + "type": "uri", + "value": "ATaskTitle" + }, + "assignee": { + "type": "uri", + "value": "http://www.vaimee.it/members/gregorio.monari@gmail.com" + }, + "spent_time": { + "type": "literal", + "value": "15.50", + "datatype": "xsd:decimal" + } + } + }, + "UPDATE_TASK":{ + "sparql":"DELETE { GRAPH ?graph { ?old_bnode rdf:type my2sec:Task; my2sec:hasProject ?old_project; my2sec:taskId ?task_id; my2sec:taskTitle ?old_task_title ; my2sec:hasMember ?old_member; my2sec:spentTime ?old_timenode . ?old_timenode rdf:type time:Duration; time:unitType time:unitHour ; time:numericDuration ?old_value}} INSERT { GRAPH ?graph { _:bnode rdf:type my2sec:Task ; my2sec:hasProject ?projecturi ; my2sec:taskId ?task_id; my2sec:taskTitle ?task_title; my2sec:hasMember ?assignee; my2sec:spentTime _:timenode . _:timenode rdf:type time:Duration; time:unitType time:unitHour ; time:numericDuration ?old_value }} WHERE { GRAPH ?graph { OPTIONAL { ?old_bnode rdf:type my2sec:Task; my2sec:hasProject ?old_project; my2sec:taskId ?task_id; my2sec:taskTitle ?old_task_title ; my2sec:Member ?old_member; my2sec:spentTime ?old_timenode . ?old_timenode rdf:type time:Duration; time:unitType time:unitHour ; time:numericDuration ?old_value }}}", + "forcedBindings": { + "graph": { + "type": "uri", + "value": "http://www.vaimee.it/projects#" + }, + "projecturi": { + "type": "uri", + "value": "http://www.vaimee.it/projects#demo-project" + }, + "task_id": { + "type": "literal", + "value": 1, + "datatype": "xsd:integer" + }, + "task_title": { + "type": "literal", + "value": "ATaskTitle" + }, + "assignee": { + "type": "uri", + "value": "http://www.vaimee.it/members/gregorio.monari@gmail.com" + }, + "spent_time": { + "type": "literal", + "value": "15.50", + "datatype": "xsd:decimal" + } + } + }, + "SEND_KEYCLOAK_MESSAGE":{ + "sparql":"WITH ?graph INSERT { ?b rdf:type mysec:Message ; my2sec:messageValue ?msgvalue; my2sec:messageSource ?source ; time:inXSDDateTimeStamp ?msgtimestamp } WHERE {BIND(UUID() AS ?b)}", + "forcedBindings": { + "graph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/members" + }, + "source": { + "type": "uri", + "value": "http://www.vaimee.it/sources/keycloak" + }, + "msgtimestamp": { + "type": "literal", + "value": "2022-08-10T15:33:42.503000+00:00" + }, + "msgvalue": { + "type": "literal", + "value": "{}" + } + } + }, + "SET_SYNCHRONIZATION_FLAG":{ + "sparql":"INSERT {GRAPH {?flag rdf:type ?flag_type ; my2sec:hasMember ?usergraph ; time:inXSDDateTimeStamp ?now}} WHERE{BIND(now() as ?now) BIND(UUID() AS ?flag)}", + "forcedBindings": { + "flag_type": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/awproducerflag" + }, + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/admin@vaimee.it" + } + } + }, + "RESET_SYNCHRONIZATION_FLAG":{ + "sparql":"DELETE {GRAPH {?flag ?p ?o}} WHERE{GRAPH {?flag ?p ?o}}", + "forcedBindings": { + "flag": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/urn:id:1234" + } + } + }, + "LOG_TIME":{ + "sparql":"INSERT {GRAPH { ?b rdf:type my2sec:Logtime; my2sec:hasMember ?usergraph; my2sec:hasTask ?task_uri; time:inXSDDateTimeStamp ?now; my2sec:hasTimeInterval _:d . _:d rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?log_time }} WHERE{ BIND(now() as ?now) BIND(UUID() AS ?b) }", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + }, + "task_uri": { + "type": "uri", + "value": "urn:id:1234" + }, + "log_time": { + "type": "literal", + "value": "2.5" + } + } + } + }, + "queries": { + "ALL_USERNAMES": { + "sparql":"SELECT * WHERE { GRAPH { ?s my2sec:username ?o }}" + }, + "SINGLE_MESSAGE":{ + "sparql":"SELECT * WHERE {GRAPH ?user_graph {?bnode_label my2sec:messageValue ?json_message ; my2sec:messageSource ?source ;time:inXSDDateTimeStamp ?message_timestamp }}", + "forcedBindings": { + "user_graph":{ + "type": "uri", + "value": "http://www.vaimee.it/members/defuser@vaimee.it" + }, + "source": { + "type": "uri", + "value": "http://www.vaimee.it/sources/aw-watcher-window" + }, + "message_timestamp": { + "type": "literal", + "value": "22:05" + } + } + }, + "ALL_USER_DATA": { + "sparql":"SELECT * WHERE { GRAPH { ?s ?p ?o } }" + }, + "USER_EVENTS": { + "sparql":"SELECT * WHERE { GRAPH { ?nodeid rdf:type my2sec:Event; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?timestamp; my2sec:activityType ?activity_type; my2sec:taskTitle ?task; my2sec:hasTimeInterval ?duration . FILTER (?event_type != my2sec:Event) } }" + }, + "USER_EVENTS_COUNT": { + "sparql":"SELECT (COUNT(?nodeid) AS ?nevents) WHERE { GRAPH ?usergraph { ?nodeid rdf:type my2sec:Event }}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + } + } + }, + "ALL_USERS_MESSAGES_OLD":{ + "sparql":"SELECT * WHERE { GRAPH ?message_graph {?bnode_label my2sec:messageUser ?usergraph; my2sec:messageValue ?json_message ; my2sec:messageSource ?source ;time:inXSDDateTimeStamp ?message_timestamp }}", + "forcedBindings": { + "message_graph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/messages/activitywatch" + }, + "source": { + "type": "uri", + "value": "http://www.vaimee.it/sources/aw-watcher-window" + } + } + }, + "ALL_USERS_MESSAGES":{ + "sparql":"SELECT * WHERE { GRAPH ?message_graph {?b rdf:type my2sec:Message ; my2sec:hasMember ?usergraph ; my2sec:messageValue ?msgvalue; my2sec:messageSource ?source ; time:inXSDDateTimeStamp ?msgtimestamp }}", + "forcedBindings": { + "message_graph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/messages/activitywatch" + } + } + }, + "ALL_USERS_EVENTS_BLAZEGRAPH":{ + "sparql":"SELECT * WHERE { GRAPH {?usergraph my2sec:username ?username_literal} GRAPH ?usergraph {?nodeid rdf:type my2sec:Event; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:hasTimeInterval ?duration . OPTIONAL { ?nodeid my2sec:taskTitle ?task} FILTER (?event_type != my2sec:Event) }}" + }, + "ALL_USERS_TRAINING_EVENTS":{ + "sparql":"SELECT ?nodeid ?usergraph ?event_type ?app ?title ?datetimestamp ?duration ?task WHERE { GRAPH {?nodeid rdf:type my2sec:TrainingEvent ; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:hasActivityType ?activity_type; my2sec:taskTitle ?task; my2sec:hasTimeInterval ?timenode . ?timenode rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration . FILTER (?event_type != my2sec:TrainingEvent) }}" + }, + "ALL_USERS_EVENTS":{ + "sparql":"SELECT * WHERE { GRAPH {?nodeid rdf:type my2sec:Event; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; FILTER (?event_type != my2sec:Event) }}" + }, + "ALL_USERS_ACTIVITIES":{ + "sparql":"SELECT * WHERE { GRAPH {?nodeid rdf:type my2sec:Activity; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:hasTimeInterval ?timenode . ?timenode rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration . OPTIONAL { ?nodeid my2sec:taskTitle ?task} FILTER (?event_type != my2sec:Activity) }}" + }, + "ALL_USERS_VALIDATED_ACTIVITIES":{ + "sparql":"SELECT * WHERE { GRAPH {?nodeid rdf:type my2sec:ValidatedActivity; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:hasTimeInterval ?timenode . ?timenode rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration . OPTIONAL { ?nodeid my2sec:taskTitle ?task} FILTER (?event_type != my2sec:ValidatedActivity) }}" + }, + "ALL_USERS_TRAINING_ACTIVITIES":{ + "sparql":"SELECT * WHERE { GRAPH {?nodeid rdf:type my2sec:TrainingActivity; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:hasTimeInterval ?timenode . ?timenode rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration . OPTIONAL { ?nodeid my2sec:taskTitle ?task} FILTER (?event_type != my2sec:TrainingActivity) }}" + }, + "USER_TRAINING_ACTIVITIES":{ + "sparql":"SELECT * WHERE { GRAPH {?nodeid rdf:type my2sec:TrainingActivity; my2sec:hasMember ?usergraph; rdf:type ?event_type; my2sec:nameApp ?app; my2sec:titleFile ?title; time:inXSDDateTimeStamp ?datetimestamp; my2sec:activityType ?activity_type; my2sec:hasTimeInterval ?timenode . ?timenode rdf:type time:Duration; time:unitType time:unitSecond ; time:numericDuration ?duration . OPTIONAL { ?nodeid my2sec:taskTitle ?task} FILTER (?event_type != my2sec:TrainingActivity) VALUES ?usergraph {?forceUserGraph} }}", + "forcedBindings": { + "forceUserGraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/admin@vaimee.it" + } + } + }, + + "ALL_OP_MESSAGES":{ + "sparql":"SELECT * WHERE{ GRAPH ?usergraph { _:b my2sec:messageValue ?msgvalue; my2sec:messageSource ?source ; time:inXSDDateTimeStamp ?msgtimestamp . }}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/admin@vaimee.it" + }, + "source": { + "type": "uri", + "value": "http://www.vaimee.it/sources/open-project" + } + } + }, + "ALL_PROJECTS":{ + "sparql":"SELECT * WHERE {GRAPH { ?projecturi rdf:type my2sec:project; my2sec:projectId ?project_id; my2sec:projectIdentifier ?project_identifier } }" + }, + "ALL_OP_TASKS":{ + "sparql":"SELECT * WHERE {GRAPH { ?bnode rdf:type my2sec:Task; my2sec:hasProject ?progetto; my2sec:taskId ?taskid; my2sec:taskTitle ?tasktitle; my2sec:hasMember ?assignee; my2sec:spentTime _:timenode . _:timenode rdf:type time:Duration; time:unitType time:unitHour ; time:numericDuration ?spent_time }}" + }, + "USER_TASKS":{ + "sparql":"SELECT * WHERE {GRAPH { ?bnode rdf:type my2sec:Task; my2sec:hasProject ?progetto; my2sec:taskId ?taskid; my2sec:taskTitle ?tasktitle; my2sec:hasMember ?assignee; my2sec:spentTime _:timenode . _:timenode rdf:type time:Duration; time:unitType time:unitHour ; time:numericDuration ?spent_time}}", + "forcedBindings": { + "assignee": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/admin@vaimee.it" + } + } + }, + "ALL_LOG_TIMES":{ + "sparql":"SELECT * WHERE { GRAPH { ?b rdf:type my2sec:Logtime; my2sec:hasMember ?usergraph; my2sec:hasTask ?task_uri; time:inXSDDateTimeStamp ?now; my2sec:hasTimeInterval _:d . _:d rdf:type time:Duration; time:unitType ?unit_type ; time:numericDuration ?log_time }}" + }, + "USER_LOG_TIMES":{ + "sparql":"SELECT * WHERE { GRAPH { ?b rdf:type my2sec:Logtime; my2sec:hasMember ?usergraph; my2sec:hasTask ?task_uri; time:inXSDDateTimeStamp ?now; my2sec:hasTimeInterval _:d . _:d rdf:type time:Duration; time:unitType ?unit_type ; time:numericDuration ?log_time }}", + "forcedBindings": { + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/admin@vaimee.it" + } + } + }, + "GET_SYNCHRONIZATION_FLAG":{ + "sparql":"SELECT * WHERE {GRAPH {?flag rdf:type ?flag_type ; my2sec:hasMember ?usergraph ; time:inXSDDateTimeStamp ?timestamp}}", + "forcedBindings": { + "flag_type": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/production_finished_flag" + } + } + }, + "GET_USER_SYNCHRONIZATION_FLAG":{ + "sparql":"SELECT * WHERE {GRAPH {?flag rdf:type ?flag_type ; my2sec:hasMember ?usergraph ; time:inXSDDateTimeStamp ?timestamp}}", + "forcedBindings": { + "flag_type": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/production_finished_flag" + }, + "usergraph": { + "type": "uri", + "value": "http://www.vaimee.it/my2sec/defuser@vaimee.it" + } + } + } + } +} diff --git a/1_ActivityWatchProducer/SECURITY/preload2.js b/1_ActivityWatchProducer/SECURITY/preload2.js index 4e7febac..7e47b936 100644 --- a/1_ActivityWatchProducer/SECURITY/preload2.js +++ b/1_ActivityWatchProducer/SECURITY/preload2.js @@ -2,5 +2,6 @@ const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('versions', { request_user_credentials: () => ipcRenderer.invoke('request_user_credentials') + //request_user_credentials: () => ipcRenderer.invoke('request_json_package') // we can also expose variables, not just functions }) \ No newline at end of file diff --git a/1_ActivityWatchProducer/electron_main_modules/AwApiRouter.js b/1_ActivityWatchProducer/electron_main_modules/AwApiRouter.js new file mode 100644 index 00000000..07499ee1 --- /dev/null +++ b/1_ActivityWatchProducer/electron_main_modules/AwApiRouter.js @@ -0,0 +1,191 @@ +const http = require('http'); +const express = require('express'); + +class AwApiRouter { + constructor(host,port,router_port){ + this.routerPort=router_port; + this.awHost=host; + this.awPort=port; + this.awApiRouter = express(); + this.awApiRouter.use(express.json()); + this.setup(); + } + + setup(){ + this.awApiRouter.get('/api/*', (request, response) => { //listen to all requests + console.log(`received AW buckets api request: ${request.originalUrl}`) + //console.log(get_time()+` [info] received AW API request: (${request.path})`); + + //CREATE HTTP REQUEST FOR THE API + //var host_name="localhost"; + //var http_port=5600; + var host_name=this.awHost; + var http_port=this.awPort; + var reqpath=request.originalUrl; + //var response=await get(host_name,http_port,reqpath); + this.get(host_name,http_port,reqpath).then((data)=>{ + console.log(data) + response.json(JSON.parse(data)); + }); + + }); + + this.awApiRouter.post('/api/*', (request,response)=>{ + //CREATE HTTP REQUEST FOR THE API + //var host_name="localhost"; + //var http_port=5600; + var host_name=this.awHost; + var http_port=this.awPort; + var reqpath=request.originalUrl; + const reqdata=JSON.stringify(request.body); + //var response=await get(host_name,http_port,reqpath); + this.post(host_name,http_port,reqpath,reqdata).then((data)=>{ + console.log(data) + response.json(JSON.parse(data)); + }); + }); + + this.awApiRouter.delete('/api/*', (request,response)=>{ + //const data=request.body; + //consoleLog(0,"performing DELETE request to "+request.path) + //CREATE HTTP REQUEST FOR THE API + //var host_name="localhost"; + //var http_port=5600; + var host_name=this.awHost; + var http_port=this.awPort; + var reqpath=request.originalUrl; + //var response=await get(host_name,http_port,reqpath); + this.http_delete(host_name,http_port,reqpath).then((data)=>{ + console.log(data) + response.json(JSON.parse(data)); + }); + }); + } + + start(){ + this.test_datasource() + //LISTEN TO REQUESTS + this.awApiRouter.listen(this.routerPort, () => { + console.log('aw api is listening on port 1340'); + }); + + } + + test_datasource(){ + console.log("Preflight: testing ActivityWatch connection") + //var host_name="127.0.0.1"; + //var http_port=5600; + var host_name=this.awHost; + var http_port=this.awPort; + //console.log(host_name+":"+http_port) + var reqpath="/api/0/buckets/" + //console.log("sending get request") + //var response=await get(host_name,http_port,reqpath); + this.get(host_name,http_port,reqpath).then((data)=>{ + console.log(data) + console.log("DATASOURCE: OK!\n") + }); + //console.log(String(response)) + } + + //HTTP CLIENT + http_delete(host_name,http_port,reqpath){ + //CREATE HTTP REQUEST FOR THE API + const options = { + hostname: host_name, + port: http_port, + path: reqpath, //`${request.path}`, //forward the path to the api + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + 'Connection': 'close', + }, + }; + + return new Promise(resolve=>{ + const req = http.request(options, res => { + //console.log(`forwarded request to ${options.path}, statusCode: ${res.statusCode}`); + res.on('data', d => { + resolve(d) + }); + }); + req.setHeader("Connection","close"); + //CATCH ERRORS + req.on('error', error => { + console.error(error); + }); + req.end(); + }) + + } + + post(host_name,http_port,reqpath,data){ + //CREATE HTTP REQUEST FOR THE API + const options = { + hostname: host_name, + port: http_port, + path: reqpath, //`${request.path}`, //forward the path to the api + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Connection': 'close', + }, + }; + + return new Promise(resolve=>{ + const req = http.request(options, res => { + res.on('data', d => { + resolve(d); + }); + }); + //CATCH ERRORS + req.on('error', error => { + console.error(error); + }); + req.write(data); + req.end(); + }) + + } + + get(host_name,http_port,reqpath){ + //CREATE HTTP REQUEST FOR THE API + const options = { + hostname: host_name, + port: http_port, + path: reqpath, //`${request.path}`, //forward the path to the api + method: 'GET', + headers: { + 'Content-Type': 'application/json', + 'Connection': 'close', + }, + }; + + return new Promise(resolve=>{ + const req = http.request(options, res => { + //console.log(`forwarded request to ${options.path}, statusCode: ${res.statusCode}`); + var str=''; + res.on('data', d => { + str=str+d; + }); + + res.on('end', ()=>{ + resolve(str) + }) + + }); + + req.setHeader("Connection","close"); + //CATCH ERRORS + req.on('error', error => { + console.error(error); + }); + req.end(); + }) + + } + +} + + +module.exports = AwApiRouter; \ No newline at end of file diff --git a/1_ActivityWatchProducer/electron_main_modules/JsapConfigurationManager.js b/1_ActivityWatchProducer/electron_main_modules/JsapConfigurationManager.js new file mode 100644 index 00000000..eb1b41cb --- /dev/null +++ b/1_ActivityWatchProducer/electron_main_modules/JsapConfigurationManager.js @@ -0,0 +1,104 @@ +const os = require('os'); + +class JsapConfigurationManager { + constructor(path){ + this.jsapPath=path; + } + + async getConfiguredJsap(){ + var jsap=await this.configureJsap(); + return jsap; + } + + async configureJsap(){ + console.log("Configuration Manager: initializing jsap") + var loopbackAddress= this.getLoopbackAddress(); + var jsapObj= await this.getJsap(); + //console.log(jsapObj.extended) + Object.keys(jsapObj.extended.AwProducer.endpoints).forEach(k=>{ + var endpointUrl=jsapObj.extended.AwProducer.endpoints[k]; + if(endpointUrl.includes("localhost")){ + console.log("- modifying endpoint: "+k) + endpointUrl=endpointUrl.replace("localhost",loopbackAddress); + jsapObj.extended.AwProducer.endpoints[k]=endpointUrl; + } + if(endpointUrl.includes("127.0.0.1")){ + console.log("- modifying endpoint: "+k) + endpointUrl=endpointUrl.replace("127.0.0.1",loopbackAddress); + jsapObj.extended.AwProducer.endpoints[k]=endpointUrl; + } + if(endpointUrl.includes("[::1]")){ + console.log("- modifying endpoint: "+k) + endpointUrl=endpointUrl.replace("[::1]",loopbackAddress); + jsapObj.extended.AwProducer.endpoints[k]=endpointUrl; + } + }) + console.log(jsapObj.extended) + return jsapObj; + } + + + async getJsap(){ + var file=await this.readFile(this.jsapPath); + return JSON.parse(file); + } + + getLoopbackAddress(){ + console.log("Detecting loopback address") + if(!this._ipv6IsOn()){ + if(this._isDarwin()){ + console.log("- Running on darwin") + return "127.0.0.1" //MAC + }else{ + console.log("- Running on windows/linux") + return "localhost" //WINDOWS + } + }else{ + console.log("- Device is using IPV6") + return "[::1]" //IPV6 + } + } + + + //----------------------------UTILITY--------------------------------- + _ipv6IsOn(){ + const networkInterfaces = os.networkInterfaces(); + // Loop through all available network interfaces + Object.keys(networkInterfaces).forEach((iface) => { + // Loop through all addresses of the current interface + networkInterfaces[iface].forEach((address) => { + // Check if the address is an IPv6 address + if (address.family === 'IPv6' && address.address !== '::1') { + // Use the IPv6 address instead of localhost + //apiURL = `http://[${address.address}]:333/api`; + return true; + } + }); + }); + return false; + } + + _isDarwin(){ + if (process.platform == 'darwin'){ + return true; + }else { + return false; + } + } + + + + readFile(filename){ + var fs = require('fs'); + return new Promise(resolve=>{ + fs.readFile(filename, 'utf8', function (err,data) { + if (err) return console.log(err); + //console.log('FILE SAVED'); + resolve(data) + }); + }) + } + +} + +module.exports=JsapConfigurationManager; \ No newline at end of file diff --git a/1_ActivityWatchProducer/electron_main_modules/MongoDbClient.js b/1_ActivityWatchProducer/electron_main_modules/MongoDbClient.js new file mode 100644 index 00000000..b9f55a80 --- /dev/null +++ b/1_ActivityWatchProducer/electron_main_modules/MongoDbClient.js @@ -0,0 +1,49 @@ +const { MongoClient } = require('mongodb') + + +class MongoDbClient{ + constructor(uri,database,collection){ + this.uri=uri; + this.database=database; + this.collection=collection; //one user has one collection, the name is the usergraph + } + + async insertFile(file){ + let client; + try{ + client = new MongoClient(this.uri); + const database = client.db(this.database); + const collection = database.collection(this.collection); + const result = await collection.insertOne(file); + //console.log(file); + return result; + }catch(e){ + console.log(e); + }finally{ + await client.close(); + } + } + + async getFile(query,options){ + let client; + try{ + client = new MongoClient(this.uri); + const database = client.db(this.database); + const collection = database.collection(this.collection); + if(!options) options={}; + const file = await collection.findOne(query, options); + //console.log(file); + return file; + }catch(e){ + console.log(e); + }finally{ + await client.close(); + } + } + + + +} + + +module.exports=MongoDbClient; \ No newline at end of file diff --git a/1_ActivityWatchProducer/electron_main_modules/MongoDbRouter.js b/1_ActivityWatchProducer/electron_main_modules/MongoDbRouter.js new file mode 100644 index 00000000..cafe4eb3 --- /dev/null +++ b/1_ActivityWatchProducer/electron_main_modules/MongoDbRouter.js @@ -0,0 +1,47 @@ +const express = require('express'); +const MongoDbClient = require("./MongoDbClient") + +class MongoDbRouter extends MongoDbClient{ + constructor(uri,database,collection,port){ + super(uri,database,collection) + this.port=port; + this.router = express(); + this.router.use(express.json()); + this.setup(); + } + + setup(){ + this.router.get('/mongodb/api', (request, response) => { //listen to all requests + console.log(`--------`) + response.json("hello from MongoDbApi!"); + }); + + this.router.post('/mongodb/api/insert', async (request,response)=>{ + console.log(`--------`) + await this.insertFile(request.body) + response.json("OK"); + }); + this.router.post('/mongodb/api/find', async (request,response)=>{ + console.log(`--------`) + var file=await this.getFile(request.body) + response.json(file); + }); + this.router.post('/mongodb/api/delete', async (request,response)=>{ + console.log(`--------`) + console.log("to be implemented") + response.json("TO BE IMPLEMENTED"); + }); + } + + start(){ + //LISTEN TO REQUESTS + this.router.listen(this.port, () => { + console.log(`mongodb api is listening on port ${this.port}`); + }); + } + + + +} + +module.exports=MongoDbRouter; \ No newline at end of file diff --git a/1_ActivityWatchProducer/electron_main_modules/PythonApiRunner.js b/1_ActivityWatchProducer/electron_main_modules/PythonApiRunner.js new file mode 100644 index 00000000..f919226b --- /dev/null +++ b/1_ActivityWatchProducer/electron_main_modules/PythonApiRunner.js @@ -0,0 +1,26 @@ +const { spawn } = require('child_process'); +class PythonApiRunner{ + constructor(path){ + this.pathToExecutable=path + this.pyProcess; + } + + start(){ + this.pyProcess=spawn("python",[this.pathToExecutable]); + console.log("started python api") + //on new data chunk + this.pyProcess.stdout.on("data",(data)=>{ + console.log(data) + }) + //on new error + this.pyProcess.stderr.on('data', (data) => { + console.error(`stderr: ${data}`); + }); + //on app close + this.pyProcess.stdout.on("close", (code)=>{ + console.log("App exited with code: "+code) + }) + } + +} +module.exports=PythonApiRunner; \ No newline at end of file diff --git a/1_ActivityWatchProducer/index.html b/1_ActivityWatchProducer/index.html index aa3ff33e..fab2ec70 100644 --- a/1_ActivityWatchProducer/index.html +++ b/1_ActivityWatchProducer/index.html @@ -33,13 +33,12 @@ - - - - - - - + + + + + + @@ -65,7 +64,7 @@
- + User
@@ -391,9 +390,8 @@

AW-WATCHER-WINDOW [1/4]

- - - + @@ -401,25 +399,22 @@

AW-WATCHER-WINDOW [1/4]

- - - - + + + - - - - - - - - - - + + + + + - - + + + + diff --git a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwClient.js b/1_ActivityWatchProducer/lib/AwClient.js similarity index 91% rename from 1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwClient.js rename to 1_ActivityWatchProducer/lib/AwClient.js index 1ce4c554..59aef510 100644 --- a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwClient.js +++ b/1_ActivityWatchProducer/lib/AwClient.js @@ -8,8 +8,10 @@ class AwClient { //CLASS CONSTRUCTOR, DOES NOTHING - constructor(){ - + constructor(jsap){ + this.log=new Greglogs(); + //console.log(jsap) + this.aw_host=jsap.extended.AwProducer.endpoints.AwApiRouter } @@ -30,8 +32,8 @@ class AwClient { .then(response => response.text()) .then(data => { this.jsonObj=JSON.parse(data) - consoleLog(1,"awclient: parsed json (AW configuration file)") - consoleLog(0,JSON.stringify(this.jsonObj)) + log.info("awclient: parsed json (AW configuration file)") + log.debug(JSON.stringify(this.jsonObj)) resolve(this.jsonObj) }); }); @@ -163,7 +165,8 @@ class AwClient { create_producer_bucket(){ return new Promise(resolve=>{ var req = new XMLHttpRequest(); - var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer" + //var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer" + var reqtext=this.aw_host+"/api/0/buckets/aw-producer"; //console.log("cazzomaledetto"+reqtext) req.open("POST", reqtext, true); @@ -224,7 +227,8 @@ class AwClient { create_event(json_event){ return new Promise(resolve=>{ var req = new XMLHttpRequest(); - var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer/events" + //var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer/events" + var reqtext= this.aw_host+"/api/0/buckets/aw-producer/events"; req.open("POST", reqtext, true); //Send the proper header information along with the request @@ -248,11 +252,12 @@ class AwClient { //DESCRIPTION: deletes an event by ID //ARGUMENTS: String event_id (the number id of the event to delete) delete_event(event_ID){ - consoleLog(0,"removing event") + log.info("removing event") return new Promise(resolve=>{ var req = new XMLHttpRequest(); - var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer/events/"+event_ID; + //var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer/events/"+event_ID; + var reqtext=this.aw_host+"/api/0/buckets/aw-producer/events/"+event_ID; req.open("DELETE", reqtext, true); //Send the proper header information along with the request @@ -287,7 +292,8 @@ class AwClient { get(path){ return new Promise(resolve=>{ var req= new XMLHttpRequest(); - var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+path + //var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+path + var reqtext= this.aw_host+path; req.open("GET",reqtext); req.onload = function(){ log.debug("AwClient request: GET "+reqtext) @@ -307,10 +313,16 @@ class AwClient { class AwMy2SecClient extends AwClient{ - constructor(host){ - super(); + constructor(jsap){ + super(jsap); this.load_default_configuration() - this.host=host; + this.my2secapi_host=jsap.extended.AwProducer.endpoints.My2secApi; + //TODO WORKAROUND, OVERRIDE CONFIGURATION: find a better way to do this + if(this.my2secapi_host.includes("localhost")){ + this.my2secapi_host=this.my2secapi_host.replace("localhost","127.0.0.1"); + } + //console.log(this.my2secapi_host) + //this.host="127.0.0.1:5000"; //RESET: apps_current.csv / apps_selection da cancellare this.startAction='{"watcher-api-request":{"requestAction":{"watchers-management":"START_ALL"}}}' //START SCAN this.stopAction='{"watcher-api-request":{"requestAction":{"watchers-management":"STOP_ALL"}}}' //STOP SCAN @@ -388,7 +400,8 @@ class AwMy2SecClient extends AwClient{ my2sec_post(path,body){ return new Promise(resolve=>{ var req = new XMLHttpRequest(); - var url="http://"+this.host+path + //var url="http://"+this.host+path + var url=this.my2secapi_host+path; req.open("POST", url, true); //Send the proper header information along with the request req.setRequestHeader("Content-Type", "application/json"); diff --git a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwClient_BACKUP.js b/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwClient_BACKUP.js deleted file mode 100644 index 16b8c02f..00000000 --- a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/AwClient_BACKUP.js +++ /dev/null @@ -1,260 +0,0 @@ -/*---------------------------------------------------------\ -|| aw-client.js: ACTIVITY WATCH CLIENT CLASS -|| DATE: 28/06/2022 -|| AUTHOR: Gregorio Monari -|| DESCRIPTION: a collection of methods used to -|| get and post data to the localhost Activity Watch API -\\--------------------------------------------------------*/ -class AwClient { - - //CLASS CONSTRUCTOR, DOES NOTHING - constructor(){ - - } - - - //=========================== - // GET METHODS - //=========================== - - //-------------------------------------------- - //NAME: get_aw_configuration(String jsonFilePath) - //DESCRIPTION: reads a json file from the filesystem, then parses it into a JsonObject and initializes the class variable jsonObj - //ARGUMENTS: String jsonFilePath (the path to the configuration file) - //RETURNS: a jsonObject containing the parsed json file, you don't need to catch the output since it initializes an internal variable - //NOTES: uses the fetch api and works only via http protocol, not file protocol - load_configuration(jsonFilePath){ - return new Promise(resolve=>{ - //GET CONFIG FILE - fetch(jsonFilePath) - .then(response => response.text()) - .then(data => { - this.jsonObj=JSON.parse(data) - consoleLog(1,"awclient: parsed json (AW configuration file)") - consoleLog(0,JSON.stringify(this.jsonObj)) - resolve(this.jsonObj) - }); - }); - } - //NOTES: this version works on any protocol - load_default_configuration(){ - this.jsonObj=JSON.parse("{ \"nodeHost\": \"localhost\", \"port\": \"1340\"}") //5600 - consoleLog(1,"awclient: parsed json (AW configuration file)") - consoleLog(0,JSON.stringify(this.jsonObj)) - } - - - //---------------------------------------------- - //NAME: get_watchers() - //DESCRIPTION: makes an http request to the api to get the list of active buckets in json format - //ARGUMENTS: none - //RETURNS: jsonObject jsonWatchers (the json object containing watchers info) - async get_watchers(){ - //WAIT TO GET THE JSON - //consoleLog(1,"-------------------------------") - //consoleLog(1,"aw-client: fetching watchers...") - var jsonWatchers = await this.get("/api/0/buckets/") - //RETURN THE WATCHERS - return new Promise(resolve=>{ - //consoleLog(1,"aw-client: fetched watchers correctly!") - resolve(jsonWatchers) - }); - } - - - //-------------------------------------- - //NAME: get_events(String watcher_id) - //DESCRIPTION: makes an http request to the api to get the events produced by 1 specific watcher - //ARGUMENTS: String watcher_id (identifies the watcher, it is a concatenation of client+hostname) - //RETURNS: jsonObject jsonEvents (the json object containing an array of events) - //NOTES: calling this metod fetches ALL events of a watcher in the aw server, so it could take some time - async get_events(watcher_id){ - //consoleLog(1,"aw-client: fetching events of "+watcher_id+"...") - //WAIT TO GET THE JSON - var jsonEvents = await this.get("/api/0/buckets/"+watcher_id+"/events") - //RETURN THE WATCHERS - return new Promise(resolve=>{ - //consoleLog(1,"aw-client: fetched events correctly!") - resolve(jsonEvents) - }); - } - - - //-------------------------------------- - //NAME: query_events(String watcher_id, String end_time, String start_time) - //DESCRIPTION: similar to get_events(), except in this method you can specify a time interval for the events - //ARGUMENT: String watcher_id (identifies the watcher), String end_time/start_time (formatted ISO timestamp) - //RETURNS: jsonObject jsonEvents (the json object containing an array of events in a certain period of time) - async query_events(watcher_id,end_time,start_time){ - //consoleLog(1,"-----------------------------------------------") - //consoleLog(1,"aw-client: fetching events of "+watcher_id+"...") - //WAIT TO GET THE JSON, with query example: ?end=2022-07-17T15%3A23%3A55Z&start=2022-07-16T15%3A23%3A55Z - var path="/api/0/buckets/"+watcher_id+"/events?end="+end_time+"&start="+start_time; - path=path.replace(/:/g,"%3A"); //REPLACE : WITH %3A FOR A WELL FORMATTED REQUEST - //consoleLog(0,"query_events: reqpath: "+path) - - var jsonEvents = await this.get(path) //path - //RETURN THE WATCHERS - return new Promise(resolve=>{ - //consoleLog(1,"aw-client: fetched events correctly!") - resolve(jsonEvents) - }); - } - - - - - //====================================== - // POST/UPDATE METHODS - //====================================== - - //------------------------------ - //NAME: create_producer_bucket() - //DESCRIPTION: creates a new "aw-producer" bucket. Does nothing if already exists - //ARGUMENTS: none - create_producer_bucket(){ - return new Promise(resolve=>{ - var req = new XMLHttpRequest(); - var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer" - //console.log("cazzomaledetto"+reqtext) - - req.open("POST", reqtext, true); - - //Send the proper header information along with the request - req.setRequestHeader("Content-Type", "application/json"); - - req.onreadystatechange = function() {// Call a function when the state changes. - if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { - // Request finished. Do processing here. - //consoleLog(1,"create_bucket: aw-producer bucket created, status "+this.status) - resolve("ok") - }else{ - - if (this.readyState === XMLHttpRequest.DONE && this.status === 304) { - //consoleLog(1,"create_bucket: aw-producer bucket already existing, status "+this.status) - resolve("ok") - } - } - } - req.send("{ \"client\": \"aw-producer\", \"type\": \"sepaconnector\", \"hostname\": \"unknown\"}"); - }); - } - - - //------------------------------ - //NAME: update_event(String json_event) - //DESCRIPTION: sends a stringified json to aw api to update a specific event - //ARGUMENTS: String json_event (a stringified json object containing the event to update) - //NOTES: the json event needs to have an ID field in order to be updated, but the aw server auto-assigns an ID to new events so chill - async update_event(json_event){ - var event= await this.get_events('aw-producer') - event=JSON.parse(event); - //SE ESISTE GIA', ELIMINALO - if (event.length>0) { - await this.delete_event(event[0].id) - } - await this.create_event(json_event) - } - - - //------------------------------ - //NAME: create_event(String json_event) - //DESCRIPTION: sends a stringified json to aw api to insert a new event - //ARGUMENTS: String json_event (a stringified json object containing the event to insert) - //NOTES: aw server automatically inserts the new event into the jsonEvents array of the watcher producing the event - create_event(json_event){ - return new Promise(resolve=>{ - var req = new XMLHttpRequest(); - var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer/events" - req.open("POST", reqtext, true); - - //Send the proper header information along with the request - req.setRequestHeader("Content-Type", "application/json"); - - req.onreadystatechange = function() {// Call a function when the state changes. - if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { - // Request finished. Do processing here. - //consoleLog(1,"create_event: aw-producer event created, status "+this.status) - resolve("ok") - } - } - //bodystring="{ \"timestamp\": \"2022-07-12T16:47:46.060Z\", \"duration\": 0, \"data\": {\"last_update\":\""+get_time()+"\"} }" - req.send(json_event); - }); - } - - - //------------------------------ - //NAME: delete_event(String json_event) - //DESCRIPTION: deletes an event by ID - //ARGUMENTS: String event_id (the number id of the event to delete) - delete_event(event_ID){ - consoleLog(0,"removing event") - return new Promise(resolve=>{ - - var req = new XMLHttpRequest(); - var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+"/api/0/buckets/aw-producer/events/"+event_ID; - req.open("DELETE", reqtext, true); - - //Send the proper header information along with the request - req.setRequestHeader("Content-Type", "application/json"); - - req.onreadystatechange = function() {// Call a function when the state changes. - if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { - // Request finished. Do processing here. - //consoleLog(1,"remove_event: aw-producer event n."+event_ID+" deleted, status "+this.status) - resolve("ok") - } - } - req.send(); - }); - } - - - - - //======================================================// - // /|\ [THE ROOT, ALLOWS TO GET DATA FROM THE API] // - // \|/ ______________________________________ // - // |___|______________________________________|___ // - //___|______________________________________________|___// - //| |// - //======================================================// - //NAME: get(String path) - //DESCRIPTION: sends an http request to the AW API, which responds with a json file - //ARGUMENTS: String path (the path for the api call) - //RETURNS: JsonObject jsonResponse (the API response, it is a Promise and needs to be listened with "await") - //NOTES: you can call this method with the "await" keyword form within an async function to wait for it to finish - get(path){ - - return new Promise(resolve=>{ - var req= new XMLHttpRequest(); - var reqtext="http://"+this.jsonObj.nodeHost+":"+this.jsonObj.port+path - var jsonResponse; - consoleLog(0,"AwClient request: GET "+reqtext) - - req.open("GET",reqtext); - - req.onload = function(){ - //jsonResponse = JSON.parse(req.responseText); - //consoleLog(0,"api_GetJson: fetched data correctly from AW API") - //consoleLog(0,JSON.stringify(jsonResponse)) - //consoleLog(0,"API response: "+req.responseText) - //resolve(jsonResponse) //return json asynchronously - resolve(req.responseText); - } - req.send(); - }); - - } - //=============================================================================================================== - - -} - - - - - - - diff --git a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/jsap.js b/1_ActivityWatchProducer/lib/AwUpdateFlowControl/jsap.js deleted file mode 100644 index afc5e78a..00000000 --- a/1_ActivityWatchProducer/lib/AwUpdateFlowControl/jsap.js +++ /dev/null @@ -1,37 +0,0 @@ -console.log("-> Loaded external script: jsap.js") -default_jsap={ - "host": "localhost", - "oauth": { - "enable": false, - "register": "https://localhost:8443/oauth/register", - "tokenRequest": "https://localhost:8443/oauth/token" - }, - "sparql11protocol": { - "protocol": "http", - "port": 8666, - "query": { - "path": "/query", - "method": "POST", - "format": "JSON" - }, - "update": { - "path": "/update", - "method": "POST", - "format": "JSON" - } - }, - "sparql11seprotocol": { - "reconnect" : true, - "protocol": "ws", - "availableProtocols": { - "ws": { - "port": 9666, - "path": "/subscribe" - }, - "wss": { - "port": 9443, - "path": "/secure/subscribe" - } - } - } -} diff --git a/1_ActivityWatchProducer/lib/PacFactoryJs/GregLogs.js b/1_ActivityWatchProducer/lib/PacFactoryJs/GregLogs.js index 99fd3b1d..ed244ec3 100644 --- a/1_ActivityWatchProducer/lib/PacFactoryJs/GregLogs.js +++ b/1_ActivityWatchProducer/lib/PacFactoryJs/GregLogs.js @@ -1,6 +1,6 @@ class Greglogs{ constructor() { - this.loglevel=0; + this.loglevel=1; //this.info("New Greglogs logger created!") } //========= @@ -8,6 +8,21 @@ class Greglogs{ //logLevel(level){ // this.loglevel=level; //} + trace_table(text){ + if(this.loglevel<1){ + console.table(text); + } + } + debug_table(text){ + if(this.loglevel<2){ + console.table(text); + } + } + info_table(text){ + if(this.loglevel<3){ + console.table(text); + } + } trace(text){ if(this.loglevel<1){ console.log(get_current_timestamp()+" [trace] "+text); diff --git a/1_ActivityWatchProducer/lib/gregnet-grid-plugin/gregnet-grid-script.js b/1_ActivityWatchProducer/lib/gregnet-grid-plugin/gregnet-grid-script.js deleted file mode 100644 index 8720af11..00000000 --- a/1_ActivityWatchProducer/lib/gregnet-grid-plugin/gregnet-grid-script.js +++ /dev/null @@ -1,106 +0,0 @@ - -//DYNAMIC LINKS MENU -document.getElementById("dynamic_links_menu").style.display="none" -function dynamic_links_menu(){ - var dlm=document.getElementById("dynamic_links_menu") - if(dlm.style.display!="none"){ - dlm.style.display="none" - }else{ - dlm.innerHTML="SERVICES
" - //PRENDI TUTTE LE RIGHE FIGLIE DI DASH-WRAP - var righe=get_childs_via_class("dashboard-wrapper","row") - var title; - //alert(righe[0].id) - for (var i = 0; i < righe.length; i++) { - //alert(righe[i].id) - title=get_row_title(righe[i].id) - if(title!="gtnull"){ - //CREATE LINK! - dlm.innerHTML=dlm.innerHTML+"  "+title+"
" - } - - } - //alert(i) - //dlm.innerHTML=dlm.innerHTML+titles[0]+"\n" - - dlm.style.display="block" - } -} - - - - - -//ESTRAI IL TITOLO DALLA RIGA -//get_row_title(righe[0].id) - - -function get_row_title(id){ - //alert(id) - var childtopbar=get_childs_via_class(id,"rowtopbar"); - //alert(childtopbar[0].className) - //alert(childtopbar.length) - //SE NON HA TOPBAR NON E' VALIDA - if(childtopbar.length!=0){ - var childtitle=get_childs_via_class(childtopbar[0].id,"rowtitle") - //alert(childtitle[0].className) - var text_title=childtitle[0].textContent - //alert(text_title) - return text_title - }else{ - return "gtnull" - } -} - - -//--------------------------------------------- -//NAME: get_child_rows(Str(#cwrap),Str(.cname)) -//RETURNS: row_childs -//DESCRIPTION: -// START FROM ID, GET MULTIPLE CILDREN -// Returns an array of children -// identified via class -// from the father element id -function get_childs_via_class(idwrap,cname){ - //GET CONTENT WRAPPER - var dash_container=document.getElementById(idwrap) - //alert(dash_container.className) - var dashChilds= dash_container.childNodes - //alert(dashChilds[5].className) - var NRIGHE=0; - var row_childs=[]; - for(i=0; i - - - -2) Copy this line at the end of your body before your main script: - - - -3) This is an example: \ No newline at end of file diff --git a/1_ActivityWatchProducer/lib/SupersetEmbeddedDashboard/superset-embed.js b/1_ActivityWatchProducer/lib/superset-embed.js similarity index 89% rename from 1_ActivityWatchProducer/lib/SupersetEmbeddedDashboard/superset-embed.js rename to 1_ActivityWatchProducer/lib/superset-embed.js index 05c48580..c8159090 100644 --- a/1_ActivityWatchProducer/lib/SupersetEmbeddedDashboard/superset-embed.js +++ b/1_ActivityWatchProducer/lib/superset-embed.js @@ -1,10 +1,18 @@ +var log=new Greglogs(); async function createDashboard(dash_id,superset_host,container_id){ var embed= await supersetEmbeddedSdk.embedDashboard({ id: dash_id, // given by the Superset embedding UI supersetDomain: superset_host, mountPoint: document.getElementById(container_id), // any html element that can contain an iframe fetchGuestToken: () => fetchGuestTokenFromBackend(superset_host,dash_id), - dashboardUiConfig: { hideTitle: true }, // dashboard UI config: hideTitle, hideTab, hideChartControls (optional) + dashboardUiConfig: { + hideTitle: true , + filters:{ + visible: false + }, + hideTab: true, + hideChartControls: true + }, // dashboard UI config: hideTitle, hideTab, hideChartControls (optional) }); return embed; } @@ -19,7 +27,7 @@ async function fetchGuestTokenFromBackend(superset_host,dash_id){ var login_token_json=JSON.parse(login_token_string) var access_token=login_token_json.access_token - consoleLog(1,access_token) + log.debug(access_token) return new Promise(resolve=>{ @@ -52,7 +60,7 @@ async function fetchGuestTokenFromBackend(superset_host,dash_id){ req.onreadystatechange = function() {// Call a function when the state changes. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { // Request finished. Do processing here. - consoleLog(1,"status "+this.status) + log.trace("status "+this.status) //consoleLog(1,req.responseText) var tmp=JSON.parse(req.responseText) @@ -81,7 +89,7 @@ function fetchAccessTokenFromBackend(superset_host){ req.onreadystatechange = function() {// Call a function when the state changes. if (this.readyState === XMLHttpRequest.DONE && this.status === 200) { // Request finished. Do processing here. - consoleLog(1,"status "+this.status) + log.trace(1,"status "+this.status) //consoleLog(1,req.responseText) resolve(req.responseText) } diff --git a/1_ActivityWatchProducer/main.js b/1_ActivityWatchProducer/main.js index 139e8295..5fedd2c8 100644 --- a/1_ActivityWatchProducer/main.js +++ b/1_ActivityWatchProducer/main.js @@ -1,12 +1,26 @@ -// main.js +//================================ +// ELECTRON: main.js +// Controls the main node process +//================================ // Modules to control application life and create native browser window const { app, BrowserWindow } = require('electron') const path = require('path') const {ipcMain} = require('electron') - +//Custom modules +const AwApiRouter = require("./electron_main_modules/AwApiRouter"); +const PythonApiRunner = require("./electron_main_modules/PythonApiRunner"); +const MongoDbRouter = require("./electron_main_modules/MongoDbRouter"); +const JsapConfigurationManager = require("./electron_main_modules/JsapConfigurationManager"); + +/*=============== +## APP WINDOWS +===============*/ +//GLOBAL VARIABLES var user_login_json=""; +//var my2sec_jsap; +var json_package={}; +// Create the browser window. const createWindow = () => { - // Create the browser window. const mainWindow = new BrowserWindow({ show: false, //fullscreen: true, @@ -16,7 +30,8 @@ const createWindow = () => { preload: path.join(__dirname, './SECURITY/preload2.js') } }) - ipcMain.handle('request_user_credentials', () => user_login_json) + //ipcMain.handle('request_user_credentials', () => user_login_json) + ipcMain.handle('request_user_credentials', () => JSON.stringify(json_package)) mainWindow.setMenuBarVisibility(false) // and load the index.html of the app. mainWindow.loadFile('index.html') @@ -27,8 +42,7 @@ const createWindow = () => { // Open the DevTools. // mainWindow.webContents.openDevTools() } - -// Create the browser window. +// Create LoginWindow. const createLoginWindow = () => { loginWindow = new BrowserWindow({ show: false, @@ -50,20 +64,28 @@ const createLoginWindow = () => { }) } - function handleLoginSuccess(arg){ console.log(arg) - user_login_json=arg; + //user_login_json=arg; //set user_login_json + json_package["user_login_json"]=JSON.parse(arg); //delete login window loginWindow.close(); createWindow(); } - - // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. -app.whenReady().then(() => { +app.whenReady().then(async () => { + + console.log("----------------------------------------") + //INITIALIZE CONFIGURATION MANAGER + //This will detect if the host machine uses ipv6 or is windows/darwin and change the requests urls accordingly. + let jsapConfigurationManager = new JsapConfigurationManager("./Resources/my2sec_7-3-2023.jsap"); + var my2sec_jsap=await jsapConfigurationManager.getConfiguredJsap(); + json_package["my2sec_jsap"]=my2sec_jsap; + //INITIALIZE REST OF THE MODULES + initMainElectronModules() + createLoginWindow() app.on('activate', () => { @@ -83,218 +105,57 @@ app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit() }) - - - - +//------------------------------------------------------------------------------------------------------------- // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. - - - - - - - - - -//SNEAKY BOY -//--------------------------- -console.log("#============#") -console.log("# SNEAKY BOY #") -console.log("#============#") - -const http = require('http'); -const express = require('express'); - - -test_datasource(); - - -//CREATE APP -const awApiRouter = express(); -//YEAH FUCK IT BITCH -//app.use(cors()); -awApiRouter.use(express.json()); - -awApiRouter.get('/api/*', (request, response) => { //listen to all requests - console.log(`received AW buckets api request: ${request.originalUrl}`) - //console.log(get_time()+` [info] received AW API request: (${request.path})`); - - //CREATE HTTP REQUEST FOR THE API - var host_name="localhost"; - var http_port=5600; - var reqpath=request.originalUrl; - //var response=await get(host_name,http_port,reqpath); - get(host_name,http_port,reqpath).then((data)=>{ - console.log(data) - response.json(JSON.parse(data)); - }); - -}); - - -awApiRouter.post('/api/*', (request,response)=>{ - //CREATE HTTP REQUEST FOR THE API - var host_name="localhost"; - var http_port=5600; - var reqpath=request.originalUrl; - const reqdata=JSON.stringify(request.body); - //var response=await get(host_name,http_port,reqpath); - post(host_name,http_port,reqpath,reqdata).then((data)=>{ - console.log(data) - response.json(JSON.parse(data)); - }); -}); - - -awApiRouter.delete('/api/*', (request,response)=>{ - //const data=request.body; - //consoleLog(0,"performing DELETE request to "+request.path) - //CREATE HTTP REQUEST FOR THE API - var host_name="localhost"; - var http_port=5600; - var reqpath=request.originalUrl; - //var response=await get(host_name,http_port,reqpath); - http_delete(host_name,http_port,reqpath).then((data)=>{ - console.log(data) - response.json(JSON.parse(data)); - }); -}); - - - - - - -//--------------------------------------- -//USER FUNCTIONS -async function test_datasource(){ - console.log("TESTING DATASOURCE: preflight...") - var host_name="localhost"; - var http_port=5600; - var reqpath="/api/0/buckets/" - //console.log("sending get request") - //var response=await get(host_name,http_port,reqpath); - get(host_name,http_port,reqpath).then((data)=>{ - console.log("DATASOURCE: OK!\n") - }); - //console.log(String(response)) -} - - - - -function http_delete(host_name,http_port,reqpath){ - //CREATE HTTP REQUEST FOR THE API - const options = { - hostname: host_name, - port: http_port, - path: reqpath, //`${request.path}`, //forward the path to the api - method: 'DELETE', - headers: { - 'Content-Type': 'application/json', - 'Connection': 'close', - }, - }; - - return new Promise(resolve=>{ - const req = http.request(options, res => { - //console.log(`forwarded request to ${options.path}, statusCode: ${res.statusCode}`); - res.on('data', d => { - resolve(d) - }); - }); - req.setHeader("Connection","close"); - //CATCH ERRORS - req.on('error', error => { - console.error(error); - }); - req.end(); - }) - -} - - - -function post(host_name,http_port,reqpath,data){ - //CREATE HTTP REQUEST FOR THE API - const options = { - hostname: host_name, - port: http_port, - path: reqpath, //`${request.path}`, //forward the path to the api - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'Connection': 'close', - }, - }; - - return new Promise(resolve=>{ - const req = http.request(options, res => { - res.on('data', d => { - resolve(d); - }); - }); - //CATCH ERRORS - req.on('error', error => { - console.error(error); - }); - req.write(data); - req.end(); - }) - +async function initMainElectronModules(){ + //INITIALIZE AWAPIROUTER + //This router takes http requests from the frontend and forwards them to activitywatch. + //Connection close headers are added to requests in order to fix an aw bug + var activitywatch_url=json_package["my2sec_jsap"].extended.AwProducer.endpoints.ActivityWatch; + var arr=split_url(activitywatch_url); + var aw_host=arr[0];//"localhost"; + var aw_port=arr[1];//5600; + var aw_router_port=1340; + let awApiRouter = new AwApiRouter(aw_host,aw_port,aw_router_port); + awApiRouter.start(); + console.log("- AwApiRouter started") + + let pythonApiRunner = new PythonApiRunner('./PY/my2sec/main/API_my2sec.py'); + pythonApiRunner.start(); + console.log("- Python api started") + + + var mongodb_uri=json_package["my2sec_jsap"].extended.AwProducer.endpoints.MongoDb;//"mongodb://root:Gregnet-99@dld.arces.unibo.it:27017/" + var database="my2sec_aw_messages" + var collection="test" + var mongodb_router_port=1341 + let mongoDbRouter = new MongoDbRouter(mongodb_uri,database,collection,mongodb_router_port) + mongoDbRouter.start(); + console.log("- MongoDbClient started") } - - -function get(host_name,http_port,reqpath){ - //CREATE HTTP REQUEST FOR THE API - const options = { - hostname: host_name, - port: http_port, - path: reqpath, //`${request.path}`, //forward the path to the api - method: 'GET', - headers: { - 'Content-Type': 'application/json', - 'Connection': 'close', - }, - }; - - return new Promise(resolve=>{ - const req = http.request(options, res => { - //console.log(`forwarded request to ${options.path}, statusCode: ${res.statusCode}`); - var str=''; - res.on('data', d => { - str=str+d; - }); - - res.on('end', ()=>{ - resolve(str) - }) - - }); - - req.setHeader("Connection","close"); - //CATCH ERRORS - req.on('error', error => { - console.error(error); - }); - req.end(); - }) - +function split_url(url){ + var string=url.split("//")[1] + console.log(string) + if(string.includes("[") && string.includes("]")){ + var tempArr=string.split("]"); + var dirtyport=tempArr[1]; + var splitArr=[]; + splitArr[0]=tempArr[0]+"]" + if(dirtyport.startsWith(":")){ + if(dirtyport.endsWith("/")){ + splitArr[1]=dirtyport.slice(1,dirtyport.length-2) + }else{ + splitArr[1]=dirtyport.slice(1,dirtyport.length-1) + } + return splitArr + }else{ + throw new Error("loopback address parse error") + } + }else{ + var splitArr=string.split(":"); + return splitArr + } } - - - - - - - -//----------------------------------------------------------------------------------------------------- -//LISTEN TO REQUESTS -awApiRouter.listen(1340, () => { - console.log('server is listening on port 1340'); -}); - diff --git a/1_ActivityWatchProducer/node_modules/.package-lock.json b/1_ActivityWatchProducer/node_modules/.package-lock.json index fda727ea..a5f30d8f 100644 --- a/1_ActivityWatchProducer/node_modules/.package-lock.json +++ b/1_ActivityWatchProducer/node_modules/.package-lock.json @@ -127,8 +127,7 @@ "node_modules/@types/node": { "version": "18.7.13", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.13.tgz", - "integrity": "sha512-46yIhxSe5xEaJZXWdIBP7GU4HDTG8/eo0qd9atdiL+lFpA03y8KS+lkTN834TWJj5767GbWv4n/P6efyTFt1Dw==", - "dev": true + "integrity": "sha512-46yIhxSe5xEaJZXWdIBP7GU4HDTG8/eo0qd9atdiL+lFpA03y8KS+lkTN834TWJj5767GbWv4n/P6efyTFt1Dw==" }, "node_modules/@types/responselike": { "version": "1.0.0", @@ -139,6 +138,20 @@ "@types/node": "*" } }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-xTE1E+YF4aWPJJeUzaZI5DRntlkY3+BCVJi0axFptnjGmAoWxkyREIh/XMrfxVLejwQxMCfDXdICo0VLxThrog==" + }, + "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/abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -345,6 +358,14 @@ "concat-map": "0.0.1" } }, + "node_modules/bson": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/bson/-/bson-5.0.1.tgz", + "integrity": "sha512-y09gBGusgHtinMon/GVbv1J6FrXhnr/+6hqLlSmEFzkz6PodqF6TxjyvfvY3AfO+oG1mgUtbC86xSbOlwvM62Q==", + "engines": { + "node": ">=14.20.1" + } + }, "node_modules/buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -1313,8 +1334,7 @@ "node_modules/ip": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", - "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==", - "dev": true + "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==" }, "node_modules/ipaddr.js": { "version": "1.9.1", @@ -1495,6 +1515,12 @@ "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", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", @@ -1670,6 +1696,47 @@ "node": ">=10" } }, + "node_modules/mongodb": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.1.0.tgz", + "integrity": "sha512-qgKb7y+EI90y4weY3z5+lIgm8wmexbonz0GalHkSElQXVKtRuwqXuhXKccyvIjXCJVy9qPV82zsinY0W1FBnJw==", + "dependencies": { + "bson": "^5.0.1", + "mongodb-connection-string-url": "^2.6.0", + "socks": "^2.7.1" + }, + "engines": { + "node": ">=14.20.1" + }, + "optionalDependencies": { + "saslprep": "^1.0.3" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.201.0", + "mongodb-client-encryption": "^2.3.0", + "snappy": "^7.2.2" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", + "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^11.0.0" + } + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -1950,6 +2017,14 @@ "once": "^1.3.1" } }, + "node_modules/punycode": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", + "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", + "engines": { + "node": ">=6" + } + }, "node_modules/qs": { "version": "6.10.3", "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.3.tgz", @@ -2111,6 +2186,18 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "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/semver": { "version": "7.3.7", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", @@ -2256,17 +2343,15 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "dev": true, "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==", - "dev": true, + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", + "integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", "dependencies": { "ip": "^2.0.0", "smart-buffer": "^4.2.0" @@ -2290,6 +2375,15 @@ "node": ">= 10" } }, + "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/ssri": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/ssri/-/ssri-9.0.1.tgz", @@ -2382,6 +2476,17 @@ "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/type-is": { "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", @@ -2466,6 +2571,26 @@ "defaults": "^1.0.3" } }, + "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/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/LICENSE b/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/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/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/README.md b/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/README.md new file mode 100644 index 00000000..d0a3931a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/webidl-conversions` + +# Summary +This package contains type definitions for webidl-conversions (https://github.com/jsdom/webidl-conversions#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/webidl-conversions. + +### Additional Details + * Last updated: Mon, 29 Aug 2022 23:32:44 GMT + * Dependencies: none + * Global values: none + +# Credits +These definitions were written by [ExE Boss](https://github.com/ExE-Boss), and [BendingBender](https://github.com/BendingBender). diff --git a/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/index.d.ts b/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/index.d.ts new file mode 100644 index 00000000..ba90653d --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for webidl-conversions 7.0 +// Project: https://github.com/jsdom/webidl-conversions#readme +// Definitions by: ExE Boss +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace WebIDLConversions { + interface Globals { + [key: string]: unknown; + + Number: (value?: unknown) => number; + String: (value?: unknown) => string; + TypeError: new (message?: string) => TypeError; + } + + interface Options { + context?: string | undefined; + globals?: Globals | undefined; + } + + interface IntegerOptions extends Options { + enforceRange?: boolean | undefined; + clamp?: boolean | undefined; + } + + interface StringOptions extends Options { + treatNullAsEmptyString?: boolean | undefined; + } + + interface BufferSourceOptions extends Options { + allowShared?: boolean | undefined; + } + + type IntegerConversion = (V: unknown, opts?: IntegerOptions) => number; + type StringConversion = (V: unknown, opts?: StringOptions) => string; + type NumberConversion = (V: unknown, opts?: Options) => number; +} + +declare const WebIDLConversions: { + any(V: V, opts?: WebIDLConversions.Options): V; + undefined(V?: unknown, opts?: WebIDLConversions.Options): void; + boolean(V: unknown, opts?: WebIDLConversions.Options): boolean; + + byte(V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + octet(V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + + short(V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + ['unsigned short'](V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + + long(V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + ['unsigned long'](V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + + ['long long'](V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + ['unsigned long long'](V: unknown, opts?: WebIDLConversions.IntegerOptions): number; + + double(V: unknown, opts?: WebIDLConversions.Options): number; + ['unrestricted double'](V: unknown, opts?: WebIDLConversions.Options): number; + + float(V: unknown, opts?: WebIDLConversions.Options): number; + ['unrestricted float'](V: unknown, opts?: WebIDLConversions.Options): number; + + DOMString(V: unknown, opts?: WebIDLConversions.StringOptions): string; + ByteString(V: unknown, opts?: WebIDLConversions.StringOptions): string; + USVString(V: unknown, opts?: WebIDLConversions.StringOptions): string; + + object(V: V, opts?: WebIDLConversions.Options): V extends object ? V : V & object; + ArrayBuffer( + V: unknown, + opts?: WebIDLConversions.BufferSourceOptions & { allowShared?: false | undefined }, + ): ArrayBuffer; + ArrayBuffer(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferLike; + DataView(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): DataView; + + Int8Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int8Array; + Int16Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int16Array; + Int32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Int32Array; + + Uint8Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint8Array; + Uint16Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint16Array; + Uint32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint32Array; + Uint8ClampedArray(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Uint8ClampedArray; + + Float32Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Float32Array; + Float64Array(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): Float64Array; + + ArrayBufferView(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferView; + BufferSource( + V: unknown, + opts?: WebIDLConversions.BufferSourceOptions & { allowShared?: false | undefined }, + ): ArrayBuffer | ArrayBufferView; + BufferSource(V: unknown, opts?: WebIDLConversions.BufferSourceOptions): ArrayBufferLike | ArrayBufferView; + + DOMTimeStamp(V: unknown, opts?: WebIDLConversions.Options): number; +}; + +// This can't use ES6 style exports, as those can't have spaces in export names. +export = WebIDLConversions; diff --git a/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/package.json b/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/package.json new file mode 100644 index 00000000..90070333 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/webidl-conversions/package.json @@ -0,0 +1,30 @@ +{ + "name": "@types/webidl-conversions", + "version": "7.0.0", + "description": "TypeScript definitions for webidl-conversions", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/webidl-conversions", + "license": "MIT", + "contributors": [ + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss", + "githubUsername": "ExE-Boss" + }, + { + "name": "BendingBender", + "url": "https://github.com/BendingBender", + "githubUsername": "BendingBender" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/webidl-conversions" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "e0992101980ba36c2f7240b4be2fd23d4ea0c812f8b3c9149d2efcfce2201d3b", + "typeScriptVersion": "4.0" +} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/@types/whatwg-url/LICENSE b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/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/1_ActivityWatchProducer/node_modules/@types/whatwg-url/README.md b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/README.md new file mode 100644 index 00000000..41143c4e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/whatwg-url` + +# Summary +This package contains type definitions for whatwg-url (https://github.com/jsdom/whatwg-url#readme). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-url. + +### Additional Details + * Last updated: Tue, 21 Jun 2022 16:31:40 GMT + * Dependencies: [@types/webidl-conversions](https://npmjs.com/package/@types/webidl-conversions), [@types/node](https://npmjs.com/package/@types/node) + * Global values: none + +# Credits +These definitions were written by [Alexander Marks](https://github.com/aomarks), and [ExE Boss](https://github.com/ExE-Boss). diff --git a/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URL-impl.d.ts b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URL-impl.d.ts new file mode 100644 index 00000000..ae739464 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URL-impl.d.ts @@ -0,0 +1,23 @@ +declare class URLImpl { + constructor( + globalObject: object, + constructorArgs: readonly [url: string, base?: string], + privateData?: {}, + ); + + href: string; + readonly origin: string; + protocol: string; + username: string; + password: string; + host: string; + hostname: string; + port: string; + pathname: string; + search: string; + readonly searchParams: URLSearchParams; + hash: string; + + toJSON(): string; +} +export { URLImpl as implementation }; diff --git a/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URL.d.ts b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URL.d.ts new file mode 100644 index 00000000..47f092af --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URL.d.ts @@ -0,0 +1,76 @@ +import { Options as WebIDLConversionOptions } from "webidl-conversions"; +import { URL } from "../index"; +import { implementation as URLImpl } from "./URL-impl"; + +/** + * Checks whether `obj` is a `URL` object with an implementation + * provided by this package. + */ +export function is(obj: unknown): obj is URL; + +/** + * Checks whether `obj` is a `URLImpl` WebIDL2JS implementation object + * provided by this package. + */ +export function isImpl(obj: unknown): obj is URLImpl; + +/** + * Converts the `URL` wrapper into a `URLImpl` object. + * + * @throws {TypeError} If `obj` is not a `URL` wrapper instance provided by this package. + */ +export function convert(obj: unknown, options?: WebIDLConversionOptions): URLImpl; + +/** + * Creates a new `URL` instance. + * + * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor + * registry or a `URL` constructor provided by this package + * in the WebIDL2JS constructor registry. + */ +export function create( + globalObject: object, + constructorArgs: readonly [url: string, base?: string], + privateData?: {}, +): URL; + +/** + * Calls `create()` and returns the internal `URLImpl`. + * + * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor + * registry or a `URL` constructor provided by this package + * in the WebIDL2JS constructor registry. + */ +export function createImpl( + globalObject: object, + constructorArgs: readonly [url: string, base?: string], + privateData?: {}, +): URLImpl; + +/** + * Initializes the `URL` instance, called by `create()`. + * + * Useful when manually sub-classing a non-constructable wrapper object. + */ +export function setup( + obj: T, + globalObject: object, + constructorArgs: readonly [url: string, base?: string], + privateData?: {}, +): T; + +/** + * Creates a new `URL` object without runing the constructor steps. + * + * Useful when implementing specifications that initialize objects + * in different ways than their constructors do. + */ +declare function _new(globalObject: object): URLImpl; +export { _new as new }; + +/** + * Installs the `URL` constructor onto the `globalObject`. + * + * @throws {Error} If the target `globalObject` doesn't have an `Error` constructor. + */ +export function install(globalObject: object, globalNames: readonly string[]): void; diff --git a/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URLSearchParams-impl.d.ts b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URLSearchParams-impl.d.ts new file mode 100644 index 00000000..3464b87d --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URLSearchParams-impl.d.ts @@ -0,0 +1,23 @@ +declare class URLSearchParamsImpl { + constructor( + globalObject: object, + constructorArgs: readonly [ + init?: + | ReadonlyArray + | { readonly [name: string]: string } + | string, + ], + privateData: { readonly doNotStripQMark?: boolean | undefined }, + ); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + + [Symbol.iterator](): IterableIterator<[name: string, value: string]>; +} +export { URLSearchParamsImpl as implementation }; diff --git a/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URLSearchParams.d.ts b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URLSearchParams.d.ts new file mode 100644 index 00000000..c37585ca --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/dist/URLSearchParams.d.ts @@ -0,0 +1,91 @@ +import { Options as WebIDLConversionOptions } from "webidl-conversions"; +import { URLSearchParams } from "../index"; +import { implementation as URLSearchParamsImpl } from "./URLSearchParams-impl"; + +/** + * Checks whether `obj` is a `URLSearchParams` object with an implementation + * provided by this package. + */ +export function is(obj: unknown): obj is URLSearchParams; + +/** + * Checks whether `obj` is a `URLSearchParamsImpl` WebIDL2JS implementation object + * provided by this package. + */ +export function isImpl(obj: unknown): obj is URLSearchParamsImpl; + +/** + * Converts the `URLSearchParams` wrapper into a `URLSearchParamsImpl` object. + * + * @throws {TypeError} If `obj` is not a `URLSearchParams` wrapper instance provided by this package. + */ +export function convert(obj: unknown, options?: WebIDLConversionOptions): URLSearchParamsImpl; + +/** + * Creates a new `URLSearchParams` instance. + * + * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor + * registry or a `URLSearchParams` constructor provided by this package + * in the WebIDL2JS constructor registry. + */ +export function create( + globalObject: object, + constructorArgs?: readonly [ + init: + | ReadonlyArray<[name: string, value: string]> + | { readonly [name: string]: string } + | string, + ], + privateData?: { doNotStripQMark?: boolean | undefined }, +): URLSearchParams; + +/** + * Calls `create()` and returns the internal `URLSearchParamsImpl`. + * + * @throws {Error} If the `globalObject` doesn't have a WebIDL2JS constructor + * registry or a `URLSearchParams` constructor provided by this package + * in the WebIDL2JS constructor registry. + */ +export function createImpl( + globalObject: object, + constructorArgs?: readonly [ + init: + | ReadonlyArray<[name: string, value: string]> + | { readonly [name: string]: string } + | string, + ], + privateData?: { doNotStripQMark?: boolean | undefined }, +): URLSearchParamsImpl; + +/** + * Initializes the `URLSearchParams` instance, called by `create()`. + * + * Useful when manually sub-classing a non-constructable wrapper object. + */ +export function setup( + obj: T, + globalObject: object, + constructorArgs?: readonly [ + init: + | ReadonlyArray<[name: string, value: string]> + | { readonly [name: string]: string } + | string, + ], + privateData?: { doNotStripQMark?: boolean | undefined }, +): T; + +/** + * Creates a new `URLSearchParams` object without runing the constructor steps. + * + * Useful when implementing specifications that initialize objects + * in different ways than their constructors do. + */ +declare function _new(globalObject: object): URLSearchParamsImpl; +export { _new as new }; + +/** + * Installs the `URLSearchParams` constructor onto the `globalObject`. + * + * @throws {Error} If the target `globalObject` doesn't have an `Error` constructor. + */ +export function install(globalObject: object, globalNames: readonly string[]): void; diff --git a/1_ActivityWatchProducer/node_modules/@types/whatwg-url/index.d.ts b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/index.d.ts new file mode 100644 index 00000000..3613a962 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/index.d.ts @@ -0,0 +1,162 @@ +// Type definitions for whatwg-url 8.2 +// Project: https://github.com/jsdom/whatwg-url#readme +// Definitions by: Alexander Marks +// ExE Boss +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Minimum TypeScript Version: 3.6 + +/// + +/** https://url.spec.whatwg.org/#url-representation */ +export interface URLRecord { + scheme: string; + username: string; + password: string; + host: string | number | IPv6Address | null; + port: number | null; + path: string[]; + query: string | null; + fragment: string | null; + cannotBeABaseURL?: boolean | undefined; +} + +/** https://url.spec.whatwg.org/#concept-ipv6 */ +export type IPv6Address = [number, number, number, number, number, number, number, number]; + +/** https://url.spec.whatwg.org/#url-class */ +export class URL { + constructor(url: string, base?: string | URL); + + get href(): string; + set href(V: string); + + get origin(): string; + + get protocol(): string; + set protocol(V: string); + + get username(): string; + set username(V: string); + + get password(): string; + set password(V: string); + + get host(): string; + set host(V: string); + + get hostname(): string; + set hostname(V: string); + + get port(): string; + set port(V: string); + + get pathname(): string; + set pathname(V: string); + + get search(): string; + set search(V: string); + + get searchParams(): URLSearchParams; + + get hash(): string; + set hash(V: string); + + toJSON(): string; + + readonly [Symbol.toStringTag]: "URL"; +} + +/** https://url.spec.whatwg.org/#interface-urlsearchparams */ +export class URLSearchParams { + constructor( + init?: + | ReadonlyArray + | Iterable + | { readonly [name: string]: string } + | string, + ); + + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + set(name: string, value: string): void; + sort(): void; + + keys(): IterableIterator; + values(): IterableIterator; + entries(): IterableIterator<[name: string, value: string]>; + forEach( + callback: (this: THIS_ARG, value: string, name: string, searchParams: this) => void, + thisArg?: THIS_ARG, + ): void; + + readonly [Symbol.toStringTag]: "URLSearchParams"; + [Symbol.iterator](): IterableIterator<[name: string, value: string]>; +} + +/** https://url.spec.whatwg.org/#concept-url-parser */ +export function parseURL( + input: string, + options?: { readonly baseURL?: string | undefined; readonly encodingOverride?: string | undefined }, +): URLRecord | null; + +/** https://url.spec.whatwg.org/#concept-basic-url-parser */ +export function basicURLParse( + input: string, + options?: { + baseURL?: string | undefined; + encodingOverride?: string | undefined; + url?: URLRecord | undefined; + stateOverride?: StateOverride | undefined; + }, +): URLRecord | null; + +/** https://url.spec.whatwg.org/#scheme-start-state */ +export type StateOverride = + | "scheme start" + | "scheme" + | "no scheme" + | "special relative or authority" + | "path or authority" + | "relative" + | "relative slash" + | "special authority slashes" + | "special authority ignore slashes" + | "authority" + | "host" + | "hostname" + | "port" + | "file" + | "file slash" + | "file host" + | "path start" + | "path" + | "cannot-be-a-base-URL path" + | "query" + | "fragment"; + +/** https://url.spec.whatwg.org/#concept-url-serializer */ +export function serializeURL(urlRecord: URLRecord, excludeFragment?: boolean): string; + +/** https://url.spec.whatwg.org/#concept-host-serializer */ +export function serializeHost(host: string | number | IPv6Address): string; + +/** https://url.spec.whatwg.org/#serialize-an-integer */ +export function serializeInteger(number: number): string; + +/** https://html.spec.whatwg.org#ascii-serialisation-of-an-origin */ +export function serializeURLOrigin(urlRecord: URLRecord): string; + +/** https://url.spec.whatwg.org/#set-the-username */ +export function setTheUsername(urlRecord: URLRecord, username: string): void; + +/** https://url.spec.whatwg.org/#set-the-password */ +export function setThePassword(urlRecord: URLRecord, password: string): void; + +/** https://url.spec.whatwg.org/#cannot-have-a-username-password-port */ +export function cannotHaveAUsernamePasswordPort(urlRecord: URLRecord): boolean; + +/** https://url.spec.whatwg.org/#percent-decode */ +export function percentDecode(buffer: Extract>): Buffer; diff --git a/1_ActivityWatchProducer/node_modules/@types/whatwg-url/package.json b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/package.json new file mode 100644 index 00000000..120d4906 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/package.json @@ -0,0 +1,33 @@ +{ + "name": "@types/whatwg-url", + "version": "8.2.2", + "description": "TypeScript definitions for whatwg-url", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/whatwg-url", + "license": "MIT", + "contributors": [ + { + "name": "Alexander Marks", + "url": "https://github.com/aomarks", + "githubUsername": "aomarks" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss", + "githubUsername": "ExE-Boss" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/whatwg-url" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*", + "@types/webidl-conversions": "*" + }, + "typesPublisherContentHash": "ea85d67c501583ff421cfbf206fafac0410c464edef169a6d88e06ecfe226dfc", + "typeScriptVersion": "4.0" +} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts new file mode 100644 index 00000000..3b39af8d --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/@types/whatwg-url/webidl2js-wrapper.d.ts @@ -0,0 +1,4 @@ +import * as URL from "./dist/URL"; +import * as URLSearchParams from "./dist/URLSearchParams"; + +export { URL, URLSearchParams }; diff --git a/1_ActivityWatchProducer/node_modules/bson/LICENSE.md b/1_ActivityWatchProducer/node_modules/bson/LICENSE.md new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/LICENSE.md @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + 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] + + 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. diff --git a/1_ActivityWatchProducer/node_modules/bson/README.md b/1_ActivityWatchProducer/node_modules/bson/README.md new file mode 100644 index 00000000..a83d5622 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/README.md @@ -0,0 +1,368 @@ +# BSON parser + +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). + +### 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 +``` + +### Node.js or Bundling Usage + +When using a bundler or Node.js you can import bson using the package name: + +```js +import { BSON, EJSON, ObjectId } from 'bson'; +// or: +// const { BSON, EJSON, ObjectId } = require('bson'); + +const bytes = BSON.serialize({ _id: new ObjectId() }); +console.log(bytes); +const doc = BSON.deserialize(bytes); +console.log(EJSON.stringify(doc)); +// {"_id":{"$oid":"..."}} +``` + +### Browser Usage + +If you are working directly in the browser without a bundler please use the `.mjs` bundle like so: + +```html + +``` + +## Installation + +```sh +npm install bson +``` + +## Documentation + +### Objects + +
+
EJSON : object
+
+
+ +### Functions + +
+
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.

+
+
+ + + +### EJSON + +* [EJSON](#EJSON) + + * [.parse(text, [options])](#EJSON.parse) + + * [.stringify(value, [replacer], [space], [options])](#EJSON.stringify) + + * [.serialize(bson, [options])](#EJSON.serialize) + + * [.deserialize(ejson, [options])](#EJSON.deserialize) + + + + +#### *EJSON*.parse(text, [options]) + +| 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) | + +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)); +``` + + +#### *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) }; + +// prints '{"int32":{"$numberInt":"10"}}' +console.log(EJSON.stringify(doc, { relaxed: false })); + +// 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.useBigInt64] | Object | false | when deserializing a Long will return a BigInt. | +| [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. + +## Error Handling + +It is our recommendation to use `BSONError.isBSONError()` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. We guarantee `BSONError.isBSONError()` 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. + +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 `BSONError.isBSONError()` will always be able to accurately capture the errors that our BSON library throws. + +Hypothetical example: A collection in our Db has an issue with UTF-8 data: + +```ts +let documentCount = 0; +const cursor = collection.find({}, { utf8Validation: true }); +try { + for await (const doc of cursor) documentCount += 1; +} catch (error) { + if (BSONError.isBSONError(error)) { + console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`); + return documentCount; + } + throw error; +} +``` + +## React Native + +BSON requires that `TextEncoder`, `TextDecoder`, `atob`, `btoa`, and `crypto.getRandomValues` are available globally. These are present in most Javascript runtimes but require polyfilling in React Native. Polyfills for the missing functionality can be installed with the following command: +```sh +npm install --save react-native-get-random-values text-encoding-polyfill base-64 +``` + +The following snippet should be placed at the top of the entrypoint (by default this is the root `index.js` file) for React Native projects using the BSON library. These lines must be placed for any code that imports `BSON`. + +```typescript +// Required Polyfills For ReactNative +import {encode, decode} from 'base-64'; +if (global.btoa == null) { + global.btoa = encode; +} +if (global.atob == null) { + global.atob = decode; +} +import 'text-encoding-polyfill'; +import 'react-native-get-random-values'; +``` + +Finally, import the `BSON` library like so: + +```typescript +import { BSON, EJSON } from 'bson'; +``` + +This will cause React Native to import the `node_modules/bson/lib/bson.cjs` bundle (see the `"react-native"` setting we have in the `"exports"` section of our [package.json](./package.json).) + +### Technical Note about React Native module import + +The `"exports"` definition in our `package.json` will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in [React Native's runtime hermes](https://hermesengine.dev/). + +## 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/1_ActivityWatchProducer/node_modules/bson/bson.d.ts b/1_ActivityWatchProducer/node_modules/bson/bson.d.ts new file mode 100644 index 00000000..11860a3c --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/bson.d.ts @@ -0,0 +1,1225 @@ +/** + * A class representation of the BSON Binary type. + * @public + * @category BSONType + */ +export declare class Binary extends BSONValue { + get _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: Uint8Array; + 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 | 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(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): 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 | number[]; + +declare namespace BSON { + export { + setInternalBufferSize, + serialize, + serializeWithBufferAndIndex, + deserialize, + calculateObjectSize, + deserializeStream, + UUIDExtended, + BinaryExtended, + BinaryExtendedLegacy, + BinarySequence, + CodeExtended, + DBRefLike, + Decimal128Extended, + DoubleExtended, + EJSONOptions, + Int32Extended, + LongExtended, + MaxKeyExtended, + MinKeyExtended, + ObjectIdExtended, + ObjectIdLike, + BSONRegExpExtended, + BSONRegExpExtendedLegacy, + BSONSymbolExtended, + LongWithoutOverrides, + TimestampExtended, + TimestampOverrides, + LongWithoutOverridesClass, + SerializeOptions, + DeserializeOptions, + Code, + BSONSymbol, + DBRef, + Binary, + ObjectId, + UUID, + Long, + Timestamp, + Double, + Int32, + MinKey, + MaxKey, + BSONRegExp, + Decimal128, + BSONValue, + BSONError, + BSONVersionError, + BSONRuntimeError, + BSONType, + EJSON, + Document, + CalculateObjectSizeOptions + } +} +export { BSON } + +/** + * @public + * @category Error + * + * `BSONError` objects are thrown when BSON ecounters an error. + * + * This is the parent class for all the other errors thrown by this library. + */ +export declare class BSONError extends Error { + /* Excluded from this release type: bsonError */ + get name(): string; + constructor(message: string); + /** + * @public + * + * All errors thrown from the BSON library inherit from `BSONError`. + * This method can assist with determining if an error originates from the BSON library + * even if it does not pass an `instanceof` check against this class' constructor. + * + * @param value - any javascript value that needs type checking + */ + static isBSONError(value: unknown): value is BSONError; +} + +/** + * A class representation of the BSON RegExp type. + * @public + * @category BSONType + */ +export declare class BSONRegExp extends BSONValue { + get _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 */ + inspect(): string; +} + +/** @public */ +export declare interface BSONRegExpExtended { + $regularExpression: { + pattern: string; + options: string; + }; +} + +/** @public */ +export declare interface BSONRegExpExtendedLegacy { + $regex: string | BSONRegExp; + $options: string; +} + +/** + * @public + * @category Error + * + * An error generated when BSON functions encounter an unexpected input + * or reaches an unexpected/invalid internal state + * + */ +export declare class BSONRuntimeError extends BSONError { + get name(): 'BSONRuntimeError'; + constructor(message: string); +} + +/** + * A class representation of the BSON Symbol type. + * @public + * @category BSONType + */ +export declare class BSONSymbol extends BSONValue { + get _bsontype(): 'BSONSymbol'; + value: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string); + /** Access the wrapped string value. */ + valueOf(): string; + toString(): string; + inspect(): string; + toJSON(): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ +} + +/** @public */ +export declare interface BSONSymbolExtended { + $symbol: string; +} + +/** @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 abstract class BSONValue { + /** @public */ + abstract get _bsontype(): string; + /** @public */ + abstract inspect(): string; + /* Excluded from this release type: toExtendedJSON */ +} + +/** + * @public + * @category Error + */ +export declare class BSONVersionError extends BSONError { + get name(): 'BSONVersionError'; + constructor(); +} + +/** + * 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 extends BSONValue { + get _bsontype(): 'Code'; + code: string; + scope: Document | null; + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document | null); + toJSON(): { + code: string; + scope?: Document; + }; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface CodeExtended { + $code: string; + $scope?: Document; +} + +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +export declare class DBRef extends BSONValue { + get _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 extends BSONValue { + get _bsontype(): 'Decimal128'; + readonly bytes: Uint8Array; + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Uint8Array | 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: Uint8Array, options?: DeserializeOptions): Document; + +/** @public */ +export declare interface DeserializeOptions { + /** when deserializing a Long will return as a BigInt. */ + useBigInt64?: 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: Uint8Array | 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 extends BSONValue { + get _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; +} + +/** @public */ +export declare const EJSON: { + parse: typeof parse; + stringify: typeof stringify; + serialize: typeof EJSONserialize; + deserialize: typeof EJSONdeserialize; +}; + +/** + * 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 + */ +declare function EJSONdeserialize(ejson: Document, options?: EJSONOptions): any; + +/** @public */ +export declare type EJSONOptions = { + /** 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; + /** Enable native bigint support */ + useBigInt64?: boolean; +}; + +/** + * 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 + */ +declare function EJSONserialize(value: any, options?: EJSONOptions): Document; + +/** + * A class representation of a BSON Int32 type. + * @public + * @category BSONType + */ +export declare class Int32 extends BSONValue { + get _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; + +/** + * 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 extends BSONValue { + get _bsontype(): 'Long'; + /** An indicator used to reliably determine if an object is a Long or not. */ + get __isLong__(): boolean; + /** + * 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 | bigint; + inspect(): string; +} + +/** @public */ +export declare interface LongExtended { + $numberLong: string; +} + +/** @public */ +export declare type LongWithoutOverrides = new (low: unknown, high?: number | boolean, unsigned?: boolean) => { + [P in Exclude]: Long[P]; +}; + +/** @public */ +export declare const LongWithoutOverridesClass: LongWithoutOverrides; + +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +export declare class MaxKey extends BSONValue { + get _bsontype(): 'MaxKey'; + /* 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 extends BSONValue { + get _bsontype(): 'MinKey'; + /* 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 + */ +export declare class ObjectId extends BSONValue { + get _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 | Uint8Array); + /** + * The ObjectId bytes + * @readonly + */ + get id(): Uint8Array; + set id(value: Uint8Array); + /** 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): Uint8Array; + /** + * Converts the id into a 24 character hex string for printing, unless encoding is provided. + * @param encoding - hex or base64 + */ + toString(encoding?: 'hex' | 'base64'): 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 | Uint8Array): boolean; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface ObjectIdExtended { + $oid: string; +} + +/** @public */ +export declare interface ObjectIdLike { + id: string | Uint8Array; + __id?: string; + toHexString(): string; +} + +/** + * 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)); + * ``` + */ +declare function parse(text: string, options?: EJSONOptions): any; + +/** + * 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): Uint8Array; + +/** @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: Uint8Array, 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; + +/** + * 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)); + * ``` + */ +declare function stringify(value: any, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSONOptions, space?: string | number, options?: EJSONOptions): string; + +/** + * @public + * @category BSONType + * */ +export declare class Timestamp extends LongWithoutOverridesClass { + get _bsontype(): 'Timestamp'; + static readonly MAX_VALUE: Long; + /** + * @param int - A 64-bit bigint representing the Timestamp. + */ + constructor(int: bigint); + /** + * @param long - 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; + }); + 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 extends Binary { + static cacheHexString: boolean; + /* 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 | Uint8Array | UUID); + /** + * The UUID bytes + * @readonly + */ + get id(): Uint8Array; + set id(value: Uint8Array); + /** + * 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?: 'hex' | 'base64'): 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 | Uint8Array | UUID): boolean; + /** + * Creates a Binary instance from the current UUID. + */ + toBinary(): Binary; + /** + * Generates a populated buffer containing a v4 uuid + */ + static generate(): Uint8Array; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Uint8Array | 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/1_ActivityWatchProducer/node_modules/bson/etc/prepare.js b/1_ActivityWatchProducer/node_modules/bson/etc/prepare.js new file mode 100644 index 00000000..91e6f3a9 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/bson/lib/bson.bundle.js b/1_ActivityWatchProducer/node_modules/bson/lib/bson.bundle.js new file mode 100644 index 00000000..a1a04dca --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/lib/bson.bundle.js @@ -0,0 +1,4090 @@ +var BSON = (function (exports) { +'use strict'; + +const BSON_MAJOR_VERSION = 5; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +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 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message) { + super(message); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); + } +} +class BSONRuntimeError extends BSONError { + get name() { + return 'BSONRuntimeError'; + } + constructor(message) { + super(message); + } +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = (() => { + try { + return require('crypto').randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + fromUTF8(text) { + return Buffer.from(text, 'utf8'); + }, + toUTF8(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + fromUTF8(text) { + return new TextEncoder().encode(text); + }, + toUTF8(uint8array) { + return new TextDecoder('utf8', { fatal: false }).decode(uint8array); + }, + utf8ByteLength(input) { + return webByteUtils.fromUTF8(input).byteLength; + }, + encodeUTF8Into(buffer, source, byteOffset) { + const bytes = webByteUtils.fromUTF8(source); + buffer.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; +class BSONDataView extends DataView { + static fromUint8Array(input) { + return new DataView(input.buffer, input.byteOffset, input.byteLength); + } +} + +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; +const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); +const uuidHexStringToBuffer = (hexString) => { + if (!uuidValidateString(hexString)) { + throw new BSONError('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 ByteUtils.fromHex(sanitizedHexString); +}; +function bufferToUuidHexString(buffer, includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(buffer.subarray(0, 4)), + ByteUtils.toHex(buffer.subarray(4, 6)), + ByteUtils.toHex(buffer.subarray(6, 8)), + ByteUtils.toHex(buffer.subarray(8, 10)), + ByteUtils.toHex(buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(buffer); +} + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + this.buffer = ByteUtils.fromISO88591(buffer); + } + else if (Array.isArray(buffer)) { + this.buffer = ByteUtils.fromNumberArray(buffer); + } + else { + this.buffer = ByteUtils.toLocalBufferType(buffer); + } + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let 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 BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + const bytes = ByteUtils.fromISO88591(sequence); + this.buffer.set(bytes, offset); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value(asRaw) { + asRaw = !!asRaw; + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer); + return ByteUtils.toUTF8(this.buffer); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + 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() { + 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.`); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + 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 = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +class UUID extends Binary { + constructor(input) { + let bytes; + let hexStr; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + hexStr = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = uuidHexStringToBuffer(input); + } + else { + throw new BSONError('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).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + this.__id = hexStr; + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + toHexString(includeDashes = true) { + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + const uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + if (input.byteLength !== UUID_BYTE_LENGTH) { + return false; + } + return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; + } + return false; + } + static createFromHexString(hexString) { + const buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new UUID("${this.toHexString()}")`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const codeJson = this.toJSON(); + return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let 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; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + 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}"` : ''})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(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 { +} +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; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + 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; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + 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; + } + } + static fromNumber(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); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + 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; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(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); + } + static fromBytesBE(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); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + 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); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + 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; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + 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) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + 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 { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + 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); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(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; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + 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)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + 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 (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + 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); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(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); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(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); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + 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); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + 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 + ]; + } + toBytesBE() { + 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 + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + 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); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + 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; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +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; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + 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++) { + _rem = _rem.shiftLeft(32); + _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 }; +} +function multiply64x2(left, right) { + 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 { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + 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, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + let isNegative = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let firstDigit = 0; + let lastDigit = 0; + let exponent = 0; + let i = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + 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; + 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 BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + 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; + } + } + } + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit - firstDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + 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; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + 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)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + 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; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocate(16); + index = 0; + 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; + 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; + 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; + 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 new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + 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; + } + const exponent = biased_exponent - EXPONENT_BIAS; + 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; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + 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++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + 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() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Decimal128("${this.toString()}")`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const eJSON = this.toExtendedJSON(); + return `new Double(${eJSON.$numberDouble})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Int32(${this.valueOf()})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MinKey()'; + } +} + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +const kId = Symbol('id'); +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this[kId] = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 12) { + const bytes = ByteUtils.fromUTF8(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes'); + } + } + else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this[kId]; + } + set id(value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocate(12); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + 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]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); + } + 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 ByteUtils.equals(ByteUtils.fromUTF8(otherId), 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; + } + getTimestamp() { + const timestamp = new Date(); + const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + static createFromTime(time) { + const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new ObjectId("${this.toHexString()}")`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + 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 (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + 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)}`); + } + 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) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + 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 BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + inspect() { + return `new BSONSymbol("${this.value}")`; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + if (low.t < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (low.i < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (low.t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (low.i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(low.i.valueOf(), low.t.valueOf(), true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +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; +function validateUtf8(bytes, start, end) { + 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; +} + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + 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})`); + } + 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"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + const utf8KeysSet = new Set(); + 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]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i)); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === 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 === BSON_DATA_OID) { + const oid = ByteUtils.allocate(12); + oid.set(buffer.subarray(index, index + 12)); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(dataview.getFloat64(index, true)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = dataview.getFloat64(index, true); + index = index + 8; + } + else if (elementType === 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 === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === 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'); + 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 === 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; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, 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 === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); + 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); + if (useBigInt64) { + value = dataview.getBigInt64(0, true); + } + else 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 === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocate(16); + bytes.set(buffer.subarray(index, index + 16), 0); + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + 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 = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = value.toUUID(); + } + } + } + else { + const _buffer = ByteUtils.allocate(binarySize); + 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'); + } + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + 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 === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === 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 === BSON_DATA_TIMESTAMP) { + const i = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + const t = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + value = new Timestamp({ i, t }); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === 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); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + 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); + index = index + stringSize; + const _index = index; + const objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + 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'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); + index = index + stringSize; + const oidBuffer = ByteUtils.allocate(12); + oidBuffer.set(buffer.subarray(index, index + 12), 0); + const oid = new ObjectId(oidBuffer); + index = index + 12; + 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; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +function getValidatedString(buffer, start, end, shouldValidateUtf8) { + const value = ByteUtils.toUTF8(buffer.subarray(start, end)); + 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; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + 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; + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); +const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); +const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + if (type === BSON_DATA_INT) { + NUMBER_SPACE.setInt32(0, value, true); + } + else { + NUMBER_SPACE.setFloat64(0, value, true); + } + const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + buffer.set(bytes, index); + index += bytes.byteLength; + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setBigInt64(0, value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (isUint8Array(value.id)) { + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + return index + 12; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + buffer.set(value, index); + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + 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) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setFloat64(0, value.value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + 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; + buffer[index++] = value.sub_type; + 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; + } + buffer.set(data, index); + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $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, true, path); + const size = endIndex - startIndex; + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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 (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (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 (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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 === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +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 +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + 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 === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof 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); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof 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; + 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; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + 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 BSONError('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(), 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))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + 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) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(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) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(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 (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + 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); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + 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, ejsonOptions); + }); +} +function stringify(value, 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; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, 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; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocate(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, 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; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + 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); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ +__proto__: null, +Code: Code, +BSONSymbol: BSONSymbol, +DBRef: DBRef, +Binary: Binary, +ObjectId: ObjectId, +UUID: UUID, +Long: Long, +Timestamp: Timestamp, +Double: Double, +Int32: Int32, +MinKey: MinKey, +MaxKey: MaxKey, +BSONRegExp: BSONRegExp, +Decimal128: Decimal128, +setInternalBufferSize: setInternalBufferSize, +serialize: serialize, +serializeWithBufferAndIndex: serializeWithBufferAndIndex, +deserialize: deserialize, +calculateObjectSize: calculateObjectSize, +deserializeStream: deserializeStream, +BSONValue: BSONValue, +BSONError: BSONError, +BSONVersionError: BSONVersionError, +BSONRuntimeError: BSONRuntimeError, +BSONType: BSONType, +EJSON: EJSON +}); + +exports.BSON = bson; +exports.BSONError = BSONError; +exports.BSONRegExp = BSONRegExp; +exports.BSONRuntimeError = BSONRuntimeError; +exports.BSONSymbol = BSONSymbol; +exports.BSONType = BSONType; +exports.BSONValue = BSONValue; +exports.BSONVersionError = BSONVersionError; +exports.Binary = Binary; +exports.Code = Code; +exports.DBRef = DBRef; +exports.Decimal128 = Decimal128; +exports.Double = Double; +exports.EJSON = EJSON; +exports.Int32 = Int32; +exports.Long = Long; +exports.MaxKey = MaxKey; +exports.MinKey = MinKey; +exports.ObjectId = ObjectId; +exports.Timestamp = Timestamp; +exports.UUID = UUID; +exports.calculateObjectSize = calculateObjectSize; +exports.deserialize = deserialize; +exports.deserializeStream = deserializeStream; +exports.serialize = serialize; +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +exports.setInternalBufferSize = setInternalBufferSize; + +return exports; + +})({}); +//# sourceMappingURL=bson.bundle.js.map diff --git a/1_ActivityWatchProducer/node_modules/bson/lib/bson.bundle.js.map b/1_ActivityWatchProducer/node_modules/bson/lib/bson.bundle.js.map new file mode 100644 index 00000000..63253408 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/lib/bson.bundle.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.bundle.js","sources":["../src/constants.ts","../src/error.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/uuid_utils.ts","../src/parser/utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":";;;AACO,MAAM,kBAAkB,GAAG,CAAU,CAAC;AAGtC,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC,MAAM,cAAc,GAAG,CAAC,UAAU,CAAC;AAEnC,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAE3C,MAAM,cAAc,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAMxC,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAMnC,MAAM,UAAU,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAGpC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,eAAe,GAAG,CAAC,CAAC;AAG1B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAG9B,MAAM,aAAa,GAAG,CAAC,CAAC;AAGxB,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAG5B,MAAM,cAAc,GAAG,CAAC,CAAC;AAGzB,MAAM,cAAc,GAAG,EAAE,CAAC;AAG1B,MAAM,gBAAgB,GAAG,EAAE,CAAC;AAG5B,MAAM,mBAAmB,GAAG,EAAE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C;IAEhF,OAAO,2BAA2B,CAAC,MAAM,EAAE,kBAAkB,EAAE,eAAe,CAAC,CAAC;AAClF,CAAC;AAce,SAAA,iBAAiB,CAC/B,IAA8B,EAC9B,UAAkB,EAClB,iBAAyB,EACzB,SAAqB,EACrB,aAAqB,EACrB,OAA2B,EAAA;AAE3B,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CACnC,EAAE,gCAAgC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,EACpD,OAAO,CACR,CAAC;IACF,MAAM,UAAU,GAAG,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAErD,IAAI,KAAK,GAAG,UAAU,CAAC;IAEvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;AAE1C,QAAA,MAAM,IAAI,GACR,UAAU,CAAC,KAAK,CAAC;aAChB,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;aAC3B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;aAC5B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAEhC,QAAA,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;AAE9B,QAAA,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAEhF,QAAA,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AACtB,KAAA;AAGD,IAAA,OAAO,KAAK,CAAC;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/bson/lib/bson.cjs b/1_ActivityWatchProducer/node_modules/bson/lib/bson.cjs new file mode 100644 index 00000000..88ea5ce7 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/lib/bson.cjs @@ -0,0 +1,4085 @@ +'use strict'; + +const BSON_MAJOR_VERSION = 5; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +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 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message) { + super(message); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); + } +} +class BSONRuntimeError extends BSONError { + get name() { + return 'BSONRuntimeError'; + } + constructor(message) { + super(message); + } +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = (() => { + try { + return require('crypto').randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + fromUTF8(text) { + return Buffer.from(text, 'utf8'); + }, + toUTF8(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + fromUTF8(text) { + return new TextEncoder().encode(text); + }, + toUTF8(uint8array) { + return new TextDecoder('utf8', { fatal: false }).decode(uint8array); + }, + utf8ByteLength(input) { + return webByteUtils.fromUTF8(input).byteLength; + }, + encodeUTF8Into(buffer, source, byteOffset) { + const bytes = webByteUtils.fromUTF8(source); + buffer.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; +class BSONDataView extends DataView { + static fromUint8Array(input) { + return new DataView(input.buffer, input.byteOffset, input.byteLength); + } +} + +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; +const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); +const uuidHexStringToBuffer = (hexString) => { + if (!uuidValidateString(hexString)) { + throw new BSONError('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 ByteUtils.fromHex(sanitizedHexString); +}; +function bufferToUuidHexString(buffer, includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(buffer.subarray(0, 4)), + ByteUtils.toHex(buffer.subarray(4, 6)), + ByteUtils.toHex(buffer.subarray(6, 8)), + ByteUtils.toHex(buffer.subarray(8, 10)), + ByteUtils.toHex(buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(buffer); +} + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + this.buffer = ByteUtils.fromISO88591(buffer); + } + else if (Array.isArray(buffer)) { + this.buffer = ByteUtils.fromNumberArray(buffer); + } + else { + this.buffer = ByteUtils.toLocalBufferType(buffer); + } + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let 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 BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + const bytes = ByteUtils.fromISO88591(sequence); + this.buffer.set(bytes, offset); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value(asRaw) { + asRaw = !!asRaw; + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer); + return ByteUtils.toUTF8(this.buffer); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + 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() { + 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.`); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + 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 = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +class UUID extends Binary { + constructor(input) { + let bytes; + let hexStr; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + hexStr = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = uuidHexStringToBuffer(input); + } + else { + throw new BSONError('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).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + this.__id = hexStr; + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + toHexString(includeDashes = true) { + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + const uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + if (input.byteLength !== UUID_BYTE_LENGTH) { + return false; + } + return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; + } + return false; + } + static createFromHexString(hexString) { + const buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new UUID("${this.toHexString()}")`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const codeJson = this.toJSON(); + return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let 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; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + 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}"` : ''})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(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 { +} +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; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + 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; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + 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; + } + } + static fromNumber(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); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + 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; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(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); + } + static fromBytesBE(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); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + 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); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + 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; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + 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) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + 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 { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + 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); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(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; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + 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)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + 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 (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + 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); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(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); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(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); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + 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); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + 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 + ]; + } + toBytesBE() { + 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 + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + 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); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + 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; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +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; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + 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++) { + _rem = _rem.shiftLeft(32); + _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 }; +} +function multiply64x2(left, right) { + 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 { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + 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, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + let isNegative = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let firstDigit = 0; + let lastDigit = 0; + let exponent = 0; + let i = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + 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; + 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 BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + 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; + } + } + } + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit - firstDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + 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; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + 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)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + 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; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocate(16); + index = 0; + 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; + 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; + 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; + 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 new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + 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; + } + const exponent = biased_exponent - EXPONENT_BIAS; + 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; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + 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++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + 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() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Decimal128("${this.toString()}")`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const eJSON = this.toExtendedJSON(); + return `new Double(${eJSON.$numberDouble})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Int32(${this.valueOf()})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MinKey()'; + } +} + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +const kId = Symbol('id'); +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this[kId] = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 12) { + const bytes = ByteUtils.fromUTF8(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes'); + } + } + else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this[kId]; + } + set id(value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocate(12); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + 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]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); + } + 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 ByteUtils.equals(ByteUtils.fromUTF8(otherId), 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; + } + getTimestamp() { + const timestamp = new Date(); + const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + static createFromTime(time) { + const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new ObjectId("${this.toHexString()}")`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + 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 (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + 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)}`); + } + 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) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + 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 BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + inspect() { + return `new BSONSymbol("${this.value}")`; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + if (low.t < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (low.i < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (low.t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (low.i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(low.i.valueOf(), low.t.valueOf(), true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +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; +function validateUtf8(bytes, start, end) { + 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; +} + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + 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})`); + } + 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"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + const utf8KeysSet = new Set(); + 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]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i)); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === 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 === BSON_DATA_OID) { + const oid = ByteUtils.allocate(12); + oid.set(buffer.subarray(index, index + 12)); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(dataview.getFloat64(index, true)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = dataview.getFloat64(index, true); + index = index + 8; + } + else if (elementType === 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 === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === 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'); + 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 === 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; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, 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 === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); + 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); + if (useBigInt64) { + value = dataview.getBigInt64(0, true); + } + else 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 === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocate(16); + bytes.set(buffer.subarray(index, index + 16), 0); + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + 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 = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = value.toUUID(); + } + } + } + else { + const _buffer = ByteUtils.allocate(binarySize); + 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'); + } + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + 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 === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === 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 === BSON_DATA_TIMESTAMP) { + const i = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + const t = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + value = new Timestamp({ i, t }); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === 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); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + 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); + index = index + stringSize; + const _index = index; + const objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + 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'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); + index = index + stringSize; + const oidBuffer = ByteUtils.allocate(12); + oidBuffer.set(buffer.subarray(index, index + 12), 0); + const oid = new ObjectId(oidBuffer); + index = index + 12; + 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; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +function getValidatedString(buffer, start, end, shouldValidateUtf8) { + const value = ByteUtils.toUTF8(buffer.subarray(start, end)); + 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; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + 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; + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); +const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); +const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + if (type === BSON_DATA_INT) { + NUMBER_SPACE.setInt32(0, value, true); + } + else { + NUMBER_SPACE.setFloat64(0, value, true); + } + const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + buffer.set(bytes, index); + index += bytes.byteLength; + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setBigInt64(0, value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (isUint8Array(value.id)) { + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + return index + 12; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + buffer.set(value, index); + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + 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) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setFloat64(0, value.value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + 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; + buffer[index++] = value.sub_type; + 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; + } + buffer.set(data, index); + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $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, true, path); + const size = endIndex - startIndex; + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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 (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (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 (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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 === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +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 +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + 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 === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof 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); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof 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; + 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; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + 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 BSONError('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(), 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))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + 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) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(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) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(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 (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + 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); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + 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, ejsonOptions); + }); +} +function stringify(value, 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; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, 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; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocate(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, 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; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + 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); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ + __proto__: null, + Code: Code, + BSONSymbol: BSONSymbol, + DBRef: DBRef, + Binary: Binary, + ObjectId: ObjectId, + UUID: UUID, + Long: Long, + Timestamp: Timestamp, + Double: Double, + Int32: Int32, + MinKey: MinKey, + MaxKey: MaxKey, + BSONRegExp: BSONRegExp, + Decimal128: Decimal128, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONValue: BSONValue, + BSONError: BSONError, + BSONVersionError: BSONVersionError, + BSONRuntimeError: BSONRuntimeError, + BSONType: BSONType, + EJSON: EJSON +}); + +exports.BSON = bson; +exports.BSONError = BSONError; +exports.BSONRegExp = BSONRegExp; +exports.BSONRuntimeError = BSONRuntimeError; +exports.BSONSymbol = BSONSymbol; +exports.BSONType = BSONType; +exports.BSONValue = BSONValue; +exports.BSONVersionError = BSONVersionError; +exports.Binary = Binary; +exports.Code = Code; +exports.DBRef = DBRef; +exports.Decimal128 = Decimal128; +exports.Double = Double; +exports.EJSON = EJSON; +exports.Int32 = Int32; +exports.Long = Long; +exports.MaxKey = MaxKey; +exports.MinKey = MinKey; +exports.ObjectId = ObjectId; +exports.Timestamp = Timestamp; +exports.UUID = UUID; +exports.calculateObjectSize = calculateObjectSize; +exports.deserialize = deserialize; +exports.deserializeStream = deserializeStream; +exports.serialize = serialize; +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +exports.setInternalBufferSize = setInternalBufferSize; +//# sourceMappingURL=bson.cjs.map diff --git a/1_ActivityWatchProducer/node_modules/bson/lib/bson.cjs.map b/1_ActivityWatchProducer/node_modules/bson/lib/bson.cjs.map new file mode 100644 index 00000000..1cbebfb2 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/lib/bson.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.cjs","sources":["../src/constants.ts","../src/error.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/uuid_utils.ts","../src/parser/utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":";;AACO,MAAM,kBAAkB,GAAG,CAAU,CAAC;AAGtC,MAAM,cAAc,GAAG,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C,IAAI,CAAC,CAAC;IAErD,IAAI,KAAK,GAAG,UAAU,CAAC;IAEvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;AAE1C,QAAA,MAAM,IAAI,GACR,UAAU,CAAC,KAAK,CAAC;aAChB,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;aAC3B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;aAC5B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAEhC,QAAA,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;AAE9B,QAAA,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAEhF,QAAA,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AACtB,KAAA;AAGD,IAAA,OAAO,KAAK,CAAC;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/bson/lib/bson.mjs b/1_ActivityWatchProducer/node_modules/bson/lib/bson.mjs new file mode 100644 index 00000000..cc5f7abe --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/lib/bson.mjs @@ -0,0 +1,4057 @@ +const BSON_MAJOR_VERSION = 5; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +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 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message) { + super(message); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); + } +} +class BSONRuntimeError extends BSONError { + get name() { + return 'BSONRuntimeError'; + } + constructor(message) { + super(message); + } +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = await (async () => { + try { + return (await import('crypto')).randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + fromUTF8(text) { + return Buffer.from(text, 'utf8'); + }, + toUTF8(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + fromUTF8(text) { + return new TextEncoder().encode(text); + }, + toUTF8(uint8array) { + return new TextDecoder('utf8', { fatal: false }).decode(uint8array); + }, + utf8ByteLength(input) { + return webByteUtils.fromUTF8(input).byteLength; + }, + encodeUTF8Into(buffer, source, byteOffset) { + const bytes = webByteUtils.fromUTF8(source); + buffer.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; +class BSONDataView extends DataView { + static fromUint8Array(input) { + return new DataView(input.buffer, input.byteOffset, input.byteLength); + } +} + +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; +const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); +const uuidHexStringToBuffer = (hexString) => { + if (!uuidValidateString(hexString)) { + throw new BSONError('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 ByteUtils.fromHex(sanitizedHexString); +}; +function bufferToUuidHexString(buffer, includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(buffer.subarray(0, 4)), + ByteUtils.toHex(buffer.subarray(4, 6)), + ByteUtils.toHex(buffer.subarray(6, 8)), + ByteUtils.toHex(buffer.subarray(8, 10)), + ByteUtils.toHex(buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(buffer); +} + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + this.buffer = ByteUtils.fromISO88591(buffer); + } + else if (Array.isArray(buffer)) { + this.buffer = ByteUtils.fromNumberArray(buffer); + } + else { + this.buffer = ByteUtils.toLocalBufferType(buffer); + } + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let 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 BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + const bytes = ByteUtils.fromISO88591(sequence); + this.buffer.set(bytes, offset); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value(asRaw) { + asRaw = !!asRaw; + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer); + return ByteUtils.toUTF8(this.buffer); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + 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() { + 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.`); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + 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 = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +class UUID extends Binary { + constructor(input) { + let bytes; + let hexStr; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + hexStr = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = uuidHexStringToBuffer(input); + } + else { + throw new BSONError('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).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + this.__id = hexStr; + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + toHexString(includeDashes = true) { + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + const uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + if (input.byteLength !== UUID_BYTE_LENGTH) { + return false; + } + return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; + } + return false; + } + static createFromHexString(hexString) { + const buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new UUID("${this.toHexString()}")`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const codeJson = this.toJSON(); + return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let 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; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + 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}"` : ''})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(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 { +} +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; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + 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; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + 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; + } + } + static fromNumber(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); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + 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; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(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); + } + static fromBytesBE(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); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + 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); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + 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; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + 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) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + 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 { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + 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); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(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; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + 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)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + 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 (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + 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); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(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); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(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); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + 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); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + 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 + ]; + } + toBytesBE() { + 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 + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + 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); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + 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; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +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; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + 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++) { + _rem = _rem.shiftLeft(32); + _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 }; +} +function multiply64x2(left, right) { + 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 { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + 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, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + let isNegative = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let firstDigit = 0; + let lastDigit = 0; + let exponent = 0; + let i = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + 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; + 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 BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + 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; + } + } + } + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit - firstDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + 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; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + 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)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + 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; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocate(16); + index = 0; + 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; + 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; + 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; + 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 new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + 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; + } + const exponent = biased_exponent - EXPONENT_BIAS; + 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; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + 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++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + 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() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Decimal128("${this.toString()}")`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const eJSON = this.toExtendedJSON(); + return `new Double(${eJSON.$numberDouble})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Int32(${this.valueOf()})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MinKey()'; + } +} + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +const kId = Symbol('id'); +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this[kId] = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 12) { + const bytes = ByteUtils.fromUTF8(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes'); + } + } + else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this[kId]; + } + set id(value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocate(12); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + 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]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); + } + 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 ByteUtils.equals(ByteUtils.fromUTF8(otherId), 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; + } + getTimestamp() { + const timestamp = new Date(); + const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + static createFromTime(time) { + const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new ObjectId("${this.toHexString()}")`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + 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 (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + 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)}`); + } + 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) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + 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 BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + inspect() { + return `new BSONSymbol("${this.value}")`; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + if (low.t < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (low.i < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (low.t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (low.i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(low.i.valueOf(), low.t.valueOf(), true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +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; +function validateUtf8(bytes, start, end) { + 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; +} + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + 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})`); + } + 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"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + const utf8KeysSet = new Set(); + 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]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i)); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === 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 === BSON_DATA_OID) { + const oid = ByteUtils.allocate(12); + oid.set(buffer.subarray(index, index + 12)); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(dataview.getFloat64(index, true)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = dataview.getFloat64(index, true); + index = index + 8; + } + else if (elementType === 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 === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === 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'); + 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 === 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; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, 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 === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); + 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); + if (useBigInt64) { + value = dataview.getBigInt64(0, true); + } + else 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 === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocate(16); + bytes.set(buffer.subarray(index, index + 16), 0); + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + 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 = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = value.toUUID(); + } + } + } + else { + const _buffer = ByteUtils.allocate(binarySize); + 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'); + } + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + 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 === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === 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 === BSON_DATA_TIMESTAMP) { + const i = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + const t = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + value = new Timestamp({ i, t }); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === 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); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + 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); + index = index + stringSize; + const _index = index; + const objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + 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'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); + index = index + stringSize; + const oidBuffer = ByteUtils.allocate(12); + oidBuffer.set(buffer.subarray(index, index + 12), 0); + const oid = new ObjectId(oidBuffer); + index = index + 12; + 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; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +function getValidatedString(buffer, start, end, shouldValidateUtf8) { + const value = ByteUtils.toUTF8(buffer.subarray(start, end)); + 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; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + 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; + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); +const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); +const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + if (type === BSON_DATA_INT) { + NUMBER_SPACE.setInt32(0, value, true); + } + else { + NUMBER_SPACE.setFloat64(0, value, true); + } + const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + buffer.set(bytes, index); + index += bytes.byteLength; + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setBigInt64(0, value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (isUint8Array(value.id)) { + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + return index + 12; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + buffer.set(value, index); + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + 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) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setFloat64(0, value.value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + 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; + buffer[index++] = value.sub_type; + 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; + } + buffer.set(data, index); + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $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, true, path); + const size = endIndex - startIndex; + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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 (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (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 (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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 === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +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 +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + 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 === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof 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); + else if (typeof d === 'bigint') + date.setTime(Number(d)); + else + throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof 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; + 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; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + 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 BSONError('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(), 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))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + 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) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(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) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(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 (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + 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); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + 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, ejsonOptions); + }); +} +function stringify(value, 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; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, 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; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocate(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, 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; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + 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); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ + __proto__: null, + Code: Code, + BSONSymbol: BSONSymbol, + DBRef: DBRef, + Binary: Binary, + ObjectId: ObjectId, + UUID: UUID, + Long: Long, + Timestamp: Timestamp, + Double: Double, + Int32: Int32, + MinKey: MinKey, + MaxKey: MaxKey, + BSONRegExp: BSONRegExp, + Decimal128: Decimal128, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONValue: BSONValue, + BSONError: BSONError, + BSONVersionError: BSONVersionError, + BSONRuntimeError: BSONRuntimeError, + BSONType: BSONType, + EJSON: EJSON +}); + +export { bson as BSON, BSONError, BSONRegExp, BSONRuntimeError, BSONSymbol, BSONType, BSONValue, BSONVersionError, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, MaxKey, MinKey, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize }; +//# sourceMappingURL=bson.mjs.map diff --git a/1_ActivityWatchProducer/node_modules/bson/lib/bson.mjs.map b/1_ActivityWatchProducer/node_modules/bson/lib/bson.mjs.map new file mode 100644 index 00000000..9b7c10a6 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/lib/bson.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.mjs","sources":["../src/constants.ts","../src/error.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/uuid_utils.ts","../src/parser/utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":"AACO,MAAM,kBAAkB,GAAG,CAAU,CAAC;AAGtC,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC,MAAM,cAAc,GAAG,CAAC,UAAU,CAAC;AAEnC,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAE3C,MAAM,cAAc,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAMxC,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAMnC,MAAM,UAAU,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAGpC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,eAAe,GAAG,CAAC,CAAC;AAG1B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAG9B,MAAM,aAAa,GAAG,CAAC,CAAC;AAGxB,MAAM,iBAAiB,GAAG,CAAC,CAAC;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node_modules/bson/package.json b/1_ActivityWatchProducer/node_modules/bson/package.json new file mode 100644 index 00000000..233c5fa6 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/package.json @@ -0,0 +1,115 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "files": [ + "lib", + "src", + "bson.d.ts", + "etc/prepare.js" + ], + "types": "bson.d.ts", + "version": "5.0.1", + "author": { + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" + }, + "license": "Apache-2.0", + "contributors": [], + "repository": "mongodb/js-bson", + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" + }, + "devDependencies": { + "@istanbuljs/nyc-config-typescript": "^1.0.2", + "@microsoft/api-extractor": "^7.33.7", + "@rollup/plugin-node-resolve": "^15.0.1", + "@rollup/plugin-typescript": "^10.0.1", + "@types/chai": "^4.3.4", + "@types/mocha": "^10.0.1", + "@types/node": "^18.11.12", + "@types/sinon": "^10.0.13", + "@types/sinon-chai": "^3.2.9", + "@typescript-eslint/eslint-plugin": "^5.46.0", + "@typescript-eslint/parser": "^5.46.0", + "benchmark": "^2.1.4", + "chai": "^4.3.7", + "chalk": "^5.1.2", + "eslint": "^8.29.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-no-bigint-usage": "file:./etc/eslint/no-bigint-usage", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-tsdoc": "^0.2.17", + "magic-string": "^0.27.0", + "mocha": "10.1.0", + "node-fetch": "^3.2.10", + "nyc": "^15.1.0", + "prettier": "^2.8.1", + "rimraf": "^3.0.2", + "rollup": "^3.7.1", + "sinon": "^15.0.0", + "sinon-chai": "^3.7.0", + "source-map-support": "^0.5.21", + "standard-version": "^9.5.0", + "ts-node": "^10.9.1", + "tsd": "^0.25.0", + "typescript": "^4.9.4", + "typescript-cached-transpile": "0.0.6", + "uuid": "^9.0.0", + "v8-profiler-next": "^1.9.0" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + }, + "config": { + "native": false + }, + "main": "./lib/bson.cjs", + "module": "./lib/bson.mjs", + "exports": { + "import": { + "types": "./bson.d.ts", + "default": "./lib/bson.mjs" + }, + "require": { + "types": "./bson.d.ts", + "default": "./lib/bson.cjs" + }, + "react-native": "./lib/bson.cjs", + "browser": "./lib/bson.mjs" + }, + "compass:exports": { + "import": "./lib/bson.cjs", + "require": "./lib/bson.cjs" + }, + "engines": { + "node": ">=14.20.1" + }, + "scripts": { + "pretest": "npm run build", + "test": "npm run check:node && npm run check:web && npm run check:web-no-bigint", + "check:node": "WEB=false mocha test/node", + "check:tsd": "npm run build:dts && tsd", + "check:web": "WEB=true mocha test/node", + "check:web-no-bigint": "WEB=true NO_BIGINT=true mocha test/node", + "build:ts": "node ./node_modules/typescript/bin/tsc", + "build:dts": "npm run build:ts && api-extractor run --typescript-compiler-folder node_modules/typescript --local && rimraf 'lib/**/*.d.ts*' lib/parser lib/utils", + "build:bundle": "rollup -c rollup.config.mjs", + "build": "npm run build:dts && npm run build:bundle", + "check:lint": "eslint -v && eslint --ext '.js,.ts' --max-warnings=0 src test && npm run build:dts && npm run check:tsd", + "format": "eslint --ext '.js,.ts' src test --fix", + "check:coverage": "nyc --check-coverage npm run check:node", + "prepare": "node etc/prepare.js", + "release": "standard-version -i HISTORY.md" + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/binary.ts b/1_ActivityWatchProducer/node_modules/bson/src/binary.ts new file mode 100644 index 00000000..f95de920 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/binary.ts @@ -0,0 +1,485 @@ +import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils'; +import { isUint8Array } from './parser/utils'; +import type { EJSONOptions } from './extended_json'; +import { BSONError } from './error'; +import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants'; +import { ByteUtils } from './utils/byte_utils'; +import { BSONValue } from './bson_value'; + +/** @public */ +export type BinarySequence = Uint8Array | 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 extends BSONValue { + get _bsontype(): 'Binary' { + return '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!: Uint8Array; + 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) { + super(); + if ( + !(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer) + ) { + throw new BSONError( + '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 = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } else { + if (typeof buffer === 'string') { + // string + this.buffer = ByteUtils.fromISO88591(buffer); + } else if (Array.isArray(buffer)) { + // number[] + this.buffer = ByteUtils.fromNumberArray(buffer); + } else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ByteUtils.toLocalBufferType(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 | 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 BSONError('only accepts single character String'); + } else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('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 BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + 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.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + + // Assign the new buffer + this.buffer = newSpace; + } + + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } else if (typeof sequence === 'string') { + const bytes = ByteUtils.fromISO88591(sequence); + this.buffer.set(bytes, offset); + 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); + } + // TODO(NODE-4361): remove binary string support, value(true) should be the default / only option here. + return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); + } + + /** the length of the binary sequence */ + length(): number { + return this.position; + } + + toJSON(): string { + return ByteUtils.toBase64(this.buffer); + } + + toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string { + if (encoding === 'hex') return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') return ByteUtils.toUTF8(this.buffer); + return ByteUtils.toUTF8(this.buffer); + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + + 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: Uint8Array | 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 = ByteUtils.fromBase64(doc.$binary); + } else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; + } +} + +/** @public */ +export type UUIDExtended = { + $uuid: string; +}; +const UUID_BYTE_LENGTH = 16; + +/** + * A class representation of the BSON UUID type. + * @public + */ +export class UUID extends Binary { + static cacheHexString: boolean; + + /** 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 | Uint8Array | UUID) { + let bytes: Uint8Array; + let hexStr; + if (input == null) { + bytes = UUID.generate(); + } else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + hexStr = input.__id; + } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } else if (typeof input === 'string') { + bytes = uuidHexStringToBuffer(input); + } else { + throw new BSONError( + '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).' + ); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + this.__id = hexStr; + } + + /** + * The UUID bytes + * @readonly + */ + get id(): Uint8Array { + return this.buffer; + } + + set id(value: Uint8Array) { + this.buffer = value; + + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + + /** + * 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?: 'hex' | 'base64'): string { + if (encoding === 'hex') return ByteUtils.toHex(this.id); + if (encoding === 'base64') return ByteUtils.toBase64(this.id); + return 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 | Uint8Array | UUID): boolean { + if (!otherId) { + return false; + } + + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + + try { + return ByteUtils.equals(new UUID(otherId).id, 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(): Uint8Array { + const bytes = ByteUtils.randomBytes(UUID_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 bytes; + } + + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Uint8Array | 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.byteLength !== UUID_BYTE_LENGTH) { + return false; + } + + return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; + } + + 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()}")`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/bson.ts b/1_ActivityWatchProducer/node_modules/bson/src/bson.ts new file mode 100644 index 00000000..962e69e0 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/bson.ts @@ -0,0 +1,250 @@ +import { Binary, UUID } from './binary'; +import { Code } from './code'; +import { DBRef } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { Int32 } from './int_32'; +import { Long } from './long'; +import { MaxKey } from './max_key'; +import { MinKey } from './min_key'; +import { ObjectId } from './objectid'; +import { internalCalculateObjectSize } from './parser/calculate_size'; +// Parts of the parser +import { internalDeserialize, DeserializeOptions } from './parser/deserializer'; +import { serializeInto, SerializeOptions } from './parser/serializer'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; +import { ByteUtils } from './utils/byte_utils'; +export type { UUIDExtended, BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary'; +export type { CodeExtended } from './code'; +export type { DBRefLike } from './db_ref'; +export type { Decimal128Extended } from './decimal128'; +export type { DoubleExtended } from './double'; +export type { EJSONOptions } from './extended_json'; +export type { Int32Extended } from './int_32'; +export type { LongExtended } from './long'; +export type { MaxKeyExtended } from './max_key'; +export type { MinKeyExtended } from './min_key'; +export type { ObjectIdExtended, ObjectIdLike } from './objectid'; +export type { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp'; +export type { BSONSymbolExtended } from './symbol'; +export type { LongWithoutOverrides, TimestampExtended, TimestampOverrides } from './timestamp'; +export type { LongWithoutOverridesClass } from './timestamp'; +export type { SerializeOptions, DeserializeOptions }; + +export { + Code, + BSONSymbol, + DBRef, + Binary, + ObjectId, + UUID, + Long, + Timestamp, + Double, + Int32, + MinKey, + MaxKey, + BSONRegExp, + Decimal128 +}; +export { BSONValue } from './bson_value'; +export { BSONError, BSONVersionError, BSONRuntimeError } from './error'; +export { BSONType } from './constants'; +export { EJSON } from './extended_json'; + +/** @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 = ByteUtils.allocate(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 = ByteUtils.allocate(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 = {}): Uint8Array { + // 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 = ByteUtils.allocate(minInternalBufferSize); + } + + // Attempt to serialize + const serializationIndex = serializeInto( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + null + ); + + // Create the final buffer + const finishedBuffer = ByteUtils.allocate(serializationIndex); + + // Copy into the finished buffer + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + + // 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: Uint8Array, + 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 = serializeInto( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + null + ); + + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + + // 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: Uint8Array, options: DeserializeOptions = {}): Document { + return internalDeserialize(ByteUtils.toLocalBufferType(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: Uint8Array | ArrayBuffer, + startIndex: number, + numberOfDocuments: number, + documents: Document[], + docStartIndex: number, + options: DeserializeOptions +): number { + const internalOptions = Object.assign( + { allowObjectSmallerThanBufferSize: true, index: 0 }, + options + ); + const bufferData = ByteUtils.toLocalBufferType(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; +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/bson_value.ts b/1_ActivityWatchProducer/node_modules/bson/src/bson_value.ts new file mode 100644 index 00000000..b36266e0 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/bson_value.ts @@ -0,0 +1,18 @@ +import { BSON_MAJOR_VERSION } from './constants'; + +/** @public */ +export abstract class BSONValue { + /** @public */ + public abstract get _bsontype(): string; + + /** @internal */ + get [Symbol.for('@@mdb.bson.version')](): typeof BSON_MAJOR_VERSION { + return BSON_MAJOR_VERSION; + } + + /** @public */ + public abstract inspect(): string; + + /** @internal */ + abstract toExtendedJSON(): unknown; +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/code.ts b/1_ActivityWatchProducer/node_modules/bson/src/code.ts new file mode 100644 index 00000000..48889f56 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/code.ts @@ -0,0 +1,69 @@ +import type { Document } from './bson'; +import { BSONValue } from './bson_value'; + +/** @public */ +export interface CodeExtended { + $code: string; + $scope?: Document; +} + +/** + * A class representation of the BSON Code type. + * @public + * @category BSONType + */ +export class Code extends BSONValue { + get _bsontype(): 'Code' { + return 'Code'; + } + + code: string; + + // a code instance having a null scope is what determines whether + // it is BSONType 0x0D (just code) / 0x0F (code with scope) + scope: Document | null; + + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document | null) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + + toJSON(): { code: string; scope?: Document } { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + + return { code: this.code }; + } + + /** @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 != null ? `, ${JSON.stringify(codeJson.scope)}` : '' + })`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/constants.ts b/1_ActivityWatchProducer/node_modules/bson/src/constants.ts new file mode 100644 index 00000000..50a3d42e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/constants.ts @@ -0,0 +1,141 @@ +/** @internal */ +export const BSON_MAJOR_VERSION = 5 as const; + +/** @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; + +/** @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]; diff --git a/1_ActivityWatchProducer/node_modules/bson/src/db_ref.ts b/1_ActivityWatchProducer/node_modules/bson/src/db_ref.ts new file mode 100644 index 00000000..ebdcb61b --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/db_ref.ts @@ -0,0 +1,127 @@ +import type { Document } from './bson'; +import { BSONValue } from './bson_value'; +import type { EJSONOptions } from './extended_json'; +import type { ObjectId } from './objectid'; + +/** @public */ +export interface DBRefLike { + $ref: string; + $id: ObjectId; + $db?: string; +} + +/** @internal */ +export function isDBRefLike(value: unknown): value is DBRefLike { + return ( + value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + // If '$db' is defined it MUST be a string, otherwise it should be absent + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')) + ); +} + +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +export class DBRef extends BSONValue { + get _bsontype(): 'DBRef' { + return '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) { + super(); + // 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}"` : '' + })`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/decimal128.ts b/1_ActivityWatchProducer/node_modules/bson/src/decimal128.ts new file mode 100644 index 00000000..55543a76 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/decimal128.ts @@ -0,0 +1,777 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import { Long } from './long'; +import { isUint8Array } from './parser/utils'; +import { ByteUtils } from './utils/byte_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 = ByteUtils.fromNumberArray( + [ + 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 = ByteUtils.fromNumberArray( + [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse() +); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray( + [ + 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 BSONError(`"${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 extends BSONValue { + get _bsontype(): 'Decimal128' { + return 'Decimal128'; + } + + readonly bytes!: Uint8Array; + + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Uint8Array | string) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } else { + throw new BSONError('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 BSONError('' + 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 BSONError('' + 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(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } else if (representation[index] === 'N') { + return new Decimal128(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 BSONError('' + 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(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(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(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 = ByteUtils.allocate(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()}")`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/double.ts b/1_ActivityWatchProducer/node_modules/bson/src/double.ts new file mode 100644 index 00000000..45815360 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/double.ts @@ -0,0 +1,83 @@ +import { BSONValue } from './bson_value'; +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 extends BSONValue { + get _bsontype(): 'Double' { + return 'Double'; + } + + value!: number; + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + constructor(value: number) { + super(); + 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; + } + + if (Object.is(Math.sign(this.value), -0)) { + // 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 + return { $numberDouble: '-0.0' }; + } + + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + + /** @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})`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/error.ts b/1_ActivityWatchProducer/node_modules/bson/src/error.ts new file mode 100644 index 00000000..f98f0fb7 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/error.ts @@ -0,0 +1,85 @@ +import { BSON_MAJOR_VERSION } from './constants'; + +/** + * @public + * @category Error + * + * `BSONError` objects are thrown when BSON ecounters an error. + * + * This is the parent class for all the other errors thrown by this library. + */ +export class BSONError extends Error { + /** + * @internal + * The underlying algorithm for isBSONError may change to improve how strict it is + * about determining if an input is a BSONError. But it must remain backwards compatible + * with previous minors & patches of the current major version. + */ + protected get bsonError(): true { + return true; + } + + override get name(): string { + return 'BSONError'; + } + + constructor(message: string) { + super(message); + } + + /** + * @public + * + * All errors thrown from the BSON library inherit from `BSONError`. + * This method can assist with determining if an error originates from the BSON library + * even if it does not pass an `instanceof` check against this class' constructor. + * + * @param value - any javascript value that needs type checking + */ + public static isBSONError(value: unknown): value is BSONError { + return ( + value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + // Do not access the following properties, just check existence + 'name' in value && + 'message' in value && + 'stack' in value + ); + } +} + +/** + * @public + * @category Error + */ +export class BSONVersionError extends BSONError { + get name(): 'BSONVersionError' { + return 'BSONVersionError'; + } + + constructor() { + super( + `Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later` + ); + } +} + +/** + * @public + * @category Error + * + * An error generated when BSON functions encounter an unexpected input + * or reaches an unexpected/invalid internal state + * + */ +export class BSONRuntimeError extends BSONError { + get name(): 'BSONRuntimeError' { + return 'BSONRuntimeError'; + } + + constructor(message: string) { + super(message); + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/extended_json.ts b/1_ActivityWatchProducer/node_modules/bson/src/extended_json.ts new file mode 100644 index 00000000..fd1f0a30 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/extended_json.ts @@ -0,0 +1,495 @@ +import { Binary } from './binary'; +import type { Document } from './bson'; +import { Code } from './code'; +import { + BSON_INT32_MAX, + BSON_INT32_MIN, + BSON_INT64_MAX, + BSON_INT64_MIN, + BSON_MAJOR_VERSION +} from './constants'; +import { DBRef, isDBRefLike } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { BSONError, BSONRuntimeError, BSONVersionError } 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, isRegExp } from './parser/utils'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; + +/** @public */ +export type EJSONOptions = { + /** 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; + /** Enable native bigint support */ + useBigInt64?: boolean; +}; + +/** @internal */ +type BSONType = + | Binary + | Code + | DBRef + | Decimal128 + | Double + | Int32 + | Long + | MaxKey + | MinKey + | ObjectId + | BSONRegExp + | BSONSymbol + | Timestamp; + +function isBSONType(value: unknown): value is BSONType { + return ( + value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string' + ); +} + +// 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: EJSONOptions = {}) { + if (typeof value === 'number') { + // TODO(NODE-4377): EJSON js number handling diverges from BSON + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + + if (options.relaxed || options.legacy) { + return value; + } + + if (Number.isInteger(value) && !Object.is(value, -0)) { + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + // eslint-disable-next-line no-restricted-globals -- This is allowed here as useBigInt64=true + return BigInt(value); + } + 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 === 'bigint') date.setTime(Number(d)); + else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof 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); + else if (typeof d === 'bigint') date.setTime(Number(d)); + else throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof 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 = EJSONOptions & { + 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 BSONError( + '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))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + // TODO(NODE-4377): EJSON js number handling diverges from BSON + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + + if (typeof value === 'bigint') { + /* eslint-disable no-restricted-globals -- This is allowed as we are accepting a bigint as input */ + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + /* eslint-enable */ + } + + 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), + BSONRegExp: (o: BSONRegExp) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (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 of Object.keys(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 ( + doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } 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 BSONError('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); + } +} + +/** + * 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)); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function parse(text: string, options?: EJSONOptions): any { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + 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, ejsonOptions); + }); +} + +/** + * 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( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value: any, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSONOptions, + space?: string | number, + options?: EJSONOptions +): 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 + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function EJSONserialize(value: any, options?: EJSONOptions): 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 + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function EJSONdeserialize(ejson: Document, options?: EJSONOptions): any { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} + +/** @public */ +const EJSON: { + parse: typeof parse; + stringify: typeof stringify; + serialize: typeof EJSONserialize; + deserialize: typeof EJSONdeserialize; +} = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); +export { EJSON }; diff --git a/1_ActivityWatchProducer/node_modules/bson/src/index.ts b/1_ActivityWatchProducer/node_modules/bson/src/index.ts new file mode 100644 index 00000000..5ef41575 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/index.ts @@ -0,0 +1,19 @@ +import * as BSON from './bson'; + +// Export all named properties from BSON to support +// import { ObjectId, serialize } from 'bson'; +// const { ObjectId, serialize } = require('bson'); +export * from './bson'; + +// Export BSON as a namespace to support: +// import { BSON } from 'bson'; +// const { BSON } = require('bson'); +export { BSON }; + +// BSON does **NOT** have a default export + +// The following will crash in es module environments +// import BSON from 'bson'; + +// The following will work as expected, BSON as a namespace of all the APIs (BSON.ObjectId, BSON.serialize) +// const BSON = require('bson'); diff --git a/1_ActivityWatchProducer/node_modules/bson/src/int_32.ts b/1_ActivityWatchProducer/node_modules/bson/src/int_32.ts new file mode 100644 index 00000000..c74f3c82 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/int_32.ts @@ -0,0 +1,70 @@ +import { BSONValue } from './bson_value'; +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 extends BSONValue { + get _bsontype(): 'Int32' { + return 'Int32'; + } + + value!: number; + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + constructor(value: number | string) { + super(); + 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()})`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/long.ts b/1_ActivityWatchProducer/node_modules/bson/src/long.ts new file mode 100644 index 00000000..752c18fe --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/long.ts @@ -0,0 +1,1067 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import type { EJSONOptions } from './extended_json'; +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 } = {}; + +const MAX_INT64_STRING_LENGTH = 20; + +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; + +/** @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 extends BSONValue { + get _bsontype(): 'Long' { + return 'Long'; + } + + /** An indicator used to reliably determine if an object is a Long or not. */ + get __isLong__(): boolean { + return 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) { + super(); + 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; + } + } + + 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 new BSONError('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 new BSONError('radix'); + + let p; + if ((p = str.indexOf('-')) > 0) throw new BSONError('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 ( + value != null && + typeof value === 'object' && + '__isLong__' in 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 new BSONError('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 { + // eslint-disable-next-line no-restricted-globals -- This is allowed here as it is explicitly requesting a 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 new BSONError('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 | bigint { + const { useBigInt64 = false, relaxed = true } = { ...options }; + + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + + if (useBigInt64) { + /* eslint-disable no-restricted-globals -- Can use BigInt here as useBigInt64=true */ + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + /* eslint-enable */ + } + + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/max_key.ts b/1_ActivityWatchProducer/node_modules/bson/src/max_key.ts new file mode 100644 index 00000000..2894f58b --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/max_key.ts @@ -0,0 +1,36 @@ +import { BSONValue } from './bson_value'; + +/** @public */ +export interface MaxKeyExtended { + $maxKey: 1; +} + +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +export class MaxKey extends BSONValue { + get _bsontype(): 'MaxKey' { + return '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()'; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/min_key.ts b/1_ActivityWatchProducer/node_modules/bson/src/min_key.ts new file mode 100644 index 00000000..f72cf26b --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/min_key.ts @@ -0,0 +1,36 @@ +import { BSONValue } from './bson_value'; + +/** @public */ +export interface MinKeyExtended { + $minKey: 1; +} + +/** + * A class representation of the BSON MinKey type. + * @public + * @category BSONType + */ +export class MinKey extends BSONValue { + get _bsontype(): 'MinKey' { + return '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()'; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/objectid.ts b/1_ActivityWatchProducer/node_modules/bson/src/objectid.ts new file mode 100644 index 00000000..a0358208 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/objectid.ts @@ -0,0 +1,317 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import { isUint8Array } from './parser/utils'; +import { BSONDataView, ByteUtils } from './utils/byte_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 | Uint8Array; + __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 extends BSONValue { + get _bsontype(): 'ObjectId' { + return 'ObjectId'; + } + + /** @internal */ + private static index = Math.floor(Math.random() * 0xffffff); + + static cacheHexString: boolean; + + /** ObjectId Bytes @internal */ + private [kId]!: Uint8Array; + /** 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 | Uint8Array) { + super(); + // 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 BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } 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] = ByteUtils.toLocalBufferType(workingId); + } else if (typeof workingId === 'string') { + if (workingId.length === 12) { + // TODO(NODE-4361): Remove string of length 12 support + const bytes = ByteUtils.fromUTF8(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } else { + throw new BSONError('Argument passed in must be a string of 12 bytes'); + } + } else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = ByteUtils.fromHex(workingId); + } else { + throw new BSONError( + 'Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer' + ); + } + } else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + + /** + * The ObjectId bytes + * @readonly + */ + get id(): Uint8Array { + return this[kId]; + } + + set id(value: Uint8Array) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + + /** Returns the ObjectId id as a 24 character hex string representation */ + toHexString(): string { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + + const hexString = ByteUtils.toHex(this.id); + + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + + return hexString; + } + + /** + * Update the ObjectId index + * @internal + */ + private 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): Uint8Array { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocate(12); + + // 4-byte timestamp + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.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, unless encoding is provided. + * @param encoding - hex or base64 + */ + toString(encoding?: 'hex' | 'base64'): string { + // Is the id a buffer then use the buffer toString method to return the format + if (encoding === 'base64') return ByteUtils.toBase64(this.id); + if (encoding === 'hex') return this.toHexString(); + 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] && ByteUtils.equals(this[kId], otherId[kId]); + } + + if ( + typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id) + ) { + return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); + } + + 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 ByteUtils.equals(ByteUtils.fromUTF8(otherId), 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 = BSONDataView.fromUint8Array(this.id).getUint32(0, false); + 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 = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + // 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 BSONError( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + return new ObjectId(ByteUtils.fromHex(hexString)); + } + + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + static isValid(id: string | number | ObjectId | ObjectIdLike | 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()}")`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/parser/calculate_size.ts b/1_ActivityWatchProducer/node_modules/bson/src/parser/calculate_size.ts new file mode 100644 index 00000000..fd1e4a02 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/parser/calculate_size.ts @@ -0,0 +1,211 @@ +import { Binary } from '../binary'; +import type { Document } from '../bson'; +import { BSONVersionError } from '../error'; +import * as constants from '../constants'; +import { ByteUtils } from '../utils/byte_utils'; +import { isAnyArrayBuffer, isDate, isRegExp } from './utils'; + +export function internalCalculateObjectSize( + 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 of Object.keys(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 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 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 ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if ( + value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } else if ( + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value) + ) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength + ); + } else if ( + value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp' + ) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 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 ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 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 ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1) + ); + } + } else if (value._bsontype === 'Symbol') { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 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 ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if (value instanceof RegExp || isRegExp(value)) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value._bsontype === 'BSONRegExp') { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1 + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + if (serializeFunctions) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1 + ); + } + } + + return 0; +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/parser/deserializer.ts b/1_ActivityWatchProducer/node_modules/bson/src/parser/deserializer.ts new file mode 100644 index 00000000..50d7a8d8 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/parser/deserializer.ts @@ -0,0 +1,726 @@ +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 { BSONDataView, ByteUtils } from '../utils/byte_utils'; +import { validateUtf8 } from '../validate_utf8'; + +/** @public */ +export interface DeserializeOptions { + /** when deserializing a Long will return as a BigInt. */ + useBigInt64?: 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); + +export function internalDeserialize( + buffer: Uint8Array, + 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 deserialization + return deserializeObject(buffer, index, options, isArray); +} + +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; + +function deserializeObject( + buffer: Uint8Array, + index: number, + options: DeserializeOptions, + isArray = false +) { + 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 ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + + // 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++ : ByteUtils.toUTF8(buffer.subarray(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 = ByteUtils.allocate(12); + oid.set(buffer.subarray(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: DeserializeOptions = options; + + // Stop index + const stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, 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 dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); + + 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); + if (useBigInt64) { + value = dataview.getBigInt64(0, true); + } else if (promoteLongs && promoteValues === true) { + // Promote the long if possible + 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 = ByteUtils.allocate(16); + // Copy the next 16 bytes into the bytes buffer + bytes.set(buffer.subarray(index, index + 16), 0); + // Update index + index = index + 16; + // Assign the new Decimal128 value + value = new Decimal128(bytes); + } 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 = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) { + value = value.toUUID(); + } + } + } else { + const _buffer = ByteUtils.allocate(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 if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) { + value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + } else { + value = new Binary(buffer.slice(index, index + binarySize), 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 = ByteUtils.toUTF8(buffer.subarray(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 = ByteUtils.toUTF8(buffer.subarray(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 = ByteUtils.toUTF8(buffer.subarray(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 = ByteUtils.toUTF8(buffer.subarray(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) { + // We intentionally **do not** use bit shifting here + // Bit shifting in javascript coerces numbers to **signed** int32s + // We need to keep i, and t unsigned + const i = + buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + const t = + buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + + value = new Timestamp({ i, t }); + } 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 + ); + + 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'); + } + + 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 = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + + // Read the oid + const oidBuffer = ByteUtils.allocate(12); + oidBuffer.set(buffer.subarray(index, index + 12), 0); + 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; +} + +function getValidatedString( + buffer: Uint8Array, + start: number, + end: number, + shouldValidateUtf8: boolean +) { + const value = ByteUtils.toUTF8(buffer.subarray(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/1_ActivityWatchProducer/node_modules/bson/src/parser/serializer.ts b/1_ActivityWatchProducer/node_modules/bson/src/parser/serializer.ts new file mode 100644 index 00000000..b59a1b77 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/parser/serializer.ts @@ -0,0 +1,988 @@ +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 { BSONError, BSONVersionError } from '../error'; +import type { Int32 } from '../int_32'; +import { Long } from '../long'; +import type { MinKey } from '../min_key'; +import type { ObjectId } from '../objectid'; +import type { BSONRegExp } from '../regexp'; +import { ByteUtils } from '../utils/byte_utils'; +import { isAnyArrayBuffer, isDate, isMap, isRegExp, isUint8Array } 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: Uint8Array, key: string, value: string, index: number) { + // Encode String type + buffer[index++] = constants.BSON_DATA_STRING; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + // 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 NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); +const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); +const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); + +function serializeNumber(buffer: Uint8Array, key: string, value: number, index: number) { + const isNegativeZero = Object.is(value, -0); + + const type = + !isNegativeZero && + Number.isSafeInteger(value) && + value <= constants.BSON_INT32_MAX && + value >= constants.BSON_INT32_MIN + ? constants.BSON_DATA_INT + : constants.BSON_DATA_NUMBER; + + if (type === constants.BSON_DATA_INT) { + NUMBER_SPACE.setInt32(0, value, true); + } else { + NUMBER_SPACE.setFloat64(0, value, true); + } + + const bytes = + type === constants.BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; + + buffer[index++] = type; + + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + + buffer.set(bytes, index); + index += bytes.byteLength; + + return index; +} + +function serializeBigInt(buffer: Uint8Array, key: string, value: bigint, index: number) { + buffer[index++] = constants.BSON_DATA_LONG; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index += numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setBigInt64(0, value, true); + // Write BigInt value + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; + return index; +} + +function serializeNull(buffer: Uint8Array, key: string, _: unknown, index: number) { + // Set long type + buffer[index++] = constants.BSON_DATA_NULL; + + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeBoolean(buffer: Uint8Array, key: string, value: boolean, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BOOLEAN; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +function serializeDate(buffer: Uint8Array, key: string, value: Date, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_DATE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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: Uint8Array, key: string, value: RegExp, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + // 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: Uint8Array, key: string, value: BSONRegExp, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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 new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + // Write zero + buffer[index++] = 0x00; + // Write the options + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +function serializeMinMax(buffer: Uint8Array, key: string, value: MinKey | MaxKey, index: number) { + // 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 = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeObjectId(buffer: Uint8Array, key: string, value: ObjectId, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_OID; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (isUint8Array(value.id)) { + buffer.set(value.id.subarray(0, 12), index); + } else { + throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Adjust index + return index + 12; +} + +function serializeBuffer(buffer: Uint8Array, key: string, value: Uint8Array, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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(value, index); + // Adjust the index + index = index + size; + return index; +} + +function serializeObject( + buffer: Uint8Array, + key: string, + value: Document, + index: number, + checkKeys: boolean, + depth: number, + serializeFunctions: boolean, + ignoreUndefined: boolean, + path: Set +) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + + path.add(value); + + // Write the type + buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + + path.delete(value); + + return endIndex; +} + +function serializeDecimal128(buffer: Uint8Array, key: string, value: Decimal128, index: number) { + buffer[index++] = constants.BSON_DATA_DECIMAL128; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} + +function serializeLong(buffer: Uint8Array, key: string, value: Long, index: number) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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: Uint8Array, key: string, value: Int32 | number, index: number) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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: Uint8Array, key: string, value: Double, index: number) { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write float + NUMBER_SPACE.setFloat64(0, value.value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + + // Adjust index + index = index + 8; + return index; +} + +function serializeFunction(buffer: Uint8Array, key: string, value: Function, index: number) { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = value.toString(); + + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 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: Uint8Array, + key: string, + value: Code, + index: number, + checkKeys = false, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + path: Set +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + let startIndex = index; + + // Serialize the function + // Get the function string + const functionString = value.code; + // Index adjustment + index = index + 4; + // Write string into buffer + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 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, + path + ); + 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 = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = value.code.toString(); + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 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: Uint8Array, key: string, value: Binary, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + const data = value.buffer; + // 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: Uint8Array, key: string, value: BSONSymbol, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_SYMBOL; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 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: Uint8Array, + key: string, + value: DBRef, + index: number, + depth: number, + serializeFunctions: boolean, + path: Set +) { + // Write the type + buffer[index++] = constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // 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, + true, + path + ); + + // 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: Uint8Array, + object: Document, + checkKeys: boolean, + startingIndex: number, + depth: number, + serializeFunctions: boolean, + ignoreUndefined: boolean, + path: Set | null +): number { + if (path == null) { + // We are at the root input + if (object == null) { + // ONLY the root should turn into an empty document + // BSON Empty document has a size of 5 (LE) + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + // All documents end with null terminator + buffer[4] = 0x00; + return 5; + } + + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } else if ( + isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object) + ) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + + path = new Set(); + } + + // Push the object to the path + path.add(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); + } else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(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 (typeof value === 'object' && value._bsontype == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (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 (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } 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 BSONError(`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]; + let value = entry.value[1]; + + 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 new BSONError('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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 === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(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, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } 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, + path + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } 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 BSONError(`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 BSONError('toBSON function did not return an object'); + } + } + + // Iterate over all the keys + for (const key of Object.keys(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 new BSONError('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(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, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } 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, + path + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + + // Remove the path + path.delete(object); + + // 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/1_ActivityWatchProducer/node_modules/bson/src/parser/utils.ts b/1_ActivityWatchProducer/node_modules/bson/src/parser/utils.ts new file mode 100644 index 00000000..1ed11701 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/parser/utils.ts @@ -0,0 +1,29 @@ +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]'; +} + +export function isDate(d: unknown): d is Date { + return Object.prototype.toString.call(d) === '[object Date]'; +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/regexp.ts b/1_ActivityWatchProducer/node_modules/bson/src/regexp.ts new file mode 100644 index 00000000..0e7b279d --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/regexp.ts @@ -0,0 +1,114 @@ +import { BSONValue } from './bson_value'; +import { BSONError } 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 extends BSONValue { + get _bsontype(): 'BSONRegExp' { + return 'BSONRegExp'; + } + + pattern!: string; + options!: string; + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + constructor(pattern: string, options?: string) { + super(); + 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 BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/symbol.ts b/1_ActivityWatchProducer/node_modules/bson/src/symbol.ts new file mode 100644 index 00000000..081a52ad --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/symbol.ts @@ -0,0 +1,58 @@ +import { BSONValue } from './bson_value'; + +/** @public */ +export interface BSONSymbolExtended { + $symbol: string; +} + +/** + * A class representation of the BSON Symbol type. + * @public + * @category BSONType + */ +export class BSONSymbol extends BSONValue { + get _bsontype(): 'BSONSymbol' { + return 'BSONSymbol'; + } + + value!: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string) { + super(); + this.value = value; + } + + /** Access the wrapped string value. */ + valueOf(): string { + return this.value; + } + + toString(): string { + return this.value; + } + + 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(); + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/timestamp.ts b/1_ActivityWatchProducer/node_modules/bson/src/timestamp.ts new file mode 100644 index 00000000..78d7fc4c --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/timestamp.ts @@ -0,0 +1,150 @@ +import { BSONError } from './error'; +import type { Int32 } from './int_32'; +import { Long } from './long'; + +/** @public */ +export type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; +/** @public */ +export type LongWithoutOverrides = new ( + low: unknown, + high?: number | boolean, + 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 { + get _bsontype(): 'Timestamp' { + return 'Timestamp'; + } + + static readonly MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + + /** + * @param int - A 64-bit bigint representing the Timestamp. + */ + constructor(int: bigint); + /** + * @param long - 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 }); + constructor(low?: bigint | Long | { t: number | Int32; i: number | Int32 }) { + if (low == null) { + super(0, 0, true); + } else if (typeof low === 'bigint') { + super(low, true); + } else if (Long.isLong(low)) { + super(low.low, low.high, true); + } else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + if (low.t < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (low.i < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (low.t > 0xffff_ffff) { + throw new BSONError( + 'Timestamp constructed from { t, i } must provide t equal or less than uint32 max' + ); + } + if (low.i > 0xffff_ffff) { + throw new BSONError( + 'Timestamp constructed from { t, i } must provide i equal or less than uint32 max' + ); + } + + super(low.i.valueOf(), low.t.valueOf(), true); + } else { + throw new BSONError( + 'A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }' + ); + } + } + + 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({ i: lowBits, t: 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 { + // The Long check is necessary because extended JSON has different behavior given the size of the input number + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() // Need to fetch the least significant 32 bits + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() // Need to fetch the least significant 32 bits + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + + /** @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/1_ActivityWatchProducer/node_modules/bson/src/utils/byte_utils.ts b/1_ActivityWatchProducer/node_modules/bson/src/utils/byte_utils.ts new file mode 100644 index 00000000..7c44b38a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/utils/byte_utils.ts @@ -0,0 +1,61 @@ +import { nodeJsByteUtils } from './node_byte_utils'; +import { webByteUtils } from './web_byte_utils'; + +/** @internal */ +export type ByteUtils = { + /** Transforms the input to an instance of Buffer if running on node, otherwise Uint8Array */ + toLocalBufferType(buffer: Uint8Array | ArrayBufferView | ArrayBuffer): Uint8Array; + /** Create empty space of size */ + allocate: (size: number) => Uint8Array; + /** Check if two Uint8Arrays are deep equal */ + equals: (a: Uint8Array, b: Uint8Array) => boolean; + /** Check if two Uint8Arrays are deep equal */ + fromNumberArray: (array: number[]) => Uint8Array; + /** Create a Uint8Array from a base64 string */ + fromBase64: (base64: string) => Uint8Array; + /** Create a base64 string from bytes */ + toBase64: (buffer: Uint8Array) => string; + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591: (codePoints: string) => Uint8Array; + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591: (buffer: Uint8Array) => string; + /** Create a Uint8Array from a hex string */ + fromHex: (hex: string) => Uint8Array; + /** Create a hex string from bytes */ + toHex: (buffer: Uint8Array) => string; + /** Create a Uint8Array containing utf8 code units from a string */ + fromUTF8: (text: string) => Uint8Array; + /** Create a string from utf8 code units */ + toUTF8: (buffer: Uint8Array) => string; + /** Get the utf8 code unit count from a string if it were to be transformed to utf8 */ + utf8ByteLength: (input: string) => number; + /** Encode UTF8 bytes generated from `source` string into `destination` at byteOffset. Returns the number of bytes encoded. */ + encodeUTF8Into(destination: Uint8Array, source: string, byteOffset: number): number; + /** Generate a Uint8Array filled with random bytes with byteLength */ + randomBytes(byteLength: number): Uint8Array; +}; + +declare const Buffer: { new (): unknown; prototype?: { _isBuffer?: boolean } } | undefined; + +/** + * Check that a global Buffer exists that is a function and + * does not have a '_isBuffer' property defined on the prototype + * (this is to prevent using the npm buffer) + */ +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; + +/** + * This is the only ByteUtils that should be used across the rest of the BSON library. + * + * The type annotation is important here, it asserts that each of the platform specific + * utils implementations are compatible with the common one. + * + * @internal + */ +export const ByteUtils: ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; + +export class BSONDataView extends DataView { + static fromUint8Array(input: Uint8Array) { + return new DataView(input.buffer, input.byteOffset, input.byteLength); + } +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/utils/node_byte_utils.ts b/1_ActivityWatchProducer/node_modules/bson/src/utils/node_byte_utils.ts new file mode 100644 index 00000000..468acf89 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/utils/node_byte_utils.ts @@ -0,0 +1,141 @@ +import { BSONError } from '../error'; + +type NodeJsEncoding = 'base64' | 'hex' | 'utf8' | 'binary'; +type NodeJsBuffer = ArrayBufferView & + Uint8Array & { + write(string: string, offset: number, length: undefined, encoding: 'utf8'): number; + copy(target: Uint8Array, targetStart: number, sourceStart: number, sourceEnd: number): number; + toString: (this: Uint8Array, encoding: NodeJsEncoding) => string; + equals: (this: Uint8Array, other: Uint8Array) => boolean; + }; +type NodeJsBufferConstructor = Omit & { + alloc: (size: number) => NodeJsBuffer; + from(array: number[]): NodeJsBuffer; + from(array: Uint8Array): NodeJsBuffer; + from(array: ArrayBuffer): NodeJsBuffer; + from(array: ArrayBuffer, byteOffset: number, byteLength: number): NodeJsBuffer; + from(base64: string, encoding: NodeJsEncoding): NodeJsBuffer; + byteLength(input: string, encoding: 'utf8'): number; + isBuffer(value: unknown): value is NodeJsBuffer; +}; + +// This can be nullish, but we gate the nodejs functions on being exported whether or not this exists +// Node.js global +declare const Buffer: NodeJsBufferConstructor; +declare const require: (mod: 'crypto') => { randomBytes: (byteLength: number) => Uint8Array }; + +/** @internal */ +export function nodejsMathRandomBytes(byteLength: number) { + return nodeJsByteUtils.fromNumberArray( + Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)) + ); +} + +/** + * @internal + * WARNING: REQUIRE WILL BE REWRITTEN + * + * This code is carefully used by require_rewriter.mjs any modifications must be reflected in the plugin. + * + * @remarks + * "crypto" is the only dependency BSON needs. This presents a problem for creating a bundle of the BSON library + * in an es module format that can be used both on the browser and in Node.js. In Node.js when BSON is imported as + * an es module, there will be no global require function defined, making the code below fallback to the much less desireable math.random bytes. + * In order to make our es module bundle work as expected on Node.js we need to change this `require()` to a dynamic import, and the dynamic + * import must be top-level awaited since es modules are async. So we rely on a custom rollup plugin to seek out the following lines of code + * and replace `require` with `await import` and the IIFE line (`nodejsRandomBytes = (() => { ... })()`) with `nodejsRandomBytes = await (async () => { ... })()` + * when generating an es module bundle. + */ +const nodejsRandomBytes: (byteLength: number) => Uint8Array = (() => { + try { + return require('crypto').randomBytes; + } catch { + return nodejsMathRandomBytes; + } +})(); + +/** @internal */ +export const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer: Uint8Array | NodeJsBuffer | ArrayBuffer): NodeJsBuffer { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from( + potentialBuffer.buffer, + potentialBuffer.byteOffset, + potentialBuffer.byteLength + ); + } + + const stringTag = + potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if ( + stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]' + ) { + return Buffer.from(potentialBuffer); + } + + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + + allocate(size: number): NodeJsBuffer { + return Buffer.alloc(size); + }, + + equals(a: Uint8Array, b: Uint8Array): boolean { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + + fromNumberArray(array: number[]): NodeJsBuffer { + return Buffer.from(array); + }, + + fromBase64(base64: string): NodeJsBuffer { + return Buffer.from(base64, 'base64'); + }, + + toBase64(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591(codePoints: string): NodeJsBuffer { + return Buffer.from(codePoints, 'binary'); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + + fromHex(hex: string): NodeJsBuffer { + return Buffer.from(hex, 'hex'); + }, + + toHex(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + + fromUTF8(text: string): NodeJsBuffer { + return Buffer.from(text, 'utf8'); + }, + + toUTF8(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); + }, + + utf8ByteLength(input: string): number { + return Buffer.byteLength(input, 'utf8'); + }, + + encodeUTF8Into(buffer: Uint8Array, source: string, byteOffset: number): number { + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + + randomBytes: nodejsRandomBytes +}; diff --git a/1_ActivityWatchProducer/node_modules/bson/src/utils/web_byte_utils.ts b/1_ActivityWatchProducer/node_modules/bson/src/utils/web_byte_utils.ts new file mode 100644 index 00000000..6e45f91e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/utils/web_byte_utils.ts @@ -0,0 +1,190 @@ +import { BSONError } from '../error'; + +type TextDecoder = { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Uint8Array): string; +}; +type TextDecoderConstructor = { + new (label: 'utf8', options: { fatal: boolean; ignoreBOM?: boolean }): TextDecoder; +}; + +type TextEncoder = { + readonly encoding: string; + encode(input?: string): Uint8Array; +}; +type TextEncoderConstructor = { + new (): TextEncoder; +}; + +// Web global +declare const TextDecoder: TextDecoderConstructor; +declare const TextEncoder: TextEncoderConstructor; +declare const atob: (base64: string) => string; +declare const btoa: (binary: string) => string; + +type ArrayBufferViewWithTag = ArrayBufferView & { + [Symbol.toStringTag]?: string; +}; + +function isReactNative() { + const { navigator } = globalThis as { navigator?: { product?: string } }; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} + +/** @internal */ +export function webMathRandomBytes(byteLength: number) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray( + Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)) + ); +} + +/** @internal */ +const webRandomBytes: (byteLength: number) => Uint8Array = (() => { + const { crypto } = globalThis as { + crypto?: { getRandomValues?: (space: Uint8Array) => Uint8Array }; + }; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength: number) => { + // @ts-expect-error: crypto.getRandomValues cannot actually be null here + // You cannot separate getRandomValues from crypto (need to have this === crypto) + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } else { + if (isReactNative()) { + const { console } = globalThis as { console?: { warn?: (message: string) => void } }; + console?.warn?.( + 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + ); + } + return webMathRandomBytes; + } +})(); + +const HEX_DIGIT = /(\d|[a-f])/i; + +/** @internal */ +export const webByteUtils = { + toLocalBufferType( + potentialUint8array: Uint8Array | ArrayBufferViewWithTag | ArrayBuffer + ): Uint8Array { + const stringTag = + potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + + if (stringTag === 'Uint8Array') { + return potentialUint8array as Uint8Array; + } + + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array( + potentialUint8array.buffer.slice( + potentialUint8array.byteOffset, + potentialUint8array.byteOffset + potentialUint8array.byteLength + ) + ); + } + + if ( + stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]' + ) { + return new Uint8Array(potentialUint8array); + } + + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + + allocate(size: number): Uint8Array { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + + equals(a: Uint8Array, b: Uint8Array): boolean { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + + fromNumberArray(array: number[]): Uint8Array { + return Uint8Array.from(array); + }, + + fromBase64(base64: string): Uint8Array { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + + toBase64(uint8array: Uint8Array): string { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591(codePoints: string): Uint8Array { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591(uint8array: Uint8Array): string { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + + fromHex(hex: string): Uint8Array { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + + return Uint8Array.from(buffer); + }, + + toHex(uint8array: Uint8Array): string { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + + fromUTF8(text: string): Uint8Array { + return new TextEncoder().encode(text); + }, + + toUTF8(uint8array: Uint8Array): string { + return new TextDecoder('utf8', { fatal: false }).decode(uint8array); + }, + + utf8ByteLength(input: string): number { + return webByteUtils.fromUTF8(input).byteLength; + }, + + encodeUTF8Into(buffer: Uint8Array, source: string, byteOffset: number): number { + const bytes = webByteUtils.fromUTF8(source); + buffer.set(bytes, byteOffset); + return bytes.byteLength; + }, + + randomBytes: webRandomBytes +}; diff --git a/1_ActivityWatchProducer/node_modules/bson/src/uuid_utils.ts b/1_ActivityWatchProducer/node_modules/bson/src/uuid_utils.ts new file mode 100644 index 00000000..37f0dcfd --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/bson/src/uuid_utils.ts @@ -0,0 +1,33 @@ +import { BSONError } from './error'; +import { ByteUtils } from './utils/byte_utils'; + +// 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): Uint8Array => { + if (!uuidValidateString(hexString)) { + throw new BSONError( + '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 ByteUtils.fromHex(sanitizedHexString); +}; + +export function bufferToUuidHexString(buffer: Uint8Array, includeDashes = true): string { + if (includeDashes) { + return [ + ByteUtils.toHex(buffer.subarray(0, 4)), + ByteUtils.toHex(buffer.subarray(4, 6)), + ByteUtils.toHex(buffer.subarray(6, 8)), + ByteUtils.toHex(buffer.subarray(8, 10)), + ByteUtils.toHex(buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(buffer); +} diff --git a/1_ActivityWatchProducer/node_modules/bson/src/validate_utf8.ts b/1_ActivityWatchProducer/node_modules/bson/src/validate_utf8.ts new file mode 100644 index 00000000..e1da934c --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/memory-pager/.travis.yml b/1_ActivityWatchProducer/node_modules/memory-pager/.travis.yml new file mode 100644 index 00000000..1c4ab31e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/memory-pager/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - '4' + - '6' diff --git a/1_ActivityWatchProducer/node_modules/memory-pager/LICENSE b/1_ActivityWatchProducer/node_modules/memory-pager/LICENSE new file mode 100644 index 00000000..56fce089 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/memory-pager/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 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/1_ActivityWatchProducer/node_modules/memory-pager/README.md b/1_ActivityWatchProducer/node_modules/memory-pager/README.md new file mode 100644 index 00000000..aed17614 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/memory-pager/index.js b/1_ActivityWatchProducer/node_modules/memory-pager/index.js new file mode 100644 index 00000000..687f346f --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/memory-pager/package.json b/1_ActivityWatchProducer/node_modules/memory-pager/package.json new file mode 100644 index 00000000..f4847e8c --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/memory-pager/test.js b/1_ActivityWatchProducer/node_modules/memory-pager/test.js new file mode 100644 index 00000000..16382100 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs new file mode 100644 index 00000000..a0f5be52 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/LICENSE b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/LICENSE new file mode 100644 index 00000000..d57f55f4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/LICENSE @@ -0,0 +1,192 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + 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. + 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. + diff --git a/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/README.md b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/README.md new file mode 100644 index 00000000..0eb65d00 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.d.ts b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.d.ts new file mode 100644 index 00000000..49c18ea2 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.js b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.js new file mode 100644 index 00000000..8e4864d2 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.js.map b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/index.js.map new file mode 100644 index 00000000..d325062a --- /dev/null +++ b/1_ActivityWatchProducer/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,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,EAAE;YAC3C,IAAI,CAAC,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/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.d.ts b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.d.ts new file mode 100644 index 00000000..94a64def --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.js b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.js new file mode 100644 index 00000000..62c7ba71 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.js @@ -0,0 +1,86 @@ +"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 R = replacementString; + const replacements = [ + uri => uri.replace(redactUsernames ? /(\/\/)(.*)(@)/g : /(\/\/[^@]*:)(.*)(@)/g, `$1${R}$3`), + uri => uri.replace(/(AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi, `$1${R}`), + uri => uri.replace(/(tlsCertificateKeyFilePassword=)([^&]+)/gi, `$1${R}`), + uri => redactUsernames ? uri.replace(/(proxyUsername=)([^&]+)/gi, `$1${R}`) : uri, + uri => uri.replace(/(proxyPassword=)([^&]+)/gi, `$1${R}`) + ]; + for (const replacer of replacements) { + uri = replacer(uri); + } + return uri; +} +exports.redactConnectionString = redactConnectionString; +//# sourceMappingURL=redact.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.js.map b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/lib/redact.js.map new file mode 100644 index 00000000..24a282b9 --- /dev/null +++ b/1_ActivityWatchProducer/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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,EAAE,CAAC,GAAG,CAAC,OAAO,CAAC,2BAA2B,EAAE,KAAK,CAAC,EAAE,CAAC;KAC1D,CAAC;IACF,KAAK,MAAM,QAAQ,IAAI,YAAY,EAAE;QACnC,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;KACrB;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AApCD,wDAoCC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/package.json b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/package.json new file mode 100644 index 00000000..24a13d78 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb-connection-string-url/package.json @@ -0,0 +1,62 @@ +{ + "name": "mongodb-connection-string-url", + "version": "2.6.0", + "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/1_ActivityWatchProducer/node_modules/mongodb/LICENSE.md b/1_ActivityWatchProducer/node_modules/mongodb/LICENSE.md new file mode 100644 index 00000000..ad410e11 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/LICENSE.md @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + 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} + + 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. \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/README.md b/1_ActivityWatchProducer/node_modules/mongodb/README.md new file mode 100644 index 00000000..a619728b --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/README.md @@ -0,0 +1,295 @@ +# MongoDB NodeJS Driver + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. + +**Upgrading to version 5? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_5.0.0.md)!** + +## Quick Links + +| what | where | +| ------------- | ----------------------------------------------------------------------------------------------------------------- | +| documentation | [www.mongodb.com/docs/drivers/node](https://www.mongodb.com/docs/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 v5 | [etc/notes/CHANGES_5.0.0.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_5.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 +case in our issue management tool, JIRA: + +- 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**. + +### Support / Feedback + +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 + +Change history can be found in [`HISTORY.md`](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md). + +### Compatibility + +For version compatibility matrices, please refer to the following links: + +- [MongoDB](https://docs.mongodb.com/drivers/node/current/compatibility/#mongodb-compatibility) +- [NodeJS](https://docs.mongodb.com/drivers/node/current/compatibility/#language-compatibility) + +#### Typescript Version + +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). + +## Installation + +The recommended way to get started using the Node.js 5.x driver is by using the `npm` (Node Package Manager) to install the dependency in your project. + +After you've created your own project using `npm init`, you can run: + +```bash +npm install mongodb +# or ... +yarn add mongodb +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions: + +```sh +npm install -D @types/node +``` + +## Driver Extensions + +The MongoDB driver can optionally be enhanced by the following feature packages: + +Maintained by MongoDB: + +- Zstd network compression - [@mongodb-js/zstd](https://github.com/mongodb-js/zstd) +- MongoDB field level and queryable encryption - [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme) +- GSSAPI / SSPI / Kerberos authentication - [kerberos](https://github.com/mongodb-js/kerberos) + +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 compilation issues. + +Third party: + +- Snappy network compression - [snappy](https://github.com/Brooooooklyn/snappy) +- AWS authentication - [@aws-sdk/credential-providers](https://github.com/aws/aws-sdk-js-v3/tree/main/packages/credential-providers) + +## Quick Start + +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/). + +### Create the `package.json` file + +First, create a directory where your application will live. + +```bash +mkdir myProject +cd myProject +``` + +Enter the following command and answer the questions to create the initial structure for your new project: + +```bash +npm init -y +``` + +Next, install the driver as a dependency. + +```bash +npm install mongodb +``` + +### Start a MongoDB Server + +For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). + +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. + +```bash +mongod --dbpath=/data +``` + +You should see the **mongod** process start up and print some status information. + +### Connect to MongoDB + +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. + +Add code to connect to the server and the database **myProject**: + +> **NOTE:** Resolving DNS Connection issues +> +> Node.js 18 changed the default DNS resolution ordering from always prioritizing ipv4 to the ordering +> returned by the DNS provider. In some environments, this can result in `localhost` resolving to +> an ipv6 address instead of ipv4 and a consequent failure to connect to the server. +> +> This can be resolved by: +> +> - specifying the ip address family using the MongoClient `family` option (`MongoClient(, { family: 4 } )`) +> - launching mongod or mongos with the ipv6 flag enabled ([--ipv6 mongod option documentation](https://www.mongodb.com/docs/manual/reference/program/mongod/#std-option-mongod.--ipv6)) +> - using a host of `127.0.0.1` in place of localhost +> - specifying the DNS resolution ordering with the `--dns-resolution-order` Node.js command line argument (e.g. `node --dns-resolution-order=ipv4first`) + +```js +const { MongoClient } = require('mongodb'); +// or as an es module: +// import { MongoClient } from 'mongodb' + +// Connection URL +const url = 'mongodb://localhost:27017'; +const client = new MongoClient(url); + +// Database Name +const dbName = 'myProject'; + +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'); + + // the following code examples can be pasted here... + + return 'done.'; +} + +main() + .then(console.log) + .catch(console.error) + .finally(() => client.close()); +``` + +Run your app from the command line with: + +```bash +node app.js +``` + +The application should print **Connected successfully to server** to the console. + +### Insert a Document + +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. + +```js +const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]); +console.log('Inserted documents =>', insertResult); +``` + +The **insertMany** command returns an object with information about the insert operations. + +### Find All Documents + +Add a query that returns all the documents. + +```js +const findResult = await collection.find({}).toArray(); +console.log('Found documents =>', findResult); +``` + +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. + +### Find Documents with a Query Filter + +Add a query filter to find only documents which meet the query criteria. + +```js +const filteredDocs = await collection.find({ a: 3 }).toArray(); +console.log('Found documents filtered by { a: 3 } =>', filteredDocs); +``` + +Only the documents which match `'a' : 3` should be returned. + +### Update a document + +The following operation updates a document in the **documents** collection. + +```js +const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } }); +console.log('Updated documents =>', updateResult); +``` + +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. + +### Remove a document + +Remove the document where the field **a** is equal to **3**. + +```js +const deleteResult = await collection.deleteMany({ a: 3 }); +console.log('Deleted documents =>', deleteResult); +``` + +### 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 +const indexName = await collection.createIndex({ a: 1 }); +console.log('index name =', indexName); +``` + +For more detailed information, see the [indexing strategies page](https://docs.mongodb.com/manual/applications/indexes/). + +## Error Handling + +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). + +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. + +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. + +```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 +} +``` + +## Next Steps + +- [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) + +## License + +[Apache 2.0](LICENSE.md) + +© 2009-2012 Christian Amor Kvalheim +© 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTORS.md) diff --git a/1_ActivityWatchProducer/node_modules/mongodb/etc/prepare.js b/1_ActivityWatchProducer/node_modules/mongodb/etc/prepare.js new file mode 100644 index 00000000..2039d0b3 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/admin.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/admin.js new file mode 100644 index 00000000..c7722148 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/admin.js @@ -0,0 +1,131 @@ +"use strict"; +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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +class Admin { + /** + * Create a new Admin instance + * @internal + */ + constructor(db) { + this.s = { db }; + } + /** + * Execute a command + * + * @param command - The command to execute + * @param options - Optional settings for the command + */ + async command(command, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new run_command_1.RunCommandOperation(this.s.db, command, { dbName: 'admin', ...options })); + } + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async buildInfo(options) { + return this.command({ buildinfo: 1 }, options); + } + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async serverInfo(options) { + return this.command({ buildinfo: 1 }, options); + } + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + async serverStatus(options) { + return this.command({ serverStatus: 1 }, options); + } + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + async ping(options) { + return this.command({ ping: 1 }, options); + } + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + async addUser(username, passwordOrOptions, options) { + options = + options != null && typeof options === 'object' + ? options + : passwordOrOptions != null && typeof passwordOrOptions === 'object' + ? passwordOrOptions + : undefined; + const password = typeof passwordOrOptions === 'string' ? passwordOrOptions : undefined; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new add_user_1.AddUserOperation(this.s.db, username, password, { dbName: 'admin', ...options })); + } + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: 'admin', ...options })); + } + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + async validateCollection(collectionName, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options)); + } + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + async listDatabases(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new list_databases_1.ListDatabasesOperation(this.s.db, options)); + } + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + async replSetGetStatus(options) { + return this.command({ replSetGetStatus: 1 }, options); + } +} +exports.Admin = Admin; +//# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/admin.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/admin.js.map new file mode 100644 index 00000000..4477dc76 --- /dev/null +++ b/1_ActivityWatchProducer/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;AAO1C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,KAAK;IAIhB;;;OAGG;IACH,YAAY,EAAM;QAChB,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC;IAClB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,OAAO,CAAC,OAAiB,EAAE,OAA2B;QAC1D,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,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC,CAC7E,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,SAAS,CAAC,OAAiC;QAC/C,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,UAAU,CAAC,OAAiC;QAChD,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,Y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,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,kBAAkB,CACtB,cAAsB,EACtB,UAAqC,EAAE;QAEvC,OAAO,IAAA,oCAAgB,EACrB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAClB,IAAI,iDAA2B,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,CAAC,CAC/D,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,aAAa,CAAC,OAA8B;QAChD,OAAO,IAAA,oCAAgB,EAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,IAAI,uCAAsB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;IAC9F,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,gBAAgB,CAAC,OAAiC;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACxD,CAAC;CACF;AApID,sBAoIC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/bson.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/bson.js new file mode 100644 index 00000000..e3737307 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/bson.js @@ -0,0 +1,61 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveBSONOptions = exports.pluckBSONSerializeOptions = exports.Timestamp = exports.serialize = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.Double = exports.deserialize = exports.Decimal128 = exports.DBRef = exports.Code = exports.calculateObjectSize = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.BSON = exports.Binary = void 0; +var bson_1 = require("bson"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return bson_1.Binary; } }); +Object.defineProperty(exports, "BSON", { enumerable: true, get: function () { return bson_1.BSON; } }); +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, "BSONType", { enumerable: true, get: function () { return bson_1.BSONType; } }); +Object.defineProperty(exports, "calculateObjectSize", { enumerable: true, get: function () { return bson_1.calculateObjectSize; } }); +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, "deserialize", { enumerable: true, get: function () { return bson_1.deserialize; } }); +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, "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, "serialize", { enumerable: true, get: function () { return bson_1.serialize; } }); +Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return bson_1.Timestamp; } }); +function pluckBSONSerializeOptions(options) { + const { fieldsAsRaw, useBigInt64, promoteValues, promoteBuffers, promoteLongs, serializeFunctions, ignoreUndefined, bsonRegExp, raw, enableUtf8Validation } = options; + return { + fieldsAsRaw, + useBigInt64, + 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) { + const parentOptions = parent?.bsonOptions; + return { + raw: options?.raw ?? parentOptions?.raw ?? false, + useBigInt64: options?.useBigInt64 ?? parentOptions?.useBigInt64 ?? 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 + }; +} +exports.resolveBSONOptions = resolveBSONOptions; +//# sourceMappingURL=bson.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/bson.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/bson.js.map new file mode 100644 index 00000000..7236b490 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/bson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.js","sourceRoot":"","sources":["../src/bson.ts"],"names":[],"mappings":";;;AAEA,6BAoBc;AAnBZ,8FAAA,MAAM,OAAA;AACN,4FAAA,IAAI,OAAA;AACJ,kGAAA,UAAU,OAAA;AACV,kGAAA,UAAU,OAAA;AACV,gGAAA,QAAQ,OAAA;AACR,2GAAA,mBAAmB,OAAA;AACnB,4FAAA,IAAI,OAAA;AACJ,6FAAA,KAAK,OAAA;AACL,kGAAA,UAAU,OAAA;AACV,mGAAA,WAAW,OAAA;AAEX,8FAAA,MAAM,OAAA;AACN,6FAAA,KAAK,OAAA;AACL,4FAAA,IAAI,OAAA;AACJ,8FAAA,MAAM,OAAA;AAC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AAE;QACrE,oBAAoB,EAClB,OAAO,EAAE,oBAAoB,IAAI,aAAa,EAAE,oBAAoB,IAAI,IAAI;KAC/E,CAAC;AACJ,CAAC;AAlBD,gDAkBC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/common.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 00000000..98161224 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,874 @@ +"use strict"; +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 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 +}); +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +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; +/** + * @public + * The result of a bulk write. + */ +class BulkWriteResult { + static generateIdMap(ids) { + const idMap = {}; + for (const doc of ids) { + idMap[doc.index] = doc._id; + } + return idMap; + } + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult) { + this.result = bulkResult; + this.insertedCount = this.result.nInserted ?? 0; + this.matchedCount = this.result.nMatched ?? 0; + this.modifiedCount = this.result.nModified ?? 0; + this.deletedCount = this.result.nRemoved ?? 0; + this.upsertedCount = this.result.upserted.length ?? 0; + this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted); + this.insertedIds = BulkWriteResult.generateIdMap(this.result.insertedIds); + Object.defineProperty(this, 'result', { value: this.result, enumerable: false }); + } + /** 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 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 }); + } + } + toString() { + return `BulkWriteResult(${this.result})`; + } + isOk() { + return this.result.ok === 1; + } +} +exports.BulkWriteResult = BulkWriteResult; +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +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; + } + toJSON() { + return this[kServerError]; + } + toString() { + return `WriteConcernError(${this.errmsg})`; + } +} +exports.WriteConcernError = WriteConcernError; +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +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; +/** 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; + } + // 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 + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + 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) { + 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 + */ +class MongoBulkWriteError extends error_1.MongoServerError { + /** Creates a new MongoBulkWriteError */ + constructor(error, result) { + 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 = error.writeErrors ?? []; + } + 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; +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +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; + } + /** Specifies hint for the bulk operation. */ + hint(hint) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.hint = hint; + return this; + } +} +exports.FindOperators = FindOperators; +/** + * 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 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 + * ```ts + * 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 + * ```ts + * 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; + } + async execute(options = {}) { + if (this.s.executed) { + throw new error_1.MongoBatchReExecutionError(); + } + 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) { + throw new error_1.MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + } + 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); + } + /** + * 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; + } +} +exports.BulkOperationBase = BulkOperationBase; +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); +function shouldForceServerObjectId(bulkOperation) { + 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) { + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/common.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/common.js.map new file mode 100644 index 00000000..b4201c78 --- /dev/null +++ b/1_ActivityWatchProducer/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,kCAAuF;AAEvF,oCAOkB;AAGlB,iDAA6F;AAC7F,uEAAmE;AACnE,iDAAuD;AACvD,uDAAkE;AAClE,iDAA6F;AAI7F,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;AAoGZ;;;;;GAKG;AACH,MAAa,KAAK;IAShB,YAAY,SAAoB,EAAE,iBAAyB;QACzD,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;QAC3C,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;QACtB,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC;QAC1B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,CAAC,CAAC;QACd,IAAI,CAAC,SAAS,GAAG,CAAC,CAAC;IACrB,CAAC;CACF;AAlBD,sBAkBC;AAED;;;GAGG;AACH,MAAa,eAAe;IAiBlB,MAAM,CAAC,aAAa,CAAC,GAAe;QAC1C,MAAM,KAAK,GAA6B,EAAE,CAAC;QAC3C,KAAK,MAAM,GAAG,IAAI,GAAG,EAAE;YACrB,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,GAAG,CAAC;SAC5B;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED;;;OAGG;IACH,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AO,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/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/ordered.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 00000000..667f724f --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,67 @@ +"use strict"; +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 { + /** @internal */ + constructor(collection, options) { + super(collection, options, true); + } + 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; + } +} +exports.OrderedBulkOperation = OrderedBulkOperation; +//# sourceMappingURL=ordered.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/ordered.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/ordered.js.map new file mode 100644 index 00000000..3f16a990 --- /dev/null +++ b/1_ActivityWatchProducer/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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b/lib/bulk/unordered.js new file mode 100644 index 00000000..14b8f038 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,92 @@ +"use strict"; +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 { + /** @internal */ + constructor(collection, options) { + super(collection, options, false); + } + 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; + } +} +exports.UnorderedBulkOperation = UnorderedBulkOperation; +//# sourceMappingURL=unordered.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/unordered.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/bulk/unordered.js.map new file mode 100644 index 00000000..22bfa5d3 --- /dev/null +++ b/1_ActivityWatchProducer/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,gBAAgB;IAChB,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,CA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C,IAAI,CAAC,CAAC,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC;YAChD,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,IAAI,CAAC;gBACjC,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,MAAM;gBAC3C,GAAG,EAAG,QAAqB,CAAC,GAAG;aAChC,CAAC,CAAC;SACJ;aAAM,IAAI,SAAS,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;AAnGD,wDAmGC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/change_stream.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 00000000..99af9104 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,397 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChangeStream = void 0; +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(); + this.pipeline = pipeline; + this.options = { ...options }; + delete this.options.writeConcern; + 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 => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this[kCursorStream]?.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() { + return this.cursor?.resumeToken; + } + /** Check if there is any document still available in the Change Stream */ + async hasNext() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const hasNext = await this.cursor.hasNext(); + return hasNext; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + /** Get the next available document from the Change Stream. */ + async next() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.next(); + const processedChange = this._processChange(change ?? null); + return processedChange; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + async tryNext() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.tryNext(); + return change ?? null; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + async *[Symbol.asyncIterator]() { + if (this.closed) { + return; + } + try { + // Change streams run indefinitely as long as errors are resumable + // So the only loop breaking condition is if `next()` throws + while (true) { + yield await this.next(); + } + } + finally { + try { + await this.close(); + } + catch { + // we're not concerned with errors from close() + } + } + } + /** Is the cursor closed */ + get closed() { + return this[kClosed] || this.cursor.closed; + } + /** Close the Change Stream */ + async close() { + this[kClosed] = true; + const cursor = this.cursor; + try { + await cursor.close(); + } + finally { + this._endStream(); + } + } + /** + * 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().catch(() => null); + } + /** @internal */ + _streamEvents(cursor) { + 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 */ + _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 */ + async _processErrorIteratorMode(changeStreamError) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + if (!(0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) { + try { + await this.close(); + } + catch { + // ignore errors from close + } + throw changeStreamError; + } + await this.cursor.close().catch(() => null); + const topology = (0, utils_1.getTopology)(this.parent); + try { + await topology.selectServerAsync(this.cursor.readPreference, {}); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + } + catch { + // if the topology can't reconnect, close the stream + await this.close(); + throw 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/1_ActivityWatchProducer/node_modules/mongodb/lib/change_stream.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/change_stream.js.map new file mode 100644 index 00000000..eaa60cb2 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/change_stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"change_stream.js","sourceRoot":"","sources":["../src/change_stream.ts"],"names":[],"mappings":";;;AAGA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auth_provider.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/auth_provider.js new file mode 100644 index 00000000..b9a840ee --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map new file mode 100644 index 00000000..c03ab374 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/gssapi.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/gssapi.js new file mode 100644 index 00000000..b14a01f4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/gssapi.js @@ -0,0 +1,188 @@ +"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) { + 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 = mechanismProperties.SERVICE_NAME ?? 'mongodb'; + performGSSAPICanonicalizeHostName(hostAddress.host, mechanismProperties, (err, host) => { + 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, 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/gssapi.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/gssapi.js.map new file mode 100644 index 00000000..76606515 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/gssapi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gssapi.js","sourceRoot":"","sources":["../../../src/cmap/auth/gssapi.ts"],"names":[],"mappings":";;;A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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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js new file mode 100644 index 00000000..f6ada1db --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js @@ -0,0 +1,145 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCredentials = void 0; +const error_1 = require("../../error"); +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 + }; + } + } + 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() { + 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 (this.mechanism === providers_1.AuthMechanism.MONGODB_OIDC) { + if (this.username) { + throw new error_1.MongoInvalidArgumentError(`Username not permitted for mechanism '${this.mechanism}'. Use PRINCIPAL_NAME instead.`); + } + if (this.mechanismProperties.PRINCIPAL_NAME && this.mechanismProperties.DEVICE_NAME) { + throw new error_1.MongoInvalidArgumentError(`PRINCIPAL_NAME and DEVICE_NAME may not be used together for mechanism '${this.mechanism}'.`); + } + if (this.mechanismProperties.DEVICE_NAME && this.mechanismProperties.DEVICE_NAME !== 'aws') { + throw new error_1.MongoInvalidArgumentError(`Currently only a DEVICE_NAME of 'aws' is supported for mechanism '${this.mechanism}'.`); + } + if (this.mechanismProperties.REFRESH_TOKEN_CALLBACK && + !this.mechanismProperties.REQUEST_TOKEN_CALLBACK) { + throw new error_1.MongoInvalidArgumentError(`A REQUEST_TOKEN_CALLBACK must be provided when using a REFRESH_TOKEN_CALLBACK for mechanism '${this.mechanism}'`); + } + if (!this.mechanismProperties.DEVICE_NAME && + !this.mechanismProperties.REQUEST_TOKEN_CALLBACK) { + throw new error_1.MongoInvalidArgumentError(`Either a DEVICE_NAME or a REQUEST_TOKEN_CALLBACK must be specified 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 = this.mechanismProperties.CANONICALIZE_HOST_NAME ?? false; + if (!Object.values(gssapi_1.GSSAPICanonicalizationValue).includes(canonicalization)) { + throw new error_1.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`); + } + } + static merge(creds, options) { + return new MongoCredentials({ + username: options.username ?? creds?.username ?? '', + password: options.password ?? creds?.password ?? '', + mechanism: options.mechanism ?? creds?.mechanism ?? providers_1.AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: options.mechanismProperties ?? creds?.mechanismProperties ?? {}, + source: options.source ?? options.db ?? creds?.source ?? 'admin' + }); + } +} +exports.MongoCredentials = MongoCredentials; +//# sourceMappingURL=mongo_credentials.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map new file mode 100644 index 00000000..c328c29e --- /dev/null +++ b/1_ActivityWatchProducer/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,uCAIqB;AACrB,qCAAuD;AAEvD,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,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AAmB,IAAI,EAAE;YACpF,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,EAAE,IAAI,KAAK,EAAE,MAAM,IAAI,OAAO;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAxKD,4CAwKC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongocr.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongocr.js new file mode 100644 index 00000000..f8afea2d --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongocr.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongocr.js.map new file mode 100644 index 00000000..62e4f979 --- /dev/null +++ b/1_ActivityWatchProducer/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,CAAC;QACtC,MAAM,MAAM,GAAG,WAAW,CAAC,MAAM,CAAC;QAClC,UAAU,CAAC,OAAO,CAAC,IAAA,UAAE,EAAC,GAAG,MAAM,OAAO,CAAC,EAAE,EAAE,QAAQ,EAAE,CAAC,EAAE,EAAE,SAAS,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE;YAC9E,IAAI,KAAK,GAAG,IAAI,CAAC;YACjB,IAAI,GAAG,GAAG,IAAI,CAAC;YAEf,YAAY;YACZ,IAAI,GAAG,IAAI,IAAI,EAAE;gBACf,KAAK,GAAG,CAAC,CAAC,KAAK,CAAC;gBAEhB,yBAAyB;gBACzB,IAAI,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;gBAEnC,wCAAwC;gBACxC,GAAG,CAAC,MAAM,CAAC,GAAG,QAAQ,UAAU,QAAQ,EAAE,EAAE,MAAM,CAAC,CAAC;gBACpD,MAAM,aAAa,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBAExC,YAAY;gBACZ,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;gBAC/B,GAAG,CAAC,MAAM,CAAC,KAAK,GAAG,QAAQ,GAAG,aAAa,EAAE,MAAM,CAAC,CAAC;gBACrD,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;aACzB;YAED,MAAM,mBAAmB,GAAG;gBAC1B,YAAY,EAAE,CAAC;gBACf,IAAI,EAAE,QAAQ;gBACd,KAAK;gBACL,GAAG;aACJ,CAAC;YAEF,UAAU,CAAC,OAAO,CAAC,IAAA,UAAE,EAAC,GAAG,MAAM,OAAO,CAAC,EAAE,mBAAmB,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;QACrF,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAxCD,0BAwCC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js new file mode 100644 index 00000000..fe874583 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js @@ -0,0 +1,238 @@ +"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 = { + useBigInt64: false, + 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 (!utils_1.ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) { + // throw because the serverNonce's leading 32 bytes must equal the client nonce's 32 bytes + // https://github.com/mongodb/specifications/blob/875446db44aade414011731840831f38a6c668df/source/auth/auth.rst#id11 + // 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': utils_1.ByteUtils.toBase64(serverNonce), + '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 + } + })); + } + const credentialProvider = (0, deps_1.getAwsCredentialProvider)(); + // Check if the AWS credential provider from the SDK is present. If not, + // use the old method. + if ('kModuleError' in credentialProvider) { + // 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); + }); + }); + }); + } + else { + /* + * Creates a credential provider that will attempt to find credentials from the + * following sources (listed in order of precedence): + * + * - Environment variables exposed via process.env + * - SSO credentials from token cache + * - Web identity token credentials + * - Shared credentials and config ini files + * - The EC2/ECS Instance Metadata Service + */ + const { fromNodeProviderChain } = credentialProvider; + const provider = fromNodeProviderChain(); + provider() + .then((creds) => { + done({ + AccessKeyId: creds.accessKeyId, + SecretAccessKey: creds.secretAccessKey, + Token: creds.sessionToken, + Expiration: creds.expiration + }); + }) + .catch((error) => { + callback(new error_1.MongoAWSError(error.message)); + }); + } +} +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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map new file mode 100644 index 00000000..fc3883f9 --- /dev/null +++ b/1_ActivityWatchProducer/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,qCAA4D;AAC5D,uCAKqB;AACrB,uCAAsE;AACtE,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,WAAW,EAAE,KAAK;IAClB,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,CACN,IAAI,+BAAuB,CACzB,kEAAkE,CACnE,CACF,CAAC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} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js new file mode 100644 index 00000000..2e60f666 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=mongodb_oidc.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js.map new file mode 100644 index 00000000..7d5145f4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/mongodb_oidc.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongodb_oidc.js","sourceRoot":"","sources":["../../../src/cmap/auth/mongodb_oidc.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/plain.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/plain.js new file mode 100644 index 00000000..e7153a58 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/plain.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/plain.js.map new file mode 100644 index 00000000..a03580a3 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/providers.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/providers.js new file mode 100644 index 00000000..98026f29 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/providers.js @@ -0,0 +1,24 @@ +"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 TODO: NODE-5035: Make mechanism public. */ + MONGODB_OIDC: 'MONGODB-OIDC' +}); +/** @internal */ +exports.AUTH_MECHS_AUTH_SRC_EXTERNAL = new Set([ + exports.AuthMechanism.MONGODB_GSSAPI, + exports.AuthMechanism.MONGODB_AWS, + exports.AuthMechanism.MONGODB_OIDC, + exports.AuthMechanism.MONGODB_X509 +]); +//# sourceMappingURL=providers.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/providers.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/providers.js.map new file mode 100644 index 00000000..3765f23b --- /dev/null +++ b/1_ActivityWatchProducer/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;IAC5B,wDAAwD;IACxD,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;IAC1B,qBAAa,CAAC,YAAY;CAC3B,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/scram.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/scram.js new file mode 100644 index 00000000..00a77ac0 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/scram.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/scram.js.map new file mode 100644 index 00000000..c94940db --- /dev/null +++ b/1_ActivityWatchProducer/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,M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ED,MAAa,SAAU,SAAQ,QAAQ;IACrC;QACE,KAAK,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;CACF;AAJD,8BAIC;AAED,MAAa,WAAY,SAAQ,QAAQ;IACvC;QACE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAClB,CAAC;CACF;AAJD,kCAIC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/x509.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/x509.js new file mode 100644 index 00000000..02fe3853 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/x509.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/auth/x509.js.map new file mode 100644 index 00000000..84af5792 --- /dev/null +++ b/1_Activ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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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/command_monitoring_events.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/command_monitoring_events.js new file mode 100644 index 00000000..ec8fc61c --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/command_monitoring_events.js @@ -0,0 +1,242 @@ +"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) { + if (command instanceof commands_1.Msg) { + return (0, utils_1.deepCopy)(command.command); + } + if (command.query?.$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 (!reply) { + return reply; + } + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map new file mode 100644 index 00000000..0c259d49 --- /dev/null +++ b/1_ActivityWatchProducer/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,yCAA2D;AAG3D;;;;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,IAAI,CAAC;SACrC;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC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,EAAC,KAAK,CAAC,QAAQ,CAAC;gBAC5B,EAAE,EAAE,SAAS,CAAC,OAAO,CAAC;gBACtB,UAAU,EAAE,IAAA,gBAAQ,EAAC,KAAK,CAAC,SAAS,CAAC;aACtC;SACF,CAAC;KACH;IAED,OAAO,IAAA,gBAAQ,EAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/commands.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/commands.js new file mode 100644 index 00000000..58dce395 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/commands.js @@ -0,0 +1,487 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BinMsg = exports.Msg = exports.Response = 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; +/** @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 ?? { + useBigInt64: false, + 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.useBigInt64 = typeof this.opts.useBigInt64 === 'boolean' ? this.opts.useBigInt64 : false; + 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) { + // 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 useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64; + 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 = { + useBigInt64, + 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 ?? {}; + // 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 ?? { + useBigInt64: false, + 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.useBigInt64 = typeof this.opts.useBigInt64 === 'boolean' ? this.opts.useBigInt64 : false; + 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) { + // 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 useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64; + 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 = { + useBigInt64, + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/commands.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/commands.js.map new file mode 100644 index 00000000..33bb6631 --- /dev/null +++ b/1_ActivityWatchProducer/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,yDAA6D;AAE7D,0BAA0B;AAC1B,IAAI,UAAU,GAAG,CAAC,CAAC;AAEnB,cAAc;AACd,MAAM,oBAAoB,GAAG,CAAC,CAAC;AAC/B,MAAM,cAAc,GAAG,CAAC,CAAC;AACzB,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,sBAAsB,GAAG,EAAE,CAAC;AAClC,MAAM,eAAe,GAAG,EAAE,CAAC;AAC3B,MAAM,YAAY,GAAG,EAAE,CAAC;AACxB,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,iBAAiB;AACjB,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAC3B,MAAM,aAAa,GAAG,CAAC,CAAC;AACxB,MAAM,kBAAkB,GAAG,CAAC,CAAC;AAC7B,MAAM,aAAa,GAAG,CAAC,CAAC;AA0BxB;;gEAEgE;AAChE,gBAAgB;AAChB,MAAa,KAAK;IAsBhB,YAAY,EAAU,EAAE,KAAe,EAAE,OAAuB;QAC9D,uCAAuC;QACvC,kDAAkD;QAClD,IAAI,EAAE,IAAI,IAAI;YAAE,MAAM,IAAI,yBAAiB,CAAC,uCAAuC,CAAC,CAAC;QACrF,kDAAkD;QAClD,IAAI,KAAK,IAAI,IAAI;YAAE,MAAM,IAAI,yBAAiB,CAAC,8CAA8C,CAAC,CAAC;QAE/F,+DAA+D;QAC/D,IAAI,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE;YAC7B,oDAAoD;YACpD,MAAM,IAAI,yBAAiB,CAAC,2CAA2C,CAAC,CAAC;SAC1E;QAED,gBAAgB;QAChB,IAA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O,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;SACxB;QAED,OAAO,EAAE,IAAI,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE,EAAE,CAAC;IAC1C,CAAC;CACF;AAhID,wBAgIC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connect.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connect.js new file mode 100644 index 00000000..677ed64f --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connect.js @@ -0,0 +1,394 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LEGAL_TCP_SOCKET_OPTIONS = exports.LEGAL_TLS_SOCKET_OPTIONS = exports.prepareHandshakeDocument = 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) => { + if (err || !socket) { + return callback(err); + } + let ConnectionType = options.connectionType ?? connection_1.Connection; + if (options.autoEncrypter) { + ConnectionType = connection_1.CryptoConnection; + } + performInitialHandshake(new ConnectionType(socket, options), options, callback); + }); +} +exports.connect = connect; +function checkSupportedServer(hello, options) { + 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 ${JSON.stringify(hello.maxWireVersion) ?? 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({ force: false }); + } + _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?.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); + }); + }); +} +/** + * @internal + * + * This function is only exposed for testing purposes. + */ +function prepareHandshakeDocument(authContext, callback) { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + const handshakeDoc = { + [serverApi?.version ? 'hello' : constants_1.LEGACY_HELLO_COMMAND]: 1, + helloOk: true, + client: options.metadata || (0, utils_1.makeClientMetadata)(options), + compression: compressors + }; + if (options.loadBalanced === true) { + handshakeDoc.loadBalanced = true; + } + 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); +} +exports.prepareHandshakeDocument = prepareHandshakeDocument; +/** @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) { + 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; + 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) { + const hostAddress = utils_1.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); + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connect.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connect.js.map new file mode 100644 index 00000000..9294eb7f --- /dev/null +++ b/1_ActivityWatchProducer/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,EAAE,IAAI,aAAK,EAAE,CAAC;IAC1C,CAAC,yBAAa,CAAC,kBAAkB,EAAE,IAAI,iBAA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AAuB,CAAC,CAAC;KACzD;AACH,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection.js new file mode 100644 index 00000000..331a9861 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection.js @@ -0,0 +1,496 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasSessionSupport = exports.CryptoConnection = exports.Connection = void 0; +const timers_1 = require("timers"); +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 kDelayedTimeoutId = Symbol('delayedTimeoutId'); +const INVALID_QUEUE_SIZE = 'Connection internal queue contains more than 1 operation description'; +/** @internal */ +class Connection extends mongo_types_1.TypedEventEmitter { + constructor(stream, options) { + 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[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: 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() { + 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() { + return this.hello?.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) { + this.cleanup(true, error); + } + onClose() { + const message = `connection ${this.id} to ${this.address} closed`; + this.cleanup(true, new error_1.MongoNetworkError(message)); + } + onTimeout() { + this[kDelayedTimeoutId] = (0, timers_1.setTimeout)(() => { + const message = `connection ${this.id} to ${this.address} timed out`; + const beforeHandshake = this.hello == null; + this.cleanup(true, new error_1.MongoNetworkTimeoutError(message, { beforeHandshake })); + }, 1).unref(); // No need for this timer to hold the event loop open + } + onMessage(message) { + const delayedTimeoutId = this[kDelayedTimeoutId]; + if (delayedTimeoutId != null) { + (0, timers_1.clearTimeout)(delayedTimeoutId); + this[kDelayedTimeoutId] = null; + } + // always emit the message, in case we are streaming + this.emit('message', message); + let operationDescription = this[kQueue].get(message.responseTo); + if (!operationDescription && this.isMonitoringConnection) { + // This is how we recover when the initial hello's requestId is not + // the responseTo when hello responses have been skipped: + // First check if the map is of invalid size + if (this[kQueue].size > 1) { + this.cleanup(true, new error_1.MongoRuntimeError(INVALID_QUEUE_SIZE)); + } + else { + // Get the first orphaned operation description. + const entry = this[kQueue].entries().next(); + if (entry.value != null) { + const [requestId, orphaned] = entry.value; + // If the orphaned operation description exists then set it. + operationDescription = orphaned; + // Remove the entry with the bad request id from the queue. + this[kQueue].delete(requestId); + } + } + } + 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) { + // If the operation description check above does find an orphaned + // description and sets the operationDescription then this line will put one + // back in the queue with the correct requestId and will resolve not being able + // to find the next one via the responseTo of the next streaming hello. + 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), 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, message.documents[0]); + } + destroy(options, callback) { + if (this.closed) { + process.nextTick(() => callback?.()); + return; + } + if (typeof callback === 'function') { + this.once('close', () => process.nextTick(() => callback())); + } + // load balanced mode requires that these listeners remain on the connection + // after cleanup on timeouts, errors or close so we remove them before calling + // cleanup. + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + const message = `connection ${this.id} to ${this.address} closed`; + this.cleanup(options.force, new error_1.MongoNetworkError(message)); + } + /** + * A method that cleans up the connection. When `force` is true, this method + * forcibly destroys the socket. + * + * If an error is provided, any in-flight operations will be closed with the error. + * + * This method does nothing if the connection is already closed. + */ + cleanup(force, error) { + if (this.closed) { + return; + } + this.closed = true; + const completeCleanup = () => { + for (const op of this[kQueue].values()) { + op.cb(error); + } + this[kQueue].clear(); + this.emit(Connection.CLOSE); + }; + this[kStream].removeAllListeners(); + this[kMessageStream].removeAllListeners(); + this[kMessageStream].destroy(); + if (force) { + this[kStream].destroy(); + completeCleanup(); + return; + } + if (!this[kStream].writableEnded) { + this[kStream].end(() => { + this[kStream].destroy(); + completeCleanup(); + }); + } + else { + completeCleanup(); + } + } + command(ns, cmd, options, callback) { + const readPreference = (0, shared_1.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 = (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); + } + } +} +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; + } + // Save sort or indexKeys based on the command being run + // the encrypt API serializes our JS objects to BSON to pass to the native code layer + // and then deserializes the encrypted result, the protocol level components + // of the command (ex. sort) are then converted to JS objects potentially losing + // import key order information. These fields are never encrypted so we can save the values + // from before the encryption and replace them after encryption has been performed + const sort = cmd.find || cmd.findAndModify ? cmd.sort : null; + const indexKeys = cmd.createIndexes + ? cmd.indexes.map((index) => index.key) + : null; + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + // Replace the saved values + if (sort != null && (cmd.find || cmd.findAndModify)) { + encrypted.sort = sort; + } + if (indexKeys != null && cmd.createIndexes) { + for (const [offset, index] of indexKeys.entries()) { + encrypted.indexes[offset].key = index; + } + } + 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(); + } + const { remoteAddress, remotePort } = stream; + if (typeof remoteAddress === 'string' && typeof remotePort === 'number') { + return utils_1.HostAddress.fromHostPort(remoteAddress, remotePort).toString(); + } + return (0, utils_1.uuidV4)().toString('hex'); +} +function write(conn, command, options, callback) { + options = options ?? {}; + const operationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, + documentsReturnedIn: options.documentsReturnedIn, + command: !!options.command, + // for BSON parsing + useBigInt64: typeof options.useBigInt64 === 'boolean' ? options.useBigInt64 : 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, + 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) => { + // Command monitoring spec states that if ok is 1, then we must always emit + // a command suceeded event, even if there's an error. Write concern errors + // will have an ok: 1 in their reply. + if (err && reply?.ok !== 1) { + 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') { + // Since we're passing through the reply with the write concern error now, we + // need it not to be provided to the original callback in this case so + // retryability does not get tricked into thinking the command actually + // succeeded. + callback(err, err instanceof error_1.MongoWriteConcernError ? undefined : 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection.js.map new file mode 100644 index 00000000..6f824f1e --- /dev/null +++ b/1_ActivityWatchProducer/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,mCAAkD;AAGlD,4CASsB;AAEtB,oCAQkB;AAElB,gDAAsE;AAEtE,0CAAqF;AACrF,oCASkB;AAGlB,2EAIqC;AACrC,yCAAoF;AAEpF,qDAAuE;AACvE,6DAAmF;AACnF,mDAAsE;AAEtE,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAC/B,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAC/C,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAC/B,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAC/C,gBAAgB;AAChB,MAAM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,CAAC,CAAC;aAC1E;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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool.js new file mode 100644 index 00000000..b9db0002 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool.js @@ -0,0 +1,591 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPool = exports.PoolState = void 0; +const timers_1 = require("timers"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +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 kServer = Symbol('server'); +/** @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'); +/** @internal */ +const kPoolState = Symbol('poolState'); +/** @internal */ +exports.PoolState = Object.freeze({ + paused: 'paused', + ready: 'ready', + closed: 'closed' +}); +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +class ConnectionPool extends mongo_types_1.TypedEventEmitter { + constructor(server, options) { + super(); + this.options = Object.freeze({ + ...options, + connectionType: connection_1.Connection, + maxPoolSize: options.maxPoolSize ?? 100, + minPoolSize: options.minPoolSize ?? 0, + maxConnecting: options.maxConnecting ?? 2, + maxIdleTimeMS: options.maxIdleTimeMS ?? 0, + waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0, + minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100, + 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[kPoolState] = exports.PoolState.paused; + this[kServer] = server; + this[kConnections] = new utils_1.List(); + this[kPending] = 0; + this[kCheckedOut] = new Set(); + 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 utils_1.List(); + this[kMetrics] = new metrics_1.ConnectionPoolMetrics(); + this[kProcessingWaitQueue] = false; + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this)); + }); + } + /** The address of the endpoint the pool is connected to */ + get address() { + return this.options.hostAddress.toString(); + } + /** + * Check if the pool has been closed + * + * TODO(NODE-3263): We can remove this property once shell no longer needs it + */ + get closed() { + return this[kPoolState] === exports.PoolState.closed; + } + /** 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].size; + } + get waitQueueSize() { + return this[kWaitQueue].length; + } + get loadBalanced() { + return this.options.loadBalanced; + } + get serviceGenerations() { + return this[kServiceGenerations]; + } + get serverError() { + return this[kServer].description.error; + } + /** + * This is exposed ONLY for use in mongosh, to enable + * killing all connections if a user quits the shell with + * operations in progress. + * + * This property may be removed as a part of NODE-3263. + */ + get checkedOutConnections() { + return this[kCheckedOut]; + } + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + waitQueueErrorMetrics() { + return this[kMetrics].info(this.options.maxPoolSize); + } + /** + * Set the pool state to "ready" + */ + ready() { + if (this[kPoolState] !== exports.PoolState.paused) { + return; + } + this[kPoolState] = exports.PoolState.ready; + this.emit(ConnectionPool.CONNECTION_POOL_READY, new connection_pool_events_1.ConnectionPoolReadyEvent(this)); + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this.ensureMinPoolSize(); + } + /** + * 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)); + 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(() => this.processWaitQueue()); + } + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection) { + if (!this[kCheckedOut].has(connection)) { + return; + } + const poolClosed = this.closed; + const stale = this.connectionIsStale(connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + this[kCheckedOut].delete(connection); + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection)); + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + this.destroyConnection(connection, reason); + } + process.nextTick(() => this.processWaitQueue()); + } + /** + * 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(options = {}) { + if (this.closed) { + return; + } + // handle load balanced case + if (this.loadBalanced) { + const { serviceId } = options; + if (!serviceId) { + throw new error_1.MongoRuntimeError('ConnectionPool.clear() called in load balanced mode with no 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) { + 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); + } + this.emit(ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { serviceId })); + return; + } + // handle non load-balanced case + const interruptInUseConnections = options.interruptInUseConnections ?? false; + const oldGeneration = this[kGeneration]; + this[kGeneration] += 1; + const alreadyPaused = this[kPoolState] === exports.PoolState.paused; + this[kPoolState] = exports.PoolState.paused; + this.clearMinPoolSizeTimer(); + if (!alreadyPaused) { + this.emit(ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { interruptInUseConnections })); + } + if (interruptInUseConnections) { + process.nextTick(() => this.interruptInUseConnections(oldGeneration)); + } + this.processWaitQueue(); + } + /** + * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError. + * + * Only connections where `connection.generation <= minGeneration` are killed. + */ + interruptInUseConnections(minGeneration) { + for (const connection of this[kCheckedOut]) { + if (connection.generation <= minGeneration) { + this.checkIn(connection); + connection.onError(new errors_1.PoolClearedOnNetworkError(this)); + } + } + } + close(_options, _cb) { + let options = _options; + const callback = (_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'); + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + this[kPoolState] = exports.PoolState.closed; + this.clearMinPoolSizeTimer(); + this.processWaitQueue(); + (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({ force: !!options.force }, 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); + } + }); + }); + } + /** Clear the min pool size timer */ + clearMinPoolSizeTimer() { + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + (0, timers_1.clearTimeout)(minPoolSizeTimer); + } + } + destroyConnection(connection, reason) { + this.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, connection, reason)); + // destroy the connection + process.nextTick(() => connection.destroy({ force: false })); + } + connectionIsStale(connection) { + const serviceId = connection.serviceId; + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + return connection.generation !== generation; + } + return connection.generation !== this[kGeneration]; + } + connectionIsIdle(connection) { + return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS); + } + /** + * Destroys a connection if the connection is perished. + * + * @returns `true` if the connection was destroyed, `false` otherwise. + */ + destroyConnectionIfPerished(connection) { + const isStale = this.connectionIsStale(connection); + const isIdle = this.connectionIsIdle(connection); + if (!isStale && !isIdle && !connection.closed) { + return false; + } + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + this.destroyConnection(connection, reason); + return true; + } + createConnection(callback) { + const connectOptions = { + ...this.options, + id: this[kConnectionCounter].next().value, + generation: this[kGeneration], + cancellationToken: this[kCancellationToken] + }; + this[kPending]++; + // This is our version of a "virtual" no-I/O connection as the spec requires + this.emit(ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(this, { id: connectOptions.id })); + (0, connect_1.connect)(connectOptions, (err, connection) => { + if (err || !connection) { + this[kPending]--; + this.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, { id: connectOptions.id, serviceId: undefined }, 'error')); + if (err instanceof error_1.MongoNetworkError || err instanceof error_1.MongoServerError) { + err.connectionGeneration = connectOptions.generation; + } + callback(err ?? new error_1.MongoRuntimeError('Connection creation failed without error')); + return; + } + // The pool might have closed since we started trying to create a connection + if (this[kPoolState] !== exports.PoolState.ready) { + this[kPending]--; + connection.destroy({ force: true }); + callback(this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this)); + 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) => this.emit(event, e)); + } + if (this.loadBalanced) { + connection.on(connection_1.Connection.PINNED, pinType => this[kMetrics].markPinned(pinType)); + connection.on(connection_1.Connection.UNPINNED, pinType => this[kMetrics].markUnpinned(pinType)); + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = this.serviceGenerations.get(sid))) { + connection.generation = generation; + } + else { + this.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + connection.markAvailable(); + this.emit(ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(this, connection)); + this[kPending]--; + callback(undefined, connection); + return; + }); + } + ensureMinPoolSize() { + const minPoolSize = this.options.minPoolSize; + if (this[kPoolState] !== exports.PoolState.ready || minPoolSize === 0) { + return; + } + this[kConnections].prune(connection => this.destroyConnectionIfPerished(connection)); + if (this.totalConnectionCount < minPoolSize && + this.pendingConnectionCount < this.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 + this.createConnection((err, connection) => { + if (err) { + this[kServer].handleError(err); + } + if (!err && connection) { + this[kConnections].push(connection); + process.nextTick(() => this.processWaitQueue()); + } + if (this[kPoolState] === exports.PoolState.ready) { + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS); + } + }); + } + else { + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS); + } + } + processWaitQueue() { + if (this[kProcessingWaitQueue]) { + return; + } + this[kProcessingWaitQueue] = true; + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].first(); + if (!waitQueueMember) { + this[kWaitQueue].shift(); + continue; + } + if (waitQueueMember[kCancelled]) { + this[kWaitQueue].shift(); + continue; + } + if (this[kPoolState] !== exports.PoolState.ready) { + const reason = this.closed ? 'poolClosed' : 'connectionError'; + const error = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this); + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, reason)); + if (waitQueueMember.timer) { + (0, timers_1.clearTimeout)(waitQueueMember.timer); + } + this[kWaitQueue].shift(); + waitQueueMember.callback(error); + continue; + } + if (!this.availableConnectionCount) { + break; + } + const connection = this[kConnections].shift(); + if (!connection) { + break; + } + if (!this.destroyConnectionIfPerished(connection)) { + this[kCheckedOut].add(connection); + this.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection)); + if (waitQueueMember.timer) { + (0, timers_1.clearTimeout)(waitQueueMember.timer); + } + this[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + } + } + const { maxPoolSize, maxConnecting } = this.options; + while (this.waitQueueSize > 0 && + this.pendingConnectionCount < maxConnecting && + (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)) { + const waitQueueMember = this[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + continue; + } + this.createConnection((err, connection) => { + if (waitQueueMember[kCancelled]) { + if (!err && connection) { + this[kConnections].push(connection); + } + } + else { + if (err) { + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'connectionError')); + } + else if (connection) { + this[kCheckedOut].add(connection); + this.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection)); + } + if (waitQueueMember.timer) { + (0, timers_1.clearTimeout)(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + } + process.nextTick(() => this.processWaitQueue()); + }); + } + this[kProcessingWaitQueue] = false; + } +} +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 each time the connection pool is marked ready + * @event + */ +ConnectionPool.CONNECTION_POOL_READY = constants_1.CONNECTION_POOL_READY; +/** + * 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; +//# sourceMappingURL=connection_pool.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool.js.map new file mode 100644 index 00000000..464ab40d --- /dev/null +++ b/1_ActivityWatchProducer/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,mCAAkD;AAGlD,4CAasB;AACtB,oCAMkB;AAClB,gDAAsE;AAEtE,oCAAkE;AAClE,uCAAoC;AACpC,6CAA+E;AAC/E,qEAYkC;AAClC,qCAKkB;AAClB,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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CAAC,UAAU,CAAC,CAAC;wBAClC,IAAI,CAAC,IAAI,CACP,cAAc,CAAC,sBAAsB,EACrC,IAAI,kDAAyB,CAAC,IAAI,EAAE,UAAU,CAAC,CAChD,CAAC;qBACH;oBAED,IAAI,eAAe,CAAC,KAAK,EAAE;wBACzB,IAAA,qBAAY,EAAC,eAAe,CAAC,KAAK,CAAC,CAAC;qBACrC;oBACD,eAAe,CAAC,QAAQ,CAAC,GAAG,EAAE,UAAU,CAAC,CAAC;iBAC3C;gBACD,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC,CAAC;YAClD,CAAC,CAAC,CAAC;SACJ;QACD,IAAI,CAAC,oBAAoB,CAAC,GAAG,KAAK,CAAC;IACrC,CAAC;;AAlrBH,wCAmrBC;AA7pBC;;;GAGG;AACa,sCAAuB,GAAG,mCAAuB,CAAC;AAClE;;;GAGG;AACa,qCAAsB,GAAG,kCAAsB,CAAC;AAChE;;;GAGG;AACa,sCAAuB,GAAG,mCAAuB,CAAC;AAClE;;;GAGG;AACa,oCAAqB,GAAG,iCAAqB,CAAC;AAC9D;;;GAGG;AACa,iCAAkB,GAAG,8BAAkB,CAAC;AACxD;;;GAGG;AACa,+BAAgB,GAAG,4BAAgB,CAAC;AACpD;;;GAGG;AACa,gCAAiB,GAAG,6BAAiB,CAAC;AACtD;;;GAGG;AACa,2CAA4B,GAAG,wCAA4B,CAAC;AAC5E;;;GAGG;AACa,0CAA2B,GAAG,uCAA2B,CAAC;AAC1E;;;GAGG;AACa,qCAAsB,GAAG,kCAAsB,CAAC;AAChE;;;GAGG;AACa,oCAAqB,GAAG,iCAAqB,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool_events.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool_events.js new file mode 100644 index 00000000..f13528d4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool_events.js @@ -0,0 +1,160 @@ +"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.ConnectionPoolReadyEvent = 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 ready + * @public + * @category Event + */ +class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + } +} +exports.ConnectionPoolReadyEvent = ConnectionPoolReadyEvent; +/** + * 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, options = {}) { + super(pool); + this.serviceId = options.serviceId; + this.interruptInUseConnections = options.interruptInUseConnections; + } +} +exports.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent; +//# sourceMappingURL=connection_pool_events.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool_events.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/connection_pool_events.js.map new file mode 100644 index 00000000..22ad3af4 --- /dev/null +++ b/1_ActivityWatchProducer/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,EAAE,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;CACF;AAXD,sEAWC;AAED;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,6BAA6B;IAI3E,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;CACF;AATD,gEASC;AAED;;;;GAIG;AACH,MAAa,wBAAyB,SAAQ,6BAA6B;IACzE,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;CACF;AALD,4DAKC;AAED;;;;GAIG;AACH,MAAa,yBAA0B,SAAQ,6BAA6B;IAC1E,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;CACF;AALD,8DAKC;AAED;;;;GAIG;AACH,MAAa,sBAAuB,SAAQ,6BAA6B;IAIvE,gBAAgB;IAChB,YAAY,IAAoB,EAAE,UAAwC;QACxE,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,YAAY,GAAG,UAAU,CAAC,EAAE,CAAC;IACpC,CAAC;CACF;AATD,wDASC;AAED;;;;GAIG;AACH,MAAa,oBAAqB,SAAQ,6BAA6B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GAAG,UAAU,CAAC,EAAE,CAAC;IACpC,CAAC;CACF;AATD,4DASC;AAED;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,6BAA6B;IAM3E,gBAAgB;IAChB,YACE,IAAoB,EACpB,UAAyE,EAAE;QAE3E,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC;IACrE,CAAC;CACF;AAfD,gEAeC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/errors.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/errors.js new file mode 100644 index 00000000..4ffd5b41 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/errors.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WaitQueueTimeoutError = exports.PoolClearedOnNetworkError = exports.PoolClearedError = 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 indicating a connection pool is currently paused + * @category Error + */ +class PoolClearedError extends error_1.MongoNetworkError { + constructor(pool, message) { + const errorMessage = message + ? message + : `Connection pool for ${pool.address} was cleared because another operation failed with: "${pool.serverError?.message}"`; + super(errorMessage); + this.address = pool.address; + this.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); + } + get name() { + return 'MongoPoolClearedError'; + } +} +exports.PoolClearedError = PoolClearedError; +/** + * An error indicating that a connection pool has been cleared after the monitor for that server timed out. + * @category Error + */ +class PoolClearedOnNetworkError extends PoolClearedError { + constructor(pool) { + super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`); + } + get name() { + return 'PoolClearedOnNetworkError'; + } +} +exports.PoolClearedOnNetworkError = PoolClearedOnNetworkError; +/** + * 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/errors.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/errors.js.map new file mode 100644 index 00000000..9ea0e0ba --- /dev/null +++ b/1_ActivityWatchProducer/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,oCAAgF;AAGhF;;;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,gBAAiB,SAAQ,yBAAiB;IAIrD,YAAY,IAAoB,EAAE,OAAgB;QAChD,MAAM,YAAY,GAAG,OAAO;YAC1B,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,uBAAuB,IAAI,CAAC,OAAO,wDAAwD,IAAI,CAAC,WAAW,EAAE,OAAO,GAAG,CAAC;QAC5H,KAAK,CAAC,YAAY,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,CAAC,aAAa,CAAC,uBAAe,CAAC,mBAAmB,CAAC,CAAC;IAC1D,CAAC;IAED,IAAa,IAAI;QACf,OAAO,uBAAuB,CAAC;IACjC,CAAC;CACF;AAjBD,4CAiBC;AAED;;;GAGG;AACH,MAAa,yBAA0B,SAAQ,gBAAgB;IAC7D,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,EAAE,iBAAiB,IAAI,CAAC,OAAO,4CAA4C,CAAC,CAAC;IACzF,CAAC;IAED,IAAa,IAAI;QACf,OAAO,2BAA2B,CAAC;IACrC,CAAC;CACF;AARD,8DAQC;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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/message_stream.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/message_stream.js new file mode 100644 index 00000000..fe4fafe5 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/message_stream.js @@ -0,0 +1,156 @@ +"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) { + const agreedCompressor = operationDescription.agreedCompressor ?? 'none'; + if (agreedCompressor === '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); + const options = { + agreedCompressor, + zlibCompressionLevel: operationDescription.zlibCompressionLevel ?? 0 + }; + // Compress the message body + (0, compression_1.compress)(options, messageToBeCompressed).then(compressedMessage => { + // 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[agreedCompressor], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }, error => { + operationDescription.cb(error); + }); + } +} +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]; + const sizeOfMessage = buffer.getInt32(); + if (sizeOfMessage == null) { + return callback(); + } + if (sizeOfMessage < 0) { + return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + } + if (sizeOfMessage > stream.maxBsonMessageSize) { + return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`)); + } + if (sizeOfMessage > buffer.length) { + return callback(); + } + 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? + const sizeOfMessage = buffer.getInt32(); + if (sizeOfMessage != null && 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.subarray(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()) { + return processIncomingData(stream, callback); + } + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + return processIncomingData(stream, callback); + } + return callback(); + } + 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).then(messageBody => { + if (messageBody.length !== messageHeader.length) { + return callback(new error_1.MongoDecompressionError('Message body and message header must be the same length')); + } + // 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()) { + return processIncomingData(stream, callback); + } + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + return processIncomingData(stream, callback); + } + return callback(); + }, error => { + return callback(error); + }); +} +//# sourceMappingURL=message_stream.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/message_stream.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/message_stream.js.map new file mode 100644 index 00000000..a027b82a --- /dev/null +++ b/1_ActivityWatchProducer/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,yCAA4F;AAC5F,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;AAuBjC;;;;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,I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,KAAK,kBAAM,CAAC,CAAC,CAAC,iBAAM,CAAC,CAAC,CAAC,mBAAQ,CAAC;IACnE,IAAA,wBAAU,EAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC,IAAI,CAC7C,WAAW,CAAC,EAAE;QACZ,IAAI,WAAW,CAAC,MAAM,KAAK,aAAa,CAAC,MAAM,EAAE;YAC/C,OAAO,QAAQ,CACb,IAAI,+BAAuB,CAAC,yDAAyD,CAAC,CACvF,CAAC;SACH;QAED,uDAAuD;QACvD,yEAAyE;QACzE,8DAA8D;QAC9D,IAAI,sBAAsB,EAAE,EAAE;YAC5B,OAAO,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;SAC9C;QACD,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;QAE9E,IAAI,MAAM,CAAC,MAAM,IAAI,CAAC,EAAE;YACtB,OAAO,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;SAC9C;QACD,OAAO,QAAQ,EAAE,CAAC;IACpB,CAAC,EACD,KAAK,CAAC,EAAE;QACN,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC,CACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/metrics.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/metrics.js new file mode 100644 index 00000000..89c22109 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/metrics.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/metrics.js.map new file mode 100644 index 00000000..270cefe7 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/stream_description.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/stream_description.js new file mode 100644 index 00000000..d2337b76 --- /dev/null +++ b/1_ActivityWatchProducer/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?.logicalSessionTimeoutMinutes; + this.loadBalanced = !!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 => response.compression?.includes(c))[0]; + } + } +} +exports.StreamDescription = StreamDescription; +//# sourceMappingURL=stream_description.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/stream_description.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/stream_description.js.map new file mode 100644 index 00000000..fabbada0 --- /dev/null +++ b/1_ActivityWatchProducer/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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CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,QAAQ,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SACtF;IACH,CAAC;CACF;AArDD,8CAqDC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/compression.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/compression.js new file mode 100644 index 00000000..d2ecc6ed --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/compression.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decompress = exports.compress = exports.uncompressibleCommands = exports.Compressor = void 0; +const util_1 = require("util"); +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 ZSTD_COMPRESSION_LEVEL = 3; +const zlibInflate = (0, util_1.promisify)(zlib.inflate.bind(zlib)); +const zlibDeflate = (0, util_1.promisify)(zlib.deflate.bind(zlib)); +// Facilitate compressing a message using an agreed compressor +async function compress(options, dataToBeCompressed) { + const zlibOptions = {}; + switch (options.agreedCompressor) { + case 'snappy': + if ('kModuleError' in deps_1.Snappy) { + throw deps_1.Snappy['kModuleError']; + } + return deps_1.Snappy.compress(dataToBeCompressed); + case 'zstd': + if ('kModuleError' in deps_1.ZStandard) { + throw deps_1.ZStandard['kModuleError']; + } + return deps_1.ZStandard.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL); + case 'zlib': + if (options.zlibCompressionLevel) { + zlibOptions.level = options.zlibCompressionLevel; + } + return zlibDeflate(dataToBeCompressed, zlibOptions); + default: + throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${options.agreedCompressor} failed to compress`); + } +} +exports.compress = compress; +// Decompress a message using the given compressor +async function decompress(compressorID, compressedData) { + if (compressorID !== exports.Compressor.snappy && + compressorID !== exports.Compressor.zstd && + compressorID !== exports.Compressor.zlib && + compressorID !== exports.Compressor.none) { + 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) { + throw deps_1.Snappy['kModuleError']; + } + return deps_1.Snappy.uncompress(compressedData, { asBuffer: true }); + case exports.Compressor.zstd: + if ('kModuleError' in deps_1.ZStandard) { + throw deps_1.ZStandard['kModuleError']; + } + return deps_1.ZStandard.decompress(compressedData); + case exports.Compressor.zlib: + return zlibInflate(compressedData); + default: + return compressedData; + } +} +exports.decompress = decompress; +//# sourceMappingURL=compression.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map new file mode 100644 index 00000000..bb980454 --- /dev/null +++ b/1_ActivityWatchProducer/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,+BAAiC;AACjC,6BAA6B;AAE7B,+CAAuD;AACvD,qCAA+C;AAC/C,uCAAiF;AAEjF,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,GAAG,CAAC;IA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AsB;IAC3E,IACE,YAAY,KAAK,kBAAU,CAAC,MAAM;QAClC,YAAY,KAAK,kBAAU,CAAC,IAAI;QAChC,YAAY,KAAK,kBAAU,CAAC,IAAI;QAChC,YAAY,KAAK,kBAAU,CAAC,IAAI,EAChC;QACA,MAAM,IAAI,+BAAuB,CAC/B,2FAA2F,YAAY,GAAG,CAC3G,CAAC;KACH;IAED,QAAQ,YAAY,EAAE;QACpB,KAAK,kBAAU,CAAC,MAAM;YACpB,IAAI,cAAc,IAAI,aAAM,EAAE;gBAC5B,MAAM,aAAM,CAAC,cAAc,CAAC,CAAC;aAC9B;YACD,OAAO,aAAM,CAAC,UAAU,CAAC,cAAc,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QAE/D,KAAK,kBAAU,CAAC,IAAI;YAClB,IAAI,cAAc,IAAI,gBAAS,EAAE;gBAC/B,MAAM,gBAAS,CAAC,cAAc,CAAC,CAAC;aACjC;YACD,OAAO,gBAAS,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QAE9C,KAAK,kBAAU,CAAC,IAAI;YAClB,OAAO,WAAW,CAAC,cAAc,CAAC,CAAC;QAErC;YACE,OAAO,cAAc,CAAC;KACzB;AACH,CAAC;AA/BD,gCA+BC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/constants.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/constants.js new file mode 100644 index 00000000..ab10958c --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/constants.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OP_MSG = exports.OP_COMPRESSED = exports.OP_DELETE = 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_DELETE = 2006; +exports.OP_COMPRESSED = 2012; +exports.OP_MSG = 2013; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map new file mode 100644 index 00000000..8974600c --- /dev/null +++ b/1_ActivityWatchProducer/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,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,aAAa,GAAG,IAAI,CAAC;AACrB,QAAA,MAAM,GAAG,IAAI,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/shared.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/shared.js new file mode 100644 index 00000000..1acb4f55 --- /dev/null +++ b/1_ActivityWatchProducer/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?.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/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map new file mode 100644 index 00000000..367981e4 --- /dev/null +++ b/1_ActivityWatchProducer/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,EAAE,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,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AC;AAjBD,8BAiBC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/collection.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/collection.js new file mode 100644 index 00000000..62b9887f --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/collection.js @@ -0,0 +1,576 @@ +"use strict"; +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 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/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +class Collection { + /** + * Create a new Collection instance + * @internal + */ + constructor(db, name, options) { + (0, utils_1.checkCollectionName)(name); + // Internal state + this.s = { + db, + options, + namespace: new utils_1.MongoDBNamespace(db.databaseName, name), + pkFactory: db.options?.pkFactory ?? 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; + } + 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; + } + 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; + } + /** The current index hint for the collection */ + get hint() { + return this.s.collectionHint; + } + set hint(v) { + this.s.collectionHint = (0, utils_1.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 + */ + async insertOne(doc, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + */ + async insertMany(docs, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options ?? { ordered: true }))); + } + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * 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 + * @throws MongoDriverError if operations is not an array + */ + async bulkWrite(operations, options) { + 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 ?? { ordered: true }))); + } + /** + * 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 + */ + async updateOne(filter, update, 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))); + } + /** + * 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 + */ + async replaceOne(filter, replacement, 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))); + } + /** + * 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 + */ + async updateMany(filter, update, 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))); + } + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + async deleteOne(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + async deleteMany(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + */ + async rename(newName, 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 + })); + } + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + async drop(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options)); + } + async findOne(filter = {}, options = {}) { + return this.find(filter, options).limit(-1).batchSize(1).next(); + } + find(filter = {}, options = {}) { + return new find_cursor_1.FindCursor(this.s.db.s.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + */ + async 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))); + } + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + async isCapped(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + * + * @example + * ```ts + * 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' }]) + * ``` + */ + async createIndex(indexSpec, 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))); + } + /** + * 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 + * + * @example + * ```ts + * 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' + * } + * ]); + * ``` + */ + async createIndexes(indexSpecs, options) { + 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, maxTimeMS: undefined }))); + } + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + async dropIndex(indexName, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.DropIndexOperation(this, indexName, { + ...(0, utils_1.resolveOptions)(this, options), + readPreference: read_preference_1.ReadPreference.primary + })); + } + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + async dropIndexes(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.DropIndexesOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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)); + } + /** + * 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 + */ + async indexExists(indexes, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.IndexExistsOperation(this, indexes, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + async indexInformation(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))); + } + /** + * 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 + */ + async estimatedDocumentCount(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))); + } + /** + * 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 + * + * @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 + */ + async countDocuments(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + async distinct(key, filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + async indexes(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.IndexesOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + */ + async stats(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new stats_1.CollStatsOperation(this, options)); + } + /** + * 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 + */ + async findOneAndDelete(filter, 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))); + } + /** + * 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 + */ + async findOneAndReplace(filter, replacement, 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))); + } + /** + * 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 + */ + async findOneAndUpdate(filter, update, 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))); + } + /** + * 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 (!Array.isArray(pipeline)) { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages'); + } + 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 use cases: + * - 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)); + } + /** + * 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 implementation. + * 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 implementation. + * 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)); + } + /** + * 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 + */ + async count(filter = {}, options = {}) { + 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))); + } +} +exports.Collection = Collection; +//# sourceMappingURL=collection.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/collection.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/collection.js.map new file mode 100644 index 00000000..e12827a0 --- /dev/null +++ b/1_ActivityWatchProducer/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;AAYpD,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;AAE3D,sEAAkE;AAClE,gDAAqE;AACrE,8CAAqF;AACrF,gDAO6B;AAC7B,iDAA8D;AAC9D,uDAAuE;AACvE,mCAMiB;AACjB,mDAAoE;AAmCpE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;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;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AC;IAED;;;;;;;;;;;OAWG;IACH,KAAK,CAAC,KAAK,CAAC,SAA0B,EAAE,EAAE,UAAwB,EAAE;QAClE,OAAO,IAAA,oCAAgB,EACrB,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAClB,IAAI,sBAAc,CAChB,wBAAgB,CAAC,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,EAC3C,MAAM,EACN,IAAA,sBAAc,EAAC,IAAI,EAAE,OAAO,CAAC,CAC9B,CACF,CAAC;IACJ,CAAC;CACF;AA/zBD,gCA+zBC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/connection_string.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/connection_string.js new file mode 100644 index 00000000..6cdb2bdf --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/connection_string.js @@ -0,0 +1,1106 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FEATURE_FLAGS = exports.DEFAULT_OPTIONS = exports.OPTIONS = exports.parseOptions = 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 mongo_client_1 = require("./mongo_client"); +const mongo_logger_1 = require("./mongo_logger"); +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 + */ +async function resolveSRVRecord(options) { + if (typeof options.srvHost !== 'string') { + throw new error_1.MongoAPIError('Option "srvHost" must not be empty'); + } + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + throw 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; + const addresses = await dns.promises.resolveSrv(`_${options.srvServiceName}._tcp.${lookupAddress}`); + if (addresses.length === 0) { + throw new error_1.MongoAPIError('No addresses found at host'); + } + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + throw new error_1.MongoAPIError('Server record does not share hostname with parent URI'); + } + } + const hostAddresses = addresses.map(r => utils_1.HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)); + validateLoadBalancedOptions(hostAddresses, options, true); + // Resolve TXT record and add options from there if they exist. + let record; + try { + record = await dns.promises.resolveTxt(lookupAddress); + } + catch (error) { + if (error.code !== 'ENODATA' && error.code !== 'ENOTFOUND') { + throw error; + } + return hostAddresses; + } + if (record.length > 1) { + throw 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))) { + throw new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`); + } + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + throw new error_1.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 && + !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) { + throw new error_1.MongoParseError('Cannot combine replicaSet option with srvMaxHosts'); + } + validateLoadBalancedOptions(hostAddresses, options, true); + return hostAddresses; +} +exports.resolveSRVRecord = resolveSRVRecord; +/** + * Checks if TLS options are valid + * + * @param allOptions - All options provided by user or included in default options map + * @throws MongoAPIError if TLS options are invalid + */ +function checkTLSOptions(allOptions) { + if (!allOptions) + return; + const check = (a, b) => { + if (allOptions.has(a) && allOptions.has(b)) { + throw new error_1.MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`); + } + }; + 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, 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 getIntFromOptions(name, value) { + const parsedInt = (0, utils_1.parseInteger)(value); + if (parsedInt != null) { + return parsedInt; + } + throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} +function getUIntFromOptions(name, value) { + const parsedValue = getIntFromOptions(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; + } + // validate BSONOptions + if (options.useBigInt64 && typeof options.promoteLongs === 'boolean' && !options.promoteLongs) { + throw new error_1.MongoAPIError('Must request either bigint or Long for int64 deserialization'); + } + if (options.useBigInt64 && typeof options.promoteValues === 'boolean' && !options.promoteValues) { + throw new error_1.MongoAPIError('Must request either bigint or Long for int64 deserialization'); + } + 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.'); + } + } + checkTLSOptions(allOptions); + 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; + const isOidc = mongoOptions.credentials.mechanism === providers_1.AuthMechanism.MONGODB_OIDC; + 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 || isOidc) && + 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 + }); + } + if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) { + throw new error_1.MongoMissingCredentialsError(`When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified`); + } + 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'; + } + validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + 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 => urlOptions.get(key) ?? []); + if (proxyOptions.some(options => options.length > 1)) { + throw new error_1.MongoParseError('Proxy options cannot be specified multiple times in the connection string'); + } + const loggerFeatureFlag = Symbol.for('@@mdb.enableMongoLogger'); + mongoOptions[loggerFeatureFlag] = mongoOptions[loggerFeatureFlag] ?? false; + let loggerEnvOptions = {}; + let loggerClientOptions = {}; + if (mongoOptions[loggerFeatureFlag]) { + loggerEnvOptions = { + MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND, + MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY, + MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION, + MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION, + MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL, + MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH, + MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH + }; + loggerClientOptions = { + mongodbLogPath: mongoOptions.mongodbLogPath + }; + } + mongoOptions.mongoLoggerOptions = mongo_logger_1.MongoLogger.resolveOptions(loggerEnvOptions, loggerClientOptions); + return mongoOptions; +} +exports.parseOptions = parseOptions; +/** + * #### Throws if LB mode is true: + * - hosts contains more than one host + * - there is a replicaSet name set + * - directConnection is set + * - if srvMaxHosts is used when an srv connection string is passed in + * + * @throws MongoParseError + */ +function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + throw new error_1.MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + throw new error_1.MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + throw new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + if (isSrv && mongoOptions.srvMaxHosts > 0) { + throw 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 ?? 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] = getIntFromOptions(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUIntFromOptions(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] }) { + 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 = options.credentials?.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 = options.credentials?.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 }) { + // We can have a combination of options passed in the URI and options passed + // as an object to the MongoClient. So we must transform the string options + // as well as merge them together with a potentially provided object. + let mechanismProperties = Object.create(null); + for (const optionValue of values) { + if (typeof optionValue === 'string') { + for (const [key, value] of entriesFromString(optionValue)) { + try { + mechanismProperties[key] = getBoolean(key, value); + } + catch { + mechanismProperties[key] = value; + } + } + } + else { + if (!(0, utils_1.isRecord)(optionValue)) { + throw new error_1.MongoParseError('AuthMechanismProperties must be an object'); + } + mechanismProperties = { ...optionValue }; + } + } + return mongo_credentials_1.MongoCredentials.merge(options.credentials, { + mechanismProperties + }); + } + }, + 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] }) { + if (!(0, utils_1.isRecord)(value)) + throw new error_1.MongoParseError('DriverInfo must be an object'); + return (0, utils_1.makeClientMetadata)({ + driverInfo: value, + appName: options.metadata?.application?.name + }); + } + }, + enableUtf8Validation: { type: 'boolean', default: true }, + family: { + transform({ name, values: [value] }) { + const transformValue = getIntFromOptions(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' + }, + maxConnecting: { + default: 2, + transform({ name, values: [value] }) { + const maxConnecting = getUIntFromOptions(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 = getUIntFromOptions(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}`); + } + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + useBigInt64: { + 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 }) { + 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: options.readPreference?.hedge, + maxStalenessSeconds: options.readPreference?.maxStalenessSeconds + }; + return new read_preference_1.ReadPreference(value, options.readPreference?.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: getUIntFromOptions('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: getUIntFromOptions('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'), + Symbol.for('@@mdb.enableMongoLogger') +]); +//# sourceMappingURL=connection_string.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/connection_string.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/connection_string.js.map new file mode 100644 index 00000000..d0922c1a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/connection_string.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connection_string.js","sourceRoot":"","sources":["../src/connection_string.ts"],"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;IACrC,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC;CACtC,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/constants.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/constants.js new file mode 100644 index 00000000..f3b151f2 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/constants.js @@ -0,0 +1,131 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +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_READY = 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 = exports.APM_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_POOL_READY = 'connectionPoolReady'; +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_READY, + exports.CONNECTION_POOL_CLEARED, + 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 +]); +/** @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/1_ActivityWatchProducer/node_modules/mongodb/lib/constants.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/constants.js.map new file mode 100644 index 00000000..483983ab --- /dev/null +++ b/1_ActivityWatchProducer/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,Q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AA,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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/abstract_cursor.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/abstract_cursor.js new file mode 100644 index 00000000..acf4aa60 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/abstract_cursor.js @@ -0,0 +1,678 @@ +"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 util_1 = require("util"); +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[kId] = null; + this[kDocuments] = new utils_1.List(); + 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 (typeof options.maxAwaitTimeMS === 'number') { + this[kOptions].maxAwaitTimeMS = options.maxAwaitTimeMS; + } + 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] ?? undefined; + } + /** @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() { + return !!this[kClient].topology?.loadBalanced; + } + /** Returns current buffered documents length */ + bufferedCount() { + return this[kDocuments].length; + } + /** Returns current buffered documents */ + readBufferedDocuments(number) { + const bufferedDocs = []; + const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length); + for (let count = 0; count < documentsToRead; count++) { + const document = this[kDocuments].shift(); + if (document != null) { + bufferedDocs.push(document); + } + } + return bufferedDocs; + } + async *[Symbol.asyncIterator]() { + if (this.closed) { + return; + } + try { + while (true) { + const document = await this.next(); + // Intentional strict null check, because users can map cursors to falsey values. + // We allow mapping to all values except for null. + // eslint-disable-next-line no-restricted-syntax + if (document === null) { + if (!this.closed) { + const message = 'Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.'; + await cleanupCursorAsync(this, { needsToEmitClosed: true }).catch(() => null); + throw new error_1.MongoAPIError(message); + } + break; + } + yield document; + if (this[kId] === bson_1.Long.ZERO) { + // Cursor exhausted + break; + } + } + } + finally { + // Only close the cursor if it has not already been closed. This finally clause handles + // the case when a user would break out of a for await of loop early. + if (!this.closed) { + await this.close().catch(() => null); + } + } + } + stream(options) { + if (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); + } + async hasNext() { + if (this[kId] === bson_1.Long.ZERO) { + return false; + } + if (this[kDocuments].length !== 0) { + return true; + } + const doc = await nextAsync(this, true); + if (doc) { + this[kDocuments].unshift(doc); + return true; + } + return false; + } + /** Get the next available document from the cursor, returns null if no more documents are available. */ + async next() { + if (this[kId] === bson_1.Long.ZERO) { + throw new error_1.MongoCursorExhaustedError(); + } + return nextAsync(this, true); + } + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + async tryNext() { + if (this[kId] === bson_1.Long.ZERO) { + throw new error_1.MongoCursorExhaustedError(); + } + return nextAsync(this, false); + } + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + */ + async forEach(iterator) { + if (typeof iterator !== 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + for await (const document of this) { + const result = iterator(document); + if (result === false) { + break; + } + } + } + async close() { + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + await cleanupCursorAsync(this, { needsToEmitClosed }); + } + /** + * 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. + */ + async toArray() { + const array = []; + for await (const document of this) { + array.push(document); + } + return array; + } + /** + * 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** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **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] = null; + this[kDocuments].clear(); + 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) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const getMoreOperation = new get_more_1.GetMoreOperation(this[kNamespace], this[kId], this[kServer], { + ...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], (error, state) => { + if (state) { + const response = state.response; + this[kServer] = state.server; + if (response.cursor) { + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this[kId] = + typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : typeof response.cursor.id === 'bigint' + ? bson_1.Long.fromBigInt(response.cursor.id) + : response.cursor.id; + if (response.cursor.ns) { + this[kNamespace] = (0, utils_1.ns)(response.cursor.ns); + } + this[kDocuments].pushMany(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].push(state.response); + } + } + // the cursor is now initialized, even if an error occurred or it is dead + this[kInitialized] = true; + if (error) { + return cleanupCursor(this, { error }, () => callback(error, undefined)); + } + if (cursorIsDead(this)) { + return cleanupCursor(this, undefined, () => callback()); + } + callback(); + }); + } +} +exports.AbstractCursor = AbstractCursor; +/** @event */ +AbstractCursor.CLOSE = 'close'; +function nextDocument(cursor) { + const doc = cursor[kDocuments].shift(); + if (doc && cursor[kTransform]) { + return cursor[kTransform](doc); + } + return doc; +} +const nextAsync = (0, util_1.promisify)(next); +/** + * @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].length !== 0) { + 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 => { + if (err) + return callback(err); + 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, (error, response) => { + if (response) { + const cursorId = typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : typeof response.cursor.id === 'bigint' + ? bson_1.Long.fromBigInt(response.cursor.id) + : response.cursor.id; + cursor[kDocuments].pushMany(response.cursor.nextBatch); + cursor[kId] = cursorId; + } + if (error || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error }, () => callback(error, 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(); +} +const cleanupCursorAsync = (0, util_1.promisify)(cleanupCursor); +function cleanupCursor(cursor, options, callback) { + 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 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) { + session.endSession({ error }).finally(() => { + callback(); + }); + return; + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } + } + return callback(); + } + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + session.endSession({ error }).finally(() => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + return; + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } + } + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + cursor[kKilled] = true; + if (session.hasEnded) { + return completeCleanup(); + } + (0, execute_operation_1.executeOperation)(cursor[kClient], new kill_cursors_1.KillCursorsOperation(cursorId, cursorNs, server, { session })) + .catch(() => null) + .finally(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().then(() => callback(error), closeError => callback(closeError)); + } + _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 was 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(/operation was interrupted/)) { + return this.push(null); + } + // NOTE: The two above checks on the message of the error will cause a null to be pushed + // to the stream, thus closing the stream before the destroy call happens. This means + // that either of those error messages on a change stream will not get a proper + // 'error' event to be emitted (the error passed to destroy). Change stream resumability + // relies on that error event to be emitted to create its new cursor and thus was not + // working on 4.4 servers because the error emitted on failover was "interrupted at + // shutdown" while on 5.0+ it is "The server is in quiesce mode and will shut down". + // See NODE-4475. + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/abstract_cursor.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/abstract_cursor.js.map new file mode 100644 index 00000000..92f06d09 --- /dev/null +++ b/1_ActivityWatchProducer/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;AAC7C,+BAAiC;AAEjC,kCAA0F;AAC1F,oCASkB;AAElB,gDAAmE;AACnE,uEAAoF;AACpF,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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/aggregation_cursor.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/aggregation_cursor.js new file mode 100644 index 00000000..0673ee92 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/aggregation_cursor.js @@ -0,0 +1,168 @@ +"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 }); + }); + } + /** Execute the explain for the cursor */ + async explain(verbosity) { + return (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + explain: verbosity ?? true + })); + } + 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; + } + /** 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map new file mode 100644 index 00000000..c8e5c7a7 --- /dev/null +++ b/1_ActivityWatchProducer/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,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAElC,IAAI,CAAC,SAAS,CAA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} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/change_stream_cursor.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/change_stream_cursor.js new file mode 100644 index 00000000..471fb6cd --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map new file mode 100644 index 00000000..259e3ded --- /dev/null +++ b/1_ActivityWatchProducer/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,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c,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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/find_cursor.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/find_cursor.js new file mode 100644 index 00000000..f4388561 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/find_cursor.js @@ -0,0 +1,381 @@ +"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) { + this.close().finally(() => callback()); + return; + } + } + 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 + */ + async count(options) { + (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'); + } + return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + ...options + })); + } + /** Execute the explain for the cursor */ + async explain(verbosity) { + return (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + explain: verbosity ?? true + })); + } + /** 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 behavior. + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/find_cursor.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/find_cursor.js.map new file mode 100644 index 00000000..5beda290 --- /dev/null +++ b/1_ActivityWatchProducer/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,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAE7C,uCAAuC;AAC1B,QAAA,KAAK,GAAG;IACnB,UAAU;IACV,aAAa;IACb,iBAAiB;IACjB,WAA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O,IAAI,CAAC;IACd,CAAC;CACF;AAvaD,gCAuaC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_collections_cursor.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_collections_cursor.js new file mode 100644 index 00000000..883474b0 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map new file mode 100644 index 00000000..2f8ecbe3 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_indexes_cursor.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_indexes_cursor.js new file mode 100644 index 00000000..7d62d78f --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map new file mode 100644 index 00000000..f17b5768 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/db.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/db.js new file mode 100644 index 00000000..7e624f46 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/db.js @@ -0,0 +1,349 @@ +"use strict"; +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 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', + 'useBigInt64', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'enableUtf8Validation', + 'promoteValues', + 'compression', + 'retryWrites' +]; +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +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) { + options = 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, + // 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: options?.pkFactory ?? 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 + get options() { + return this.s.options; + } + /** + * Check if a secondary can be used (because the read preference is *not* set to primary) + */ + get secondaryOk() { + return this.s.readPreference?.preference !== 'primary' || false; + } + get readConcern() { + 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() { + if (this.s.readPreference == null) { + return this.s.client.readPreference; + } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + // get the write Concern + get writeConcern() { + return this.s.writeConcern; + } + get namespace() { + 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 + */ + async createCollection(name, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + */ + async command(command, 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)); + } + /** + * 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) { + return new aggregation_cursor_1.AggregationCursor(this.s.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** Return the Admin db instance */ + admin() { + return new admin_1.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, options = {}) { + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + */ + async stats(options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + listCollections(filter = {}, options = {}) { + return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.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 + */ + async renameCollection(fromCollection, toCollection, options) { + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)(this.s.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, { ...options, new_collection: true, readPreference: read_preference_1.ReadPreference.primary })); + } + /** + * 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 + */ + async dropCollection(name, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + async dropDatabase(options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + async collections(options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + */ + async createIndex(name, indexSpec, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + async addUser(username, passwordOrOptions, options) { + options = + options != null && typeof options === 'object' + ? options + : passwordOrOptions != null && typeof passwordOrOptions === 'object' + ? passwordOrOptions + : undefined; + const password = typeof passwordOrOptions === 'string' ? passwordOrOptions : undefined; + return (0, execute_operation_1.executeOperation)(this.s.client, new add_user_1.AddUserOperation(this, username, password, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + async setProfilingLevel(level, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + async profilingLevel(options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + async indexInformation(name, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 use cases: + * - 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)); + } +} +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 +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]}'`); + } +} +//# sourceMappingURL=db.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/db.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/db.js.map new file mode 100644 index 00000000..910ef4fe --- /dev/null +++ b/1_ActivityWatchProducer/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;AAGnE,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,mCAA8F;AAC9F,mDAAoE;AAEpE,qBAAqB;AACrB,MAAM,qBAAqB,GAAG;IAC5B,cAAc;IACd,gBAAgB;IAChB,oBAAoB;IACpB,eAAe;IACf,qBAAqB;IACrB,WAAW;IACX,oBAAoB;IACpB,KAAK;IACL,YAAY;IACZ,iBAAiB;IACjB,aAAa;IACb,kBAAkB;IAClB,iBAAiB;IACjB,aAAa;IACb,gBAAgB;IAChB,cAAc;IACd,YAAY;IACZ,sBAAsB;IACtB,eAAe;IACf,aAAa;IACb,aAAa;CACd,CAAC;AA8BF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAa,EAAE;IAWb;;;;;;OAMG;IACH,YAAY,MAAmB,EAAE,YAAoB,EAAE,OAAmB;QACxE,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAExB,qBAAqB;QACrB,OAAO,GAAG,IAAA,qBAAa,EAAC,OAAO,EAAE,qBAAqB,CAAC,CAAC;QAExD,iCAAiC;QACjC,oBAAoB,CAAC,YAAY,CA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CAAC;;AAnYH,gBAoYC;AAhYe,8BAA2B,GAAG,SAAS,CAAC,2BAA2B,CAAC;AACpE,0BAAuB,GAAG,SAAS,CAAC,uBAAuB,CAAC;AAC5D,4BAAyB,GAAG,SAAS,CAAC,yBAAyB,CAAC;AAChE,yBAAsB,GAAG,SAAS,CAAC,sBAAsB,CAAC;AAC1D,4BAAyB,GAAG,SAAS,CAAC,yBAAyB,CAAC;AAChE,uBAAoB,GAAG,SAAS,CAAC,oBAAoB,CAAC;AA6XtE,kDAAkD;AAClD,6BAA6B;AAC7B,SAAS,oBAAoB,CAAC,YAAoB;IAChD,IAAI,OAAO,YAAY,KAAK,QAAQ;QAClC,MAAM,IAAI,iCAAyB,CAAC,gCAAgC,CAAC,CAAC;IACxE,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC;QAC3B,MAAM,IAAI,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/1_ActivityWatchProducer/node_modules/mongodb/lib/deps.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/deps.js new file mode 100644 index 00000000..58a87178 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/deps.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AutoEncryptionLoggerLevel = exports.aws4 = exports.saslprep = exports.Snappy = exports.getAwsCredentialProvider = exports.ZStandard = exports.Kerberos = void 0; +const error_1 = require("./error"); +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 +function getAwsCredentialProvider() { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const credentialProvider = require('@aws-sdk/credential-providers'); + return credentialProvider; + } + catch { + return makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `@aws-sdk/credential-providers` not found.' + + ' Please install it to enable getting aws credentials via the official sdk.')); + } +} +exports.getAwsCredentialProvider = getAwsCredentialProvider; +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'); +} +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/1_ActivityWatchProducer/node_modules/mongodb/lib/deps.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/deps.js.map new file mode 100644 index 00000000..467de7ce --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/deps.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deps.js","sourceRoot":"","sources":["../src/deps.ts"],"names":[],"mappings":";;;AAIA,mCAAsD;AAItD,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,EAAE,EAAE;YACxB,IAAI,GAAG,KAAK,cAAc,EAAE;gBAC1B,OAAO,KAAK,CAAC;aACd;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QACD,GAAG,EAAE,GAAG,EAAE;YACR,MAAM,KAAK,CAAC;QACd,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAEU,QAAA,QAAQ,GACjB,eAAe,CACb,IAAI,mCAA2B,CAC7B,2FAA2F,CAC5F,CACF,CAAC;AAEJ,IAAI;IACF,wEAAwE;IACxE,gBAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAChC;AAAC,MAAM,GAAE,CAAC,sBAAsB;AAwBtB,QAAA,SAAS,GAClB,eAAe,CACb,IAAI,mCAA2B,CAC7B,4FAA4F,CAC7F,CACF,CAAC;AAEJ,IAAI;IACF,iBAAS,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;CACzC;AAAC,MAAM,GAAE,CAAC,sBAAsB;AAMjC,SAAgB,wBAAwB;IAGtC,IAAI;QACF,wEAAwE;QACxE,MAAM,kBAAkB,GAAG,OAAO,CAAC,+BAA+B,CAAC,CAAC;QACpE,OAAO,kBAAkB,CAAC;KAC3B;IAAC,MAAM;QACN,OAAO,eAAe,CACpB,IAAI,mCAA2B,CAC7B,4DAA4D;YAC1D,4EAA4E,CAC/E,CACF,CAAC;KACH;AACH,CAAC;AAfD,4DAeC;AAgBU,QAAA,MAAM,GAA8D,eAAe,CAC5F,IAAI,mCAA2B,CAC7B,oFAAoF,CACrF,CACF,CAAC;AAEF,IAAI;IACF,wEAAwE;IACxE,cAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CAC5B;AAAC,MAAM,GAAE,CAAC,sBAAsB;AAEtB,QAAA,QAAQ,GACjB,eAAe,CACb,IAAI,mCAA2B,CAC7B,uCAAuC;IACrC,8EAA8E,CACjF,CACF,CAAC;AAEJ,IAAI;IACF,wEAAwE;IACxE,gBAAQ,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CAChC;AAAC,MAAM,GAAE,CAAC,sBAAsB;AA2CtB,QAAA,IAAI,GAAyD,eAAe,CACrF,IAAI,mCAA2B,CAC7B,kFAAkF,CACnF,CACF,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/1_ActivityWatchProducer/node_modules/mongodb/lib/encrypter.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/encrypter.js new file mode 100644 index 00000000..69762c68 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/encrypter.js @@ -0,0 +1,103 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-var-requires */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Encrypter = void 0; +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 + }; + } + 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?.on(eventName, listener); + }); + this.needsConnecting = true; + } + return internalClient; + } + async connectInternalClient() { + // TODO(NODE-4144): Remove new variable for type narrowing + const internalClient = this[kInternalClient]; + if (this.needsConnecting && internalClient != null) { + this.needsConnecting = false; + await internalClient.connect(); + } + } + close(client, force, callback) { + this.autoEncrypter.teardown(!!force, e => { + const internalClient = this[kInternalClient]; + if (internalClient != null && client !== internalClient) { + internalClient.close(force).then(() => callback(), error => callback(error)); + return; + } + callback(e); + }); + } + static checkForMongoCrypt() { + const mongodbClientEncryption = (0, utils_1.getMongoDBClientEncryption)(); + if (mongodbClientEncryption == null) { + 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'); + } + AutoEncrypterClass = mongodbClientEncryption.extension(require('../lib/index')).AutoEncrypter; + } +} +exports.Encrypter = Encrypter; +//# sourceMappingURL=encrypter.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/encrypter.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/encrypter.js.map new file mode 100644 index 00000000..900bb164 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/encrypter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encrypter.js","sourceRoot":"","sources":["../src/encrypter.ts"],"names":[],"mappings":";AAAA,uDAAuD;;;AAEvD,2CAAkD;AAElD,mCAAiF;AACjF,iDAAiE;AACjE,mCAA+D;AAE/D,IAAI,kBAA0F,CAAC;AAE/F,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,2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A0D;QAC1D,MAAM,cAAc,GAAG,IAAI,CAAC,eAAe,CAAC,CAAC;QAC7C,IAAI,IAAI,CAAC,eAAe,IAAI,cAAc,IAAI,IAAI,EAAE;YAClD,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;YAC7B,MAAM,cAAc,CAAC,OAAO,EAAE,CAAC;SAChC;IACH,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,cAAc,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,IAAI,CAC9B,GAAG,EAAE,CAAC,QAAQ,EAAE,EAChB,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;gBACF,OAAO;aACR;YACD,QAAQ,CAAC,CAAC,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,CAAC,kBAAkB;QACvB,MAAM,uBAAuB,GAAG,IAAA,kCAA0B,GAAE,CAAC;QAC7D,IAAI,uBAAuB,IAAI,IAAI,EAAE;YACnC,MAAM,IAAI,mCAA2B,CACnC,8DAA8D;gBAC5D,wEAAwE,CAC3E,CAAC;SACH;QACD,kBAAkB,GAAG,uBAAuB,CAAC,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,CAAC,aAAa,CAAC;IAChG,CAAC;CACF;AA9GD,8BA8GC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/error.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/error.js new file mode 100644 index 00000000..44318b2e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/error.js @@ -0,0 +1,801 @@ +"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', + ResetPool: 'ResetPool', + InterruptInUseConnections: 'InterruptInUseConnections', + NoWritesPerformed: 'NoWritesPerformed' +}); +/** + * @public + * @category Error + * + * @privateRemarks + * mongodb-client-encryption 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); + this.cause = 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 + * mongodb-client-encryption 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) { + if (reason && reason.error) { + super(reason.error.message || reason.error); + } + else { + super(message); + } + if (reason) { + this.reason = reason; + } + this.code = reason.error?.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) { + // 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(error.result?.code ?? error.code ?? 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/1_ActivityWatchProducer/node_modules/mongodb/lib/error.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/error.js.map new file mode 100644 index 00000000..5eb67948 --- /dev/null +++ b/1_ActivityWatchProducer/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,C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ules/mongodb/lib/explain.js new file mode 100644 index 00000000..4fb841e9 --- /dev/null +++ b/1_ActivityWatchProducer/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?.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/1_ActivityWatchProducer/node_modules/mongodb/lib/explain.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/explain.js.map new file mode 100644 index 00000000..8b114f11 --- /dev/null +++ b/1_ActivityWatchProducer/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,OAAO,EAAE,OAAO,IAAI,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/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/download.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/download.js new file mode 100644 index 00000000..f5c5c1f9 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/download.js @@ -0,0 +1,313 @@ +"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 { + /** + * @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 + * @internal + */ + 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. + */ + async abort() { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + try { + await this.s.cursor.close(); + } + finally { + this.emit(GridFSBucketReadStream.CLOSE); + } + } + else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); + } + } + } +} +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; + const handleReadResult = ({ error, doc }) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + stream.s.cursor?.close().then(() => { + stream.emit(GridFSBucketReadStream.CLOSE); + }, error => { + stream.emit(GridFSBucketReadStream.ERROR, error); + }); + 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; + }; + stream.s.cursor.next().then(doc => handleReadResult({ error: null, doc }), error => handleReadResult({ error, doc: null })); +} +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; + } + const handleReadResult = ({ 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; + }; + stream.s.files.findOne(stream.s.filter, findOneOptions).then(doc => handleReadResult({ error: null, doc }), error => handleReadResult({ error, doc: null })); +} +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/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/download.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/download.js.map new file mode 100644 index 00000000..57638a06 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/download.js.map @@ -0,0 +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,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/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/index.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/index.js new file mode 100644 index 00000000..6110d8d0 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/index.js @@ -0,0 +1,128 @@ +"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 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); + } + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + async delete(id) { + const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id }); + // Delete orphaned chunks before returning FileNotFound + await this.s._chunksCollection.deleteMany({ files_id: id }); + if (deletedCount === 0) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + throw new error_1.MongoRuntimeError(`File not found for id ${id}`); + } + } + /** Convenience wrapper around find on the files collection */ + find(filter = {}, 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 }); + } + /** + * 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 + */ + async rename(id, filename) { + const filter = { _id: id }; + const update = { $set: { filename } }; + const { matchedCount } = await this.s._filesCollection.updateOne(filter, update); + if (matchedCount === 0) { + throw new error_1.MongoRuntimeError(`File with id ${id} not found`); + } + } + /** Removes this bucket's files collection, followed by its chunks collection. */ + async drop() { + await this.s._filesCollection.drop(); + await this.s._chunksCollection.drop(); + } +} +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/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/index.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/index.js.map new file mode 100644 index 00000000..9c65fd3c --- /dev/null +++ b/1_ActivityWatchProducer/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;AAC7C,gDAA2D;AAG3D,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;YAC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,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,EAAE,CAAC;QACtC,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjF,IAAI,YAAY,KAAK,CAAC,EAAE;YACtB,MAAM,IAAI,yBAAiB,CAAC,gBAAgB,EAAE,YAAY,CAAC,CAAC;SAC7D;IACH,CAAC;IAED,iFAAiF;IACjF,KAAK,CAAC,IAAI;QACR,MAAM,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;QACrC,MAAM,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,EAAE,CAAC;IACxC,CAAC;;AAnJH,oCAoJC;AAhJC;;;;;;;GAOG;AACa,kBAAK,GAAG,OAAgB,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/upload.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/upload.js new file mode 100644 index 00000000..b0cd641c --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/upload.js @@ -0,0 +1,342 @@ +"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 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 { + /** + * @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. + * @internal + */ + constructor(bucket, filename, options) { + super(); + options = 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).then(() => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }, () => null); + } + } + 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)); + } + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + */ + async abort() { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new error_1.MongoAPIError('Cannot abort a stream that has already completed'); + } + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new error_1.MongoAPIError('Cannot call abort() on a stream twice'); + } + this.state.aborted = true; + await this.chunks.deleteMany({ files_id: this.id }); + } + 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 + }; +} +async function checkChunksIndex(stream) { + const index = { files_id: 1, n: 1 }; + let indexes; + try { + indexes = await stream.chunks.listIndexes().toArray(); + } + catch (error) { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } + else { + throw error; + } + } + const hasChunksIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + return true; + } + return false; + }); + if (!hasChunksIndex) { + const writeConcernOptions = getWriteOptions(stream); + await stream.chunks.createIndex(index, { + ...writeConcernOptions, + background: true, + unique: true + }); + } +} +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)).then(() => { + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }, error => { + return __handleError(stream, error, callback); + }); + return true; + } + return false; +} +async function checkIndexes(stream) { + const doc = await stream.files.findOne({}, { projection: { _id: 1 } }); + if (doc != null) { + // If at least one document exists assume the collection has the required index + return; + } + const index = { filename: 1, uploadDate: 1 }; + let indexes; + try { + indexes = await stream.files.listIndexes().toArray(); + } + catch (error) { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } + else { + throw error; + } + } + const hasFileIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + return true; + } + return false; + }); + if (!hasFileIndex) { + await stream.files.createIndex(index, { background: false }); + } + await checkChunksIndex(stream); +} +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)).then(() => { + --stream.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }, error => { + return __handleError(stream, error); + }); + 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)).then(() => { + --stream.state.outstandingRequests; + checkDone(stream); + }, error => { + return __handleError(stream, error); + }); + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/upload.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/gridfs/upload.js.map new file mode 100644 index 00000000..d7955f8d --- /dev/null +++ b/1_ActivityWatchProducer/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;AAGpF,sDAAkD;AA0BlD;;;;;GAKG;AACH,MAAa,uBAAwB,SAAQ,iBAAQ;IA+BnD;;;;;OAKG;IACH,YAAY,MAAoB,EAAE,QAAgB,EAAE,OAAwC;QAC1F,KAAK,EAAE,CAAC;QAER,OAAO,GAAG,OAAO,IAAI,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,OAAO,CAAC,cAAc,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC;QACrF,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACpD,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;QAChB,IAAI,CAAC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,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC,CACF,CAAC;IACF,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/1_ActivityWatchProducer/node_modules/mongodb/lib/index.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/index.js new file mode 100644 index 00000000..7c167bea --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/index.js @@ -0,0 +1,161 @@ +"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.ChangeStreamCursor = exports.MongoBulkWriteError = exports.Timestamp = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.Double = exports.Decimal128 = exports.DBRef = exports.Code = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.Binary = exports.BSON = void 0; +exports.ServerDescriptionChangedEvent = exports.ServerClosedEvent = exports.ConnectionReadyEvent = exports.ConnectionPoolReadyEvent = 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.ServerApiVersion = exports.ExplainVerbosity = exports.MongoErrorLabel = exports.AutoEncryptionLoggerLevel = exports.CURSOR_FLAGS = exports.Compressor = exports.AuthMechanism = exports.GSSAPICanonicalizationValue = exports.BatchType = exports.UnorderedBulkOperation = exports.OrderedBulkOperation = exports.MongoClient = exports.ListIndexesCursor = exports.ListCollectionsCursor = exports.GridFSBucketWriteStream = exports.GridFSBucketReadStream = exports.GridFSBucket = exports.FindCursor = exports.Db = exports.Collection = exports.ClientSession = exports.ChangeStream = exports.CancellationToken = exports.AggregationCursor = void 0; +exports.SrvPollingEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.TopologyClosedEvent = exports.ServerOpeningEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.ServerHeartbeatFailedEvent = void 0; +const admin_1 = require("./admin"); +Object.defineProperty(exports, "Admin", { enumerable: true, get: function () { return admin_1.Admin; } }); +const ordered_1 = require("./bulk/ordered"); +Object.defineProperty(exports, "OrderedBulkOperation", { enumerable: true, get: function () { return ordered_1.OrderedBulkOperation; } }); +const unordered_1 = require("./bulk/unordered"); +Object.defineProperty(exports, "UnorderedBulkOperation", { enumerable: true, get: function () { return unordered_1.UnorderedBulkOperation; } }); +const change_stream_1 = require("./change_stream"); +Object.defineProperty(exports, "ChangeStream", { enumerable: true, get: function () { return change_stream_1.ChangeStream; } }); +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 download_1 = require("./gridfs/download"); +Object.defineProperty(exports, "GridFSBucketReadStream", { enumerable: true, get: function () { return download_1.GridFSBucketReadStream; } }); +const upload_1 = require("./gridfs/upload"); +Object.defineProperty(exports, "GridFSBucketWriteStream", { enumerable: true, get: function () { return upload_1.GridFSBucketWriteStream; } }); +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 sessions_1 = require("./sessions"); +Object.defineProperty(exports, "ClientSession", { enumerable: true, get: function () { return sessions_1.ClientSession; } }); +/** @public */ +var bson_1 = require("./bson"); +Object.defineProperty(exports, "BSON", { enumerable: true, get: function () { return bson_1.BSON; } }); +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, "BSONType", { enumerable: true, get: function () { return bson_2.BSONType; } }); +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, "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 common_1 = require("./bulk/common"); +Object.defineProperty(exports, "MongoBulkWriteError", { enumerable: true, get: function () { return common_1.MongoBulkWriteError; } }); +var change_stream_cursor_1 = require("./cursor/change_stream_cursor"); +Object.defineProperty(exports, "ChangeStreamCursor", { enumerable: true, get: function () { return change_stream_cursor_1.ChangeStreamCursor; } }); +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 mongo_client_2 = require("./mongo_client"); +Object.defineProperty(exports, "ServerApiVersion", { enumerable: true, get: function () { return mongo_client_2.ServerApiVersion; } }); +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, "ConnectionPoolReadyEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolReadyEvent; } }); +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/1_ActivityWatchProducer/node_modules/mongodb/lib/index.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/index.js.map new file mode 100644 index 00000000..618ebe9f --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,mCAAgC;AA0E9B,sFA1EO,aAAK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ityWatchProducer/node_modules/mongodb/lib/mongo_client.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 00000000..f9981f96 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,292 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoClient = exports.ServerApiVersion = void 0; +const util_1 = require("util"); +const bson_1 = require("./bson"); +const change_stream_1 = require("./change_stream"); +const connection_string_1 = require("./connection_string"); +const constants_1 = require("./constants"); +const db_1 = require("./db"); +const error_1 = require("./error"); +const mongo_logger_1 = require("./mongo_logger"); +const mongo_types_1 = require("./mongo_types"); +const read_preference_1 = require("./read_preference"); +const server_selection_1 = require("./sdam/server_selection"); +const topology_1 = require("./sdam/topology"); +const sessions_1 = require("./sessions"); +const utils_1 = require("./utils"); +/** @public */ +exports.ServerApiVersion = Object.freeze({ + v1: '1' +}); +/** @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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +class MongoClient extends mongo_types_1.TypedEventEmitter { + constructor(url, options) { + super(); + this[kOptions] = (0, connection_string_1.parseOptions)(url, this, options); + this.mongoLogger = new mongo_logger_1.MongoLogger(this[kOptions].mongoLoggerOptions); + // 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 isMongoClient() { + return true; + } + }; + } + get options() { + return Object.freeze({ ...this[kOptions] }); + } + get serverApi() { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); + } + /** + * Intended for APM use only + * @internal + */ + get monitorCommands() { + return this[kOptions].monitorCommands; + } + set monitorCommands(value) { + this[kOptions].monitorCommands = value; + } + 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; + } + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + async connect() { + if (this.topology && this.topology.isConnected()) { + return this; + } + const options = this[kOptions]; + if (typeof options.srvHost === 'string') { + const hosts = await (0, connection_string_1.resolveSRVRecord)(options); + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + } + 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 + this.topology = topology; + topology.client = this; + topology.once(topology_1.Topology.OPEN, () => this.emit('open', this)); + for (const event of constants_1.MONGO_CLIENT_EVENTS) { + topology.on(event, (...args) => this.emit(event, ...args)); + } + const topologyConnect = async () => { + try { + await (0, util_1.promisify)(callback => topology.connect(options, callback))(); + } + catch (error) { + topology.close({ force: true }); + throw error; + } + }; + if (this.autoEncrypter) { + const initAutoEncrypter = (0, util_1.promisify)(callback => this.autoEncrypter?.init(callback)); + await initAutoEncrypter(); + await topologyConnect(); + await options.encrypter.connectInternalClient(); + } + else { + await topologyConnect(); + } + return this; + } + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + async close(force = false) { + // There's no way to set hasBeenClosed back to false + Object.defineProperty(this.s, 'hasBeenClosed', { + value: true, + enumerable: true, + configurable: false, + writable: false + }); + const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession()); + this.s.activeSessions.clear(); + await Promise.all(activeSessionEnds); + if (this.topology == null) { + return; + } + // If we would attempt to select a server and get nothing back we short circuit + // to avoid the server selection timeout. + const selector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.primaryPreferred); + const topologyDescription = this.topology.description; + const serverDescriptions = Array.from(topologyDescription.servers.values()); + const servers = selector(topologyDescription, serverDescriptions); + if (servers.length !== 0) { + const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); + if (endSessions.length !== 0) { + await this.db('admin') + .command({ endSessions }, { readPreference: read_preference_1.ReadPreference.primaryPreferred, noResponse: true }) + .catch(() => null); // outcome does not matter + } + } + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + await 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(); + }); + }); + } + /** + * 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 ?? {}; + // 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; + } + /** + * 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 async connect(url, options) { + const client = new this(url, options); + return client.connect(); + } + /** Starts a new session on the server */ + 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); + }); + return session; + } + async 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); + try { + await withSessionCallback(session); + } + finally { + try { + await session.endSession(); + } + catch { + // We are not concerned with errors from endSession() + } + } + } + /** + * 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 use cases: + * - 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)); + } +} +exports.MongoClient = MongoClient; +//# sourceMappingURL=mongo_client.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_client.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_client.js.map new file mode 100644 index 00000000..875f5253 --- /dev/null +++ b/1_ActivityWatchProducer/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":";;;AAEA,+BAAiC;AAEjC,iCAA4E;AAC5E,mDAA0F;AAM1F,2DAAqE;AACrE,2CAAkD;AAClD,6BAAqC;AAGrC,mCA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CAAC,OAAO,kBAAkB,KAAK,QAAQ,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,CAAC;SACtE,CAAC;QAEF,MAAM,mBAAmB,GACvB,OAAO,kBAAkB,KAAK,UAAU,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,QAAQ,CAAC;QAE3E,IAAI,mBAAmB,IAAI,IAAI,EAAE;YAC/B,MAAM,IAAI,iCAAyB,CAAC,qCAAqC,CAAC,CAAC;SAC5E;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QAE3C,IAAI;YACF,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;SACpC;gBAAS;YACR,IAAI;gBACF,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC;aAC5B;YAAC,MAAM;gBACN,qDAAqD;aACtD;SACF;IACH,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;CACF;AAlUD,kCAkUC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_logger.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_logger.js new file mode 100644 index 00000000..7a133f68 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_logger.js @@ -0,0 +1,113 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoLogger = exports.MongoLoggableComponent = exports.SeverityLevel = void 0; +const stream_1 = require("stream"); +const utils_1 = require("./utils"); +/** @internal */ +exports.SeverityLevel = Object.freeze({ + EMERGENCY: 'emergency', + ALERT: 'alert', + CRITICAL: 'critical', + ERROR: 'error', + WARNING: 'warn', + NOTICE: 'notice', + INFORMATIONAL: 'info', + DEBUG: 'debug', + TRACE: 'trace', + OFF: 'off' +}); +/** @internal */ +exports.MongoLoggableComponent = Object.freeze({ + COMMAND: 'command', + TOPOLOGY: 'topology', + SERVER_SELECTION: 'serverSelection', + CONNECTION: 'connection' +}); +/** + * Parses a string as one of SeverityLevel + * + * @param s - the value to be parsed + * @returns one of SeverityLevel if value can be parsed as such, otherwise null + */ +function parseSeverityFromString(s) { + const validSeverities = Object.values(exports.SeverityLevel); + const lowerSeverity = s?.toLowerCase(); + if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { + return lowerSeverity; + } + return null; +} +/** + * resolves the MONGODB_LOG_PATH and mongodbLogPath options from the environment and the + * mongo client options respectively. + * + * @returns the Writable stream to write logs to + */ +function resolveLogPath({ MONGODB_LOG_PATH }, { mongodbLogPath }) { + const isValidLogDestinationString = (destination) => ['stdout', 'stderr'].includes(destination.toLowerCase()); + if (typeof mongodbLogPath === 'string' && isValidLogDestinationString(mongodbLogPath)) { + return mongodbLogPath.toLowerCase() === 'stderr' ? process.stderr : process.stdout; + } + // TODO(NODE-4813): check for minimal interface instead of instanceof Writable + if (typeof mongodbLogPath === 'object' && mongodbLogPath instanceof stream_1.Writable) { + return mongodbLogPath; + } + if (typeof MONGODB_LOG_PATH === 'string' && isValidLogDestinationString(MONGODB_LOG_PATH)) { + return MONGODB_LOG_PATH.toLowerCase() === 'stderr' ? process.stderr : process.stdout; + } + return process.stderr; +} +/** @internal */ +class MongoLogger { + constructor(options) { + this.componentSeverities = options.componentSeverities; + this.maxDocumentLength = options.maxDocumentLength; + this.logDestination = options.logDestination; + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + /* eslint-disable @typescript-eslint/no-empty-function */ + emergency(component, message) { } + alert(component, message) { } + critical(component, message) { } + error(component, message) { } + warn(component, message) { } + notice(component, message) { } + info(component, message) { } + debug(component, message) { } + trace(component, message) { } + /** + * Merges options set through environment variables and the MongoClient, preferring environment + * variables when both are set, and substituting defaults for values not set. Options set in + * constructor take precedence over both environment variables and MongoClient options. + * + * @remarks + * When parsing component severity levels, invalid values are treated as unset and replaced with + * the default severity. + * + * @param envOptions - options set for the logger from the environment + * @param clientOptions - options set for the logger in the MongoClient options + * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger + */ + static resolveOptions(envOptions, clientOptions) { + // client options take precedence over env options + const combinedOptions = { + ...envOptions, + ...clientOptions, + mongodbLogPath: resolveLogPath(envOptions, clientOptions) + }; + const defaultSeverity = parseSeverityFromString(combinedOptions.MONGODB_LOG_ALL) ?? exports.SeverityLevel.OFF; + return { + componentSeverities: { + command: parseSeverityFromString(combinedOptions.MONGODB_LOG_COMMAND) ?? defaultSeverity, + topology: parseSeverityFromString(combinedOptions.MONGODB_LOG_TOPOLOGY) ?? defaultSeverity, + serverSelection: parseSeverityFromString(combinedOptions.MONGODB_LOG_SERVER_SELECTION) ?? defaultSeverity, + connection: parseSeverityFromString(combinedOptions.MONGODB_LOG_CONNECTION) ?? defaultSeverity, + default: defaultSeverity + }, + maxDocumentLength: (0, utils_1.parseUnsignedInteger)(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1000, + logDestination: combinedOptions.mongodbLogPath + }; + } +} +exports.MongoLogger = MongoLogger; +//# sourceMappingURL=mongo_logger.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_logger.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_logger.js.map new file mode 100644 index 00000000..d3ca2868 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_logger.js","sourceRoot":"","sources":["../src/mongo_logger.ts"],"names":[],"mappings":";;;AAAA,mCAAk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AM,eAAe,GAAG;YACtB,GAAG,UAAU;YACb,GAAG,aAAa;YAChB,cAAc,EAAE,cAAc,CAAC,UAAU,EAAE,aAAa,CAAC;SAC1D,CAAC;QACF,MAAM,eAAe,GACnB,uBAAuB,CAAC,eAAe,CAAC,eAAe,CAAC,IAAI,qBAAa,CAAC,GAAG,CAAC;QAEhF,OAAO;YACL,mBAAmB,EAAE;gBACnB,OAAO,EAAE,uBAAuB,CAAC,eAAe,CAAC,mBAAmB,CAAC,IAAI,eAAe;gBACxF,QAAQ,EAAE,uBAAuB,CAAC,eAAe,CAAC,oBAAoB,CAAC,IAAI,eAAe;gBAC1F,eAAe,EACb,uBAAuB,CAAC,eAAe,CAAC,4BAA4B,CAAC,IAAI,eAAe;gBAC1F,UAAU,EACR,uBAAuB,CAAC,eAAe,CAAC,sBAAsB,CAAC,IAAI,eAAe;gBACpF,OAAO,EAAE,eAAe;aACzB;YACD,iBAAiB,EACf,IAAA,4BAAoB,EAAC,eAAe,CAAC,+BAA+B,CAAC,IAAI,IAAI;YAC/E,cAAc,EAAE,eAAe,CAAC,cAAc;SAC/C,CAAC;IACJ,CAAC;CACF;AAxED,kCAwEC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_types.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_types.js new file mode 100644 index 00000000..892f14d4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_types.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CancellationToken = exports.TypedEventEmitter = void 0; +const events_1 = require("events"); +/** + * 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/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_types.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/mongo_types.js.map new file mode 100644 index 00000000..c7fcc37e --- /dev/null +++ b/1_ActivityWatchProducer/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;AA0YtC;;;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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/add_user.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/add_user.js new file mode 100644 index 00000000..59876a31 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/add_user.js @@ -0,0 +1,74 @@ +"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 ?? {}; + } + 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 + // v5 removed the digestPassword option from AddUserOptions but we still want to throw + // an error when digestPassword is provided. + if ('digestPassword' in options && 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/add_user.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/add_user.js.map new file mode 100644 index 00000000..d96b6912 --- /dev/null +++ b/1_ActivityWatchProducer/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;AAqBpD,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,IAAI,EAAE,CAAC;IAC/B,CAAC;IAEQ,OAA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IAAI,CAAC,CAAC;QAEhE,IAAI,YAAY,GAAG,QAAQ,CAAC;QAE5B,IAAI,CAAC,cAAc,EAAE;YACnB,yBAAyB;YACzB,MAAM,GAAG,GAAG,MAAM,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC;YACrC,wCAAwC;YACxC,GAAG,CAAC,MAAM,CAAC,GAAG,QAAQ,UAAU,QAAQ,EAAE,CAAC,CAAC;YAC5C,YAAY,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SAClC;QAED,+BAA+B;QAC/B,MAAM,OAAO,GAAa;YACxB,UAAU,EAAE,QAAQ;YACpB,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,EAAE;YACpC,KAAK,EAAE,KAAK;YACZ,cAAc;SACf,CAAC;QAEF,cAAc;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;AApFD,4CAoFC;AAED,IAAA,yBAAa,EAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/aggregate.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/aggregate.js new file mode 100644 index 00000000..8224f5f4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/aggregate.js @@ -0,0 +1,91 @@ +"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 }; + // 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?.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; + } + else { + delete this.options.writeConcern; + } + if (this.explain && this.writeConcern) { + throw new error_1.MongoInvalidArgumentError('Option "explain" cannot be used on an aggregate call with writeConcern'); + } + if (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 (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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/aggregate.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/aggregate.js.map new file mode 100644 index 00000000..f9a3ebbe --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/aggregate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aggregate.js","sourceRoot":"","sources":["../../src/operations/aggregate.ts"],"names":[],"mappings":";;;AACA,oCAAqD;AAGrD,oCAAsE;AACtE,uCAAwF;AACxF,2CAA0D;AAE1D,gBAAgB;AACH,QAAA,uBAAuB,GAAG,CAAU,CAAC;AAClD,MAAM,0CAA0C,GAAG,CAAU,CAAC;AA0B9D,gBAAgB;AAChB,MAAa,kBAAiC,SAAQ,0BAAmB;IAMvE,YAAY,EAAoB,EAAE,QAAoB,EAAE,OAA0B;QAChF,KAAK,CAAC,SAAS,EAAE,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAEhD,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,CAAC;QAE9B,gGAAgG;QAChG,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC,UAAU,IAAI,+BAAuB,CAAC;QAEvD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,qEAAqE;QACrE,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,IAAI,OAAO,OAAO,EAAE,GAAG,KAAK,QAAQ,EAAE;YACpC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,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WAAW;IAClB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/bulk_write.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/bulk_write.js new file mode 100644 index 00000000..77299e8d --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/bulk_write.js @@ -0,0 +1,36 @@ +"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 }).then(result => callback(undefined, result), error => callback(error)); + } +} +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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/bulk_write.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/bulk_write.js.map new file mode 100644 index 00000000..08366dc8 --- /dev/null +++ b/1_ActivityWatchProducer/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,UAA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AkB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/collections.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/collections.js new file mode 100644 index 00000000..0c1fdf58 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/collections.js @@ -0,0 +1,32 @@ +"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) { + // Let's get the collection names + this.db + .listCollections({}, { ...this.options, nameOnly: true, readPreference: this.readPreference, session }) + .toArray() + .then(documents => { + const collections = []; + for (const { name } of documents) { + if (!name.includes('$')) { + // Filter collections removing any illegal ones + collections.push(new collection_1.Collection(this.db, name, this.db.s.options)); + } + } + // Return the collection objects + callback(undefined, collections); + }, error => callback(error)); + } +} +exports.CollectionsOperation = CollectionsOperation; +//# sourceMappingURL=collections.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/collections.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/collections.js.map new file mode 100644 index 00000000..fda34a0f --- /dev/null +++ b/1_ActivityWatchProducer/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,iCAAiC;QACjC,IAAI,CAAC,EAAE;aACJ,eAAe,CACd,EAAE,EACF,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAClF;aACA,OAAO,EAAE;aACT,IAAI,CACH,SAAS,CAAC,EAAE;YACV,MAAM,WAAW,GAAG,EAAE,CAAC;YACvB,KAAK,MAAM,EAAE,IAAI,EAAE,IAAI,SAAS,EAAE;gBAChC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;oBACvB,+CAA+C;oBAC/C,WAAW,CAAC,IAAI,CAAC,IAAI,uBAAU,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;iBACpE;aACF;YACD,gCAAgC;YAChC,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;QACnC,CAAC,EACD,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;IACN,CAAC;CACF;AArCD,oDAqCC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/command.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/command.js new file mode 100644 index 00000000..b51990e3 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/command.js @@ -0,0 +1,78 @@ +"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"); +/** @internal */ +class CommandOperation extends operation_1.AbstractOperation { + constructor(parent, options) { + 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 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); + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + this.explain = explain_1.Explain.fromOptions(options); + } + else if (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 (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + 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) { + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/command.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/command.js.map new file mode 100644 index 00000000..9d6c2584 --- /dev/null +++ b/1_ActivityWatchProducer/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,oCAAqD;AACrD,wCAAqD;AACrD,kDAA8C;AAG9C,+DAA4E;AAE5E,oCAMkB;AAClB,oDAAqE;AAErE,2CAA0E;AAoD1E,gBAAgB;AAChB,MAAsB,gBAAoB,SAAQ,6BAAoB;IAMpE,YAAY,MAAwB,EAAE,OAAiC;QACrE,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAE7B,kFAAkF;QAClF,kFAAkF;QAClF,qBAAqB;QACrB,MAAM,cAAc,GAAG,OAAO,EAAE,MAAM,IAAI,OAAO,EAAE,MAAM,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,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC,cAAc,CAAC,MAAM,CAAC;gBAC3C,CAAC,CAAC,IAAI,wBAAgB,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;SAC3C;QAED,IAAI,CAAC,WAAW,GAAG,0BAAW,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QACpD,IAAI,CAAC,YAAY,GAAG,4BAAY,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;QAEtD,IAAI,IAAI,CAAC,SAAS,CAAC,kBAAM,CAAC,WAAW,CAAC,EAAE;YACtC,IAAI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AE,EAAE,YAAY,EAAE,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC;SACzD;QAED,IACE,OAAO,CAAC,SAAS;YACjB,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ;YACrC,CAAC,IAAI,CAAC,SAAS,CAAC,kBAAM,CAAC,cAAc,CAAC,EACtC;YACA,MAAM,CAAC,MAAM,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC;SACtD;QAED,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YACzC,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SACnC;QAED,IAAI,IAAI,CAAC,SAAS,CAAC,kBAAM,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,OAAO,EAAE;YACtD,GAAG,GAAG,IAAA,2BAAmB,EAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;SAC9C;QAED,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAClD,CAAC;CACF;AAxFD,4CAwFC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/common_functions.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/common_functions.js new file mode 100644 index 00000000..e07d309a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/common_functions.js @@ -0,0 +1,69 @@ +"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() + .then(indexes => { + if (!Array.isArray(indexes)) + return callback(undefined, []); + if (full) + return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }, error => callback(error)); +} +exports.indexInformation = indexInformation; +function prepareDocs(coll, docs, options) { + 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; + }); +} +exports.prepareDocs = prepareDocs; +//# sourceMappingURL=common_functions.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/common_functions.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/common_functions.js.map new file mode 100644 index 00000000..a9e7d5a3 --- /dev/null +++ b/1_ActivityWatchProducer/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,C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AAC,CAAC;QAC5D,IAAI,IAAI;YAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAC9C,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC,CAAC;IAC/C,CAAC,EACD,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;AACN,CAAC;AArDD,4CAqDC;AAED,SAAgB,WAAW,CACzB,IAAgB,EAChB,IAAgB,EAChB,OAA0C;IAE1C,MAAM,mBAAmB,GACvB,OAAO,OAAO,CAAC,mBAAmB,KAAK,SAAS;QAC9C,CAAC,CAAC,OAAO,CAAC,mBAAmB;QAC7B,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,OAAO,EAAE,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count.js new file mode 100644 index 00000000..706dde67 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count.js.map new file mode 100644 index 00000000..aeee5fd7 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count_documents.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count_documents.js new file mode 100644 index 00000000..562c9c06 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count_documents.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/count_documents.js.map new file mode 100644 index 00000000..bc1ce7b6 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/create_collection.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/create_collection.js new file mode 100644 index 00000000..9345dfa5 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/create_collection.js @@ -0,0 +1,101 @@ +"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', + 'useBigInt64', + '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 () => { + const db = this.db; + const name = this.name; + const options = this.options; + const encryptedFields = 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 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/create_collection.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/create_collection.js.map new file mode 100644 index 00000000..1b018310 --- /dev/null +++ b/1_ActivityWatchProducer/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,aAAa;IACb,cAAc;IACd,eAAe;IACf,gBAAgB;IAChB,YAAY;IACZ,oBAAoB;IACpB,iBAAiB;IACjB,sBAAsB;CACvB,CAAC,CAAC;AAmEH,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,CA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AO,EAAE;gBACvB,IACG,OAAe,CAAC,CAAC,CAAC,IAAI,IAAI;oBAC3B,OAAQ,OAAe,CAAC,CAAC,CAAC,KAAK,UAAU;oBACzC,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,EAC9B;oBACA,GAAG,CAAC,CAAC,CAAC,GAAI,OAAe,CAAC,CAAC,CAAC,CAAC;iBAC9B;aACF;YAED,qCAAqC;YACrC,KAAK,CAAC,cAAc,CAAC,MAAM,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/delete.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/delete.js new file mode 100644 index 00000000..0164a261 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/delete.js @@ -0,0 +1,119 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeDeleteStatement = exports.DeleteManyOperation = exports.DeleteOneOperation = exports.DeleteOperation = void 0; +const error_1 = require("../error"); +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) { + const options = this.options ?? {}; + 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; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + callback(new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`)); + 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) => { + 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: this.writeConcern?.w !== 0 ?? 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) => { + 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: this.writeConcern?.w !== 0 ?? 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.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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/delete.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/delete.js.map new file mode 100644 index 00000000..d1133e44 --- /dev/null +++ b/1_ActivityWatchProducer/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;AAKrE,uCAAwF;AACxF,2CAA0D;AAkC1D,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAA8B;IAIjE,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,CAAC,MAAc,EAAE,OAAkC,EAAE,QAAkB;QACrF,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;QACnC,MAAM,OAAO,GAAG,OAAO,OAAO,CAAC,O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BAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,WAAW;IAClB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/distinct.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/distinct.js new file mode 100644 index 00000000..13a06dee --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/distinct.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DistinctOperation = void 0; +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 ?? {}; + 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; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (typeof options.comment !== 'undefined') { + cmd.comment = options.comment; + } + // 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); + } + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/distinct.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/distinct.js.map new file mode 100644 index 00000000..ef191acf --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/distinct.js.map @@ -0,0 +1 @@ +{"version":3,"file":"distinct.js","sourceRoot":"","sources":["../../src/operations/distinct.ts"],"names":[],"mappings":";;;AAIA,oCAAoF;AACpF,uCAAsE;AACtE,2CAAoD;AAKpD;;;GAGG;AACH,MAAa,iBAAkB,SAAQ,0BAAuB;IAQ5D;;;;;;;OAOG;IACH,YAAY,UAAsB,EAAE,GAAW,EAAE,KAAe,EAAE,OAAyB;QACzF,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAAyB;QAEzB,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC;QACrB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;QACzB,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE7B,mBAAmB;QACnB,MAAM,GAAG,GAAa;YACpB,QAAQ,EAAE,IAAI,CAAC,cAAc;YAC7B,GAAG,EAAE,GAAG;YACR,KAAK,EAAE,KAAK;SACb,CAAC;QAEF,2BAA2B;QAC3B,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YACzC,GAAG,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;SACnC;QAED,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,WAAW,EAAE;YAC1C,GAAG,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;SAC/B;QAED,qCAAqC;QACrC,IAAA,+BAAuB,EAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QAE5C,8BAA8B;QAC9B,IAAI;YACF,IAAA,6BAAqB,EAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;SAC3C;QAAC,OAAO,GAAG,EAAE;YACZ,OAAO,QAAQ,CAAC,GAAG,CAAC,CAAC;SACtB;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;AAxED,8CAwEC;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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/drop.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/drop.js new file mode 100644 index 00000000..50b39dc0 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/drop.js @@ -0,0 +1,83 @@ +"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 () => { + const db = this.db; + const options = this.options; + const name = this.name; + const encryptedFieldsMap = db.s.client.options.autoEncryption?.encryptedFieldsMap; + let encryptedFields = options.encryptedFields ?? encryptedFieldsMap?.[`${db.databaseName}.${name}`]; + if (!encryptedFields && encryptedFieldsMap) { + // If the MongoClient was configured 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 error_1.MongoServerError) || + err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + throw err; + } + } + } + } + return 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/drop.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/drop.js.map new file mode 100644 index 00000000..47f28932 --- /dev/null +++ b/1_ActivityWatchProducer/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,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,cAAc,EAAE,kBAAkB,CAAC;YAClF,IAAI,eAAe,GACjB,OAAO,CAAC,eAAe,IAAI,kBAAkB,EAAE,CAAC,GAAG,EAAE,CAAC,YAAY,IAAI,IAAI,EAAE,CAAC,CA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AAqB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/estimated_document_count.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/estimated_document_count.js new file mode 100644 index 00000000..e5948f2c --- /dev/null +++ b/1_ActivityWatchProducer/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?.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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/estimated_document_count.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/estimated_document_count.js.map new file mode 100644 index 00000000..927b7bca --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/estimated_document_count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"estimated_document_count.js","sourceRoot":"","sources":["../../src/operations/estimated_document_count.ts"],"names":[],"mappings":";;;AAKA,uCAAsE;AACtE,2CAAoD;AAYpD,gBAAgB;AAChB,MAAa,+BAAgC,SAAQ,0BAAwB;IAI3E,YAAY,UAAsB,EAAE,UAAyC,EAAE;QAC7E,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;IAClD,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA0B;QAE1B,MAAM,GAAG,GAAa,EAAE,KAAK,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAErD,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YAC9C,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;SACxC;QAED,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YACtC,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SACpC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE;YAC3D,IAAI,GAAG,EAAE;gBACP,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACd,OAAO;aACR;YAED,QAAQ,CAAC,SAAS,EAAE,QAAQ,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AApCD,0EAoCC;AAED,IAAA,yBAAa,EAAC,+BAA+B,EAAE;IAC7C,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/eval.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/eval.js new file mode 100644 index 00000000..0354c60c --- /dev/null +++ b/1_ActivityWatchProducer/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 ?? {}; + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/eval.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/eval.js.map new file mode 100644 index 00000000..cc43a0dc --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/eval.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eval.js","sourceRoot":"","sources":["../../src/operations/eval.ts"],"names":[],"mappings":";;;AAAA,kCAAyC;AAGzC,oCAA4C;AAC5C,wDAAoD;AAIpD,u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AAM,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/execute_operation.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/execute_operation.js new file mode 100644 index 00000000..bb7978ed --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/execute_operation.js @@ -0,0 +1,181 @@ +"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) { + return (0, utils_1.maybeCallback)(() => executeOperationAsync(client, operation), callback); +} +exports.executeOperation = executeOperation; +async function executeOperationAsync(client, operation) { + if (!(operation instanceof operation_1.AbstractOperation)) { + // TODO(NODE-3483): Extend MongoRuntimeError + throw new error_1.MongoRuntimeError('This method requires a valid operation instance'); + } + if (client.topology == null) { + // Auto connect on operation + if (client.s.hasBeenClosed) { + throw new error_1.MongoNotConnectedError('Client must be connected before running operations'); + } + client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true; + try { + await client.connect(); + } + finally { + delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')]; + } + } + const { topology } = client; + if (topology == null) { + throw new error_1.MongoRuntimeError('client.connect did not create a topology but also did not throw'); + } + if (topology.shouldCheckForSessionSupport()) { + await topology.selectServerAsync(read_preference_1.ReadPreference.primaryPreferred, {}); + } + // 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) { + throw new error_1.MongoExpiredSessionError('Use of expired sessions is not permitted'); + } + else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + throw 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. + throw 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; + } + } + const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary; + const inTransaction = !!session?.inTransaction(); + if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) { + throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`); + } + if (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)(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 = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference); + } + else { + selector = readPreference; + } + const server = await topology.selectServerAsync(selector, { session }); + if (session == null) { + // No session also means it is not retryable, early exit + return operation.executeAsync(server, undefined); + } + if (!operation.hasAspect(operation_1.Aspect.RETRYABLE)) { + // non-retryable operation, early exit + try { + return await operation.executeAsync(server, session); + } + finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } + } + 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); + const willRetry = (hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite); + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + try { + return await operation.executeAsync(server, session); + } + catch (operationError) { + if (willRetry && operationError instanceof error_1.MongoError) { + return await retryOperation(operation, operationError, { + session, + topology, + selector + }); + } + throw operationError; + } + finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } +} +async function retryOperation(operation, originalError, { session, topology, selector }) { + 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) { + throw new error_1.MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError + }); + } + if (isWriteOperation && !(0, error_1.isRetryableWriteError)(originalError)) { + throw originalError; + } + if (isReadOperation && !(0, error_1.isRetryableReadError)(originalError)) { + throw originalError; + } + if (originalError instanceof error_1.MongoNetworkError && + 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 + const server = await topology.selectServerAsync(selector, { session }); + if (isWriteOperation && !(0, utils_1.supportsRetryableWrites)(server)) { + throw new error_1.MongoUnexpectedServerResponseError('Selected server does not support retryable writes'); + } + try { + return await operation.executeAsync(server, session); + } + catch (retryError) { + if (retryError instanceof error_1.MongoError && + retryError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) { + throw originalError; + } + throw retryError; + } +} +//# sourceMappingURL=execute_operation.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/execute_operation.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/execute_operation.js.map new file mode 100644 index 00000000..e21b3921 --- /dev/null +++ b/1_ActivityWatchProducer/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,oCAckB;AAElB,wDAAoD;AAEpD,+DAIkC;AAGlC,oCAA4E;AAC5E,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,OAAO,IAAA,qBAAa,EAAC,GAAG,EAAE,CAAC,qBAAqB,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,QAAQ,CAA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MAAM,EAAE,iCAAiC;YACzC,aAAa;SACd,CAAC,CAAC;KACJ;IAED,IAAI,gBAAgB,IAAI,CAAC,IAAA,6BAAqB,EAAC,aAAa,CAAC,EAAE;QAC7D,MAAM,aAAa,CAAC;KACrB;IAED,IAAI,eAAe,IAAI,CAAC,IAAA,4BAAoB,EAAC,aAAa,CAAC,EAAE;QAC3D,MAAM,aAAa,CAAC;KACrB;IAED,IACE,aAAa,YAAY,yBAAiB;QAC1C,OAAO,CAAC,QAAQ;QAChB,CAAC,OAAO,CAAC,aAAa,EAAE;QACxB,SAAS,CAAC,SAAS,CAAC,kBAAM,CAAC,eAAe,CAAC,EAC3C;QACA,0EAA0E;QAC1E,mFAAmF;QACnF,4CAA4C;QAC5C,OAAO,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,IAAI,EAAE,CAAC,CAAC;KAClD;IAED,0DAA0D;IAC1D,MAAM,MAAM,GAAG,MAAM,QAAQ,CAAC,iBAAiB,CAAC,QAAQ,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC;IAEvE,IAAI,gBAAgB,IAAI,CAAC,IAAA,+BAAuB,EAAC,MAAM,CAAC,EAAE;QACxD,MAAM,IAAI,0CAAkC,CAC1C,mDAAmD,CACpD,CAAC;KACH;IAED,IAAI;QACF,OAAO,MAAM,SAAS,CAAC,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACtD;IAAC,OAAO,UAAU,EAAE;QACnB,IACE,UAAU,YAAY,kBAAU;YAChC,UAAU,CAAC,aAAa,CAAC,uBAAe,CAAC,iBAAiB,CAAC,EAC3D;YACA,MAAM,aAAa,CAAC;SACrB;QACD,MAAM,UAAU,CAAC;KAClB;AACH,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find.js new file mode 100644 index 00000000..b196f663 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find.js @@ -0,0 +1,156 @@ +"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"); +/** @internal */ +class FindOperation extends command_1.CommandOperation { + constructor(collection, ns, filter = {}, options = {}) { + super(collection, options); + this.options = { ...options }; + delete this.options.writeConcern; + 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 options = this.options; + 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.oplogReplay === 'boolean') { + findCommand.oplogReplay = options.oplogReplay; + } + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find.js.map new file mode 100644 index 00000000..27cbda3e --- /dev/null +++ b/1_ActivityWatchProducer/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,oCAAqD;AACrD,kDAA8C;AAG9C,kCAA2C;AAC3C,oCAA+F;AAC/F,uCAAwF;AACxF,2CAA0D;AA0D1D,gBAAgB;AAChB,MAAa,aAAc,SAAQ,0BAA0B;IAW3D,YACE,UAAkC,EAClC,EAAoB,EACpB,SAAmB,EAAE,EACrB,UAAuB,EAAE;QAEzB,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC;QACjC,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QAEb,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE;YACvD,MAAM,IAAI,iCAAyB,CAAC,iDAAiD,CAAC,CAAC;SACxF;QAED,oEAAoE;QACpE,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;YAC3B,MAAM,UAAU,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;YACxF,IAAI,UAAU,KAAK,MAAM,CAAC,MAAM,EAAE;gBAChC,MAAM,IAAI,iCAAyB,CACjC,qEAAqE,MAAM,CAAC,MAAM,SA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AW,CAAC;KAC/C;IAED,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;QACxC,WAAW,CAAC,eAAe,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC;KAChD;SAAM,IAAI,OAAO,OAAO,CAAC,eAAe,KAAK,SAAS,EAAE;QACvD,WAAW,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;KACvD;IAED,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,SAAS,EAAE;QAC1C,WAAW,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;KAC3C;IAED,IAAI,OAAO,OAAO,CAAC,mBAAmB,KAAK,SAAS,EAAE;QACpD,WAAW,CAAC,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find_and_modify.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find_and_modify.js new file mode 100644 index 00000000..f44efb84 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find_and_modify.js @@ -0,0 +1,151 @@ +"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 ?? {}; + 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) { + 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 = this.writeConcern?.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; + } + // 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find_and_modify.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find_and_modify.js.map new file mode 100644 index 00000000..d68f9f95 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/find_and_modify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find_and_modify.js","sourceRoot":"","sources":["../../src/operations/find_and_modify.ts"],"names":[],"mappings":";;;AAEA,oCAA8E;AAC9E,wDAAoD;AAGpD,kCAAuD;AACvD,oCAA+F;AAE/F,uCAAsE;AACtE,2CAAoD;AAEpD,cAAc;AACD,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;CACN,CAAC,CAAC;AA+EZ,SAAS,uCAAuC,CAC9C,OAA6B,EAC7B,OAA2D;IAE3D,OAAO,CAAC,GAAG,GAAG,OAAO,CAAC,cAAc,KAAK,sBAAc,CAAC,KAAK,CAAC;IAC9D,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC;IAEzC,IAAI,OAAO,CAAC,wBAAwB,KAAK,IAAI,EAAE;QAC7C,OAAO,CAAC,wBAAwB,GAAG,OAAO,CAAC,wBAAwB,CAAC;KACrE;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,gBAAgB;AAChB,MAAM,sBAAuB,SAAQ,0BAA0B;IAO7D,YACE,UAAsB,EACtB,KAAe,EACf,OAAqF;QAErF,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG;YACb,MAAM,EAAE,KAAK;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AAC;SAClF;QAED,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,MAAM,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/get_more.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/get_more.js new file mode 100644 index 00000000..94ba64ed --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/get_more.js @@ -0,0 +1,58 @@ +"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; + 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')); + } + if (this.cursorId == null || this.cursorId.isZero()) { + return callback(new error_1.MongoRuntimeError('Unable to iterate cursor with no id')); + } + const collection = this.ns.collection; + if (collection == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + return callback(new error_1.MongoRuntimeError('A collection name must be determined before getMore')); + } + const getMoreCmd = { + getMore: this.cursorId, + collection + }; + if (typeof this.options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(this.options.batchSize); + } + if (typeof this.options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined && (0, utils_1.maxWireVersion)(server) >= 9) { + getMoreCmd.comment = this.options.comment; + } + const commandOptions = { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch', + ...this.options + }; + server.command(this.ns, getMoreCmd, commandOptions, 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/get_more.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/get_more.js.map new file mode 100644 index 00000000..3803d986 --- /dev/null +++ b/1_ActivityWatchProducer/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;AA+BzF,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,6BAAiB;IAIrD,YAAY,EAAoB,EAAE,QAAc,EAAE,MAAc,EAAE,OAAuB;QACvF,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,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,I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OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAC;IAChE,CAAC;CACF;AAlED,4CAkEC;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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/indexes.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/indexes.js new file mode 100644 index 00000000..c583dd89 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/indexes.js @@ -0,0 +1,270 @@ +"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 isIndexDirection(x) { + return (typeof x === 'number' || x === '2d' || x === '2dsphere' || x === 'text' || x === 'geoHaystack'); +} +function isSingleIndexTuple(t) { + return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]); +} +function makeIndexSpec(indexSpec, options) { + const key = new Map(); + const indexSpecs = !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec; + // Iterate through array and handle different types + for (const spec of indexSpecs) { + if (typeof spec === 'string') { + key.set(spec, 1); + } + else if (Array.isArray(spec)) { + key.set(spec[0], spec[1] ?? 1); + } + else if (spec instanceof Map) { + for (const [property, value] of spec) { + key.set(property, value); + } + } + else if ((0, utils_1.isObject)(spec)) { + for (const [property, value] of Object.entries(spec)) { + key.set(property, value); + } + } + } + return { ...options, key }; +} +/** @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 ?? {}; + this.collectionName = collectionName; + this.indexes = indexes.map(userIndex => { + // Ensure the key is a Map to preserve index key ordering + const key = userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key)); + const name = userIndex.name != null ? userIndex.name : Array.from(key).flat().join('_'); + const validIndexOptions = Object.fromEntries(Object.entries({ ...userIndex }).filter(([optionName]) => VALID_INDEX_OPTIONS.has(optionName))); + return { + ...validIndexOptions, + name, + key + }; + }); + } + execute(server, session, callback) { + const options = this.options; + const indexes = this.indexes; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + 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) { + 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().then(indexes => { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + super.execute(server, session, callback); + }, error => { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + // ignore "NamespaceNotFound" errors + return super.execute(server, session, callback); + } + return callback(error); + }); + } +} +exports.EnsureIndexOperation = EnsureIndexOperation; +/** @internal */ +class DropIndexOperation extends command_1.CommandOperation { + constructor(collection, indexName, options) { + super(collection, options); + this.options = 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 }; + delete this.options.writeConcern; + 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 ?? {}; + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/indexes.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/indexes.js.map new file mode 100644 index 00000000..71eea6fd --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/indexes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"indexes.js","sourceRoot":"","sources":["../../src/operations/indexes.ts"],"names":[],"mappings":";;;AAGA,oCAAoF;AAEpF,wDAAoD;AAGpD,oCAAgF;AAChF,uCAKmB;AACnB,yDAA+E;AAC/E,2CAAuE;AAEvE,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAClC,YAAY;IACZ,QAAQ;IACR,MAAM;IACN,yBAAyB;IACzB,QAAQ;IACR,QAAQ;IACR,oBAAoB;IACpB,eAAe;IACf,WAAW;IACX,SAAS;IAET,eAAe;IACf,SAAS;IACT,kBAAkB;IAClB,mBAAmB;IACnB,kBAAkB;IAElB,oBAAoB;IACpB,sBAAsB;IAEtB,aAAa;IACb,MAAM;IACN,KAAK;IACL,KAAK;IAEL,sBAAsB;IACtB,YAAY;IAEZ,mBAAmB;IACnB,oBAAoB;CACrB,CAAC,CAAC;AAaH,SAAS,gBAAgB,CAAC,CAAU;IAClC,OAAO,CACL,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,UAAU,IAAI,CAAC,KAAK,MAAM,IAAI,CAAC,KAAK,aAAa,CAC/F,CAAC;AACJ,CAAC;AA8ED,SAAS,kBAAkB,CAAC,CAAU;IACpC,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACtE,CAAC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,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/insert.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/insert.js new file mode 100644 index 00000000..adf31329 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/insert.js @@ -0,0 +1,95 @@ +"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) { + super(undefined, options); + this.options = { ...options, checkKeys: options.checkKeys ?? false }; + this.ns = ns; + this.documents = documents; + } + execute(server, session, callback) { + const options = this.options ?? {}; + 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) => { + 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: this.writeConcern?.w !== 0 ?? 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) => { + 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: writeConcern?.w !== 0 ?? 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/insert.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/insert.js.map new file mode 100644 index 00000000..22affc58 --- /dev/null +++ b/1_ActivityWatchProducer/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,OAAO,CAAC,SAAS,IAAI,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,IAAI,CAAC,OAAO,IAAI,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,GAAG,OAAO,CAAC,wBAAwB,CAAC;SACrE;QAED,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YACjC,OAAO,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;SACnC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,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C,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/is_capped.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/is_capped.js new file mode 100644 index 00000000..096ebe22 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/is_capped.js @@ -0,0 +1,28 @@ +"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() + .then(collections => { + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + callback(undefined, !!collections[0].options?.capped); + }, error => callback(error)); + } +} +exports.IsCappedOperation = IsCappedOperation; +//# sourceMappingURL=is_capped.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/is_capped.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/is_capped.js.map new file mode 100644 index 00000000..0cb6b533 --- /dev/null +++ b/1_ActivityWatchProducer/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,EAAE;aACT,IAAI,CACH,WAAW,CAAC,EAAE;YACZ,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,SAAS,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACxD,CAAC,EACD,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;IACN,CAAC;CACF;AAnCD,8CAmCC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/kill_cursors.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/kill_cursors.js new file mode 100644 index 00000000..63d6e3e6 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/kill_cursors.js @@ -0,0 +1,32 @@ +"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')); + } + const killCursors = this.ns.collection; + if (killCursors == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + return callback(new error_1.MongoRuntimeError('A collection name must be determined before killCursors')); + } + const killCursorsCommand = { + killCursors, + cursors: [this.cursorId] + }; + server.command(this.ns, killCursorsCommand, { 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/kill_cursors.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/kill_cursors.js.map new file mode 100644 index 00000000..022ad687 --- /dev/null +++ b/1_ActivityWatchProducer/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;AAYzF,MAAa,oBAAqB,SAAQ,6BAAiB;IAGzD,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;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC;QACvC,IAAI,WAAW,IAAI,IAAI,EAAE;YACvB,gEAAgE;YAChE,wFAAwF;YACxF,OAAO,QAAQ,CACb,IAAI,yBAAiB,CAAC,yDAAyD,CAAC,CACjF,CAAC;SACH;QAED,MAAM,kBAAkB,GAAuB;YAC7C,WAAW;YACX,OAAO,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC;SACzB,CAAC;QAEF,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,kBAAkB,EAAE,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC7E,CAAC;CACF;AAjCD,oDAiCC;AAED,IAAA,yBAAa,EAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_collections.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_collections.js new file mode 100644 index 00000000..9f0726b6 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_collections.js @@ -0,0 +1,47 @@ +"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 }; + delete this.options.writeConcern; + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_collections.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_collections.js.map new file mode 100644 index 00000000..97e4a8f7 --- /dev/null +++ b/1_ActivityWatchProducer/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;IAetE,YAAY,EAAM,EAAE,MAAgB,EAAE,OAAgC;QACpE,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,OAAO,GAAG,EAAE,GAAG,OAAO,EAAE,CAAC;QAC9B,OAAO,IAAI,CAAC,OAAO,CAAC,YAAY,CAAC;QACjC,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QAC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\ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_databases.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_databases.js new file mode 100644 index 00000000..8cd6ec82 --- /dev/null +++ b/1_ActivityWatchProducer/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 ?? {}; + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_databases.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/list_databases.js.map new file mode 100644 index 00000000..875353e9 --- /dev/null +++ b/1_ActivityWatchProducer/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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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/operation.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/operation.js new file mode 100644 index 00000000..9a0297fb --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/operation.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defineAspects = exports.AbstractOperation = exports.Aspect = void 0; +const util_1 = require("util"); +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 = {}) { + this.executeAsync = (0, util_1.promisify)((server, session, callback) => { + this.execute(server, session, callback); + }); + this.readPreference = this.hasAspect(exports.Aspect.WRITE_OPERATION) + ? read_preference_1.ReadPreference.primary + : read_preference_1.ReadPreference.fromOptions(options) ?? 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/operation.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/operation.js.map new file mode 100644 index 00000000..4ad62a39 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"operation.js","sourceRoot":"","sources":["../../src/operations/operation.ts"],"names":[],"mappings":";;;AAAA,+BAAiC;AAEjC,kCAA6E;AAC7E,wDAAwE;AAK3D,QAAA,MAAM,GAAG;IACpB,cAAc,EAAE,MAAM,CAAC,gBAAgB,CAAC;IACxC,eAAe,EAAE,MAAM,CAAC,iBAAiB,CAAC;IAC1C,SAAS,EAAE,MAAM,CAAC,WAAW,CAAC;IAC9B,WAAW,EAAE,MAAM,CAAC,aAAa,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC,gBAAgB,CAAC;IACxC,eAAe,EAAE,MAAM,CAAC,iBAAiB,CAAC;IAC1C,uBAAuB,EAAE,MAAM,CAAC,yBAAyB,CAAC;CAClD,CAAC;AAuBX,gBAAgB;AAChB,MAAM,QAAQ,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC;AAEnC;;;;;;GAMG;AACH,MAAsB,iBAAiB;IAiBrC,YAAY,UAA4B,EAAE;QACxC,IAAI,CAAC,YAAY,GAAG,IAAA,gBAAS,EAC3B,CACE,MAAc,EACd,OAAkC,EAClC,QAAwC,EACxC,EAAE;YACF,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,EAAE,QAAe,CAAC,CAAC;QACjD,CAAC,CACF,CAAC;QAEF,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,SA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rB;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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/options_operation.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/options_operation.js new file mode 100644 index 00000000..37fb7e62 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/options_operation.js @@ -0,0 +1,28 @@ +"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() + .then(collections => { + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + callback(undefined, collections[0].options); + }, error => callback(error)); + } +} +exports.OptionsOperation = OptionsOperation; +//# sourceMappingURL=options_operation.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/options_operation.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/options_operation.js.map new file mode 100644 index 00000000..9b27753b --- /dev/null +++ b/1_ActivityWatchProducer/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,EAAE;aACT,IAAI,CACH,WAAW,CAAC,EAAE;YACZ,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,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QAC9C,CAAC,EACD,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;IACN,CAAC;CACF;AAnCD,4CAmCC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/profiling_level.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/profiling_level.js new file mode 100644 index 00000000..33802dfa --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/profiling_level.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/profiling_level.js.map new file mode 100644 index 00000000..8630fdc0 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/remove_user.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/remove_user.js new file mode 100644 index 00000000..daab3ebf --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/remove_user.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/remove_user.js.map new file mode 100644 index 00000000..d689529a --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/rename.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/rename.js new file mode 100644 index 00000000..82b7ec36 --- /dev/null +++ b/1_ActivityWatchProducer/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?.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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/rename.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/rename.js.map new file mode 100644 index 00000000..63e983d0 --- /dev/null +++ b/1_ActivityWatchProducer/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,C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CD,0CA6CC;AAED,IAAA,yBAAa,EAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/run_command.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/run_command.js new file mode 100644 index 00000000..10f3ebab --- /dev/null +++ b/1_ActivityWatchProducer/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 ?? {}; + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/run_command.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/run_command.js.map new file mode 100644 index 00000000..43096290 --- /dev/null +++ b/1_ActivityWatchProducer/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,IAAI,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/set_profiling_level.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/set_profiling_level.js new file mode 100644 index 00000000..4ff83297 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/set_profiling_level.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/set_profiling_level.js.map new file mode 100644 index 00000000..4928b616 --- /dev/null +++ b/1_ActivityWatchProducer/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,oCAAwE;AAIxE,oCAAwC;AACxC,uCAAsE;AAEtE,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;AAEzD,cAAc;AACD,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,GAAG,EAAE,KAAK;IACV,QAAQ,EAAE,WAAW;IACrB,GAAG,EAAE,KAAK;CACF,CAAC,CAAC;AAQZ,gBAAgB;AAChB,MAAa,0BAA2B,SAAQ,0BAAgC;IAK9E,YAAY,EAAM,EAAE,KAAqB,EAAE,OAAiC;QAC1E,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QACnB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,QAAQ,KAAK,EAAE;YACb,KAAK,sBAAc,CAAC,GAAG;gBACrB,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR,KAAK,sBAAc,CAAC,QAAQ;gBAC1B,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR,KAAK,sBAAc,CAAC,GAAG;gBACrB,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;YACR;gBACE,IAAI,CAAC,OAAO,GAAG,CAAC,CAAC;gBACjB,MAAM;SACT;QAED,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAAkC;QAElC,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC;QAEzB,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;YAC3B,OAAO,QAAQ,CACb,IAAI,iCAAyB,CAC3B,mCAAmC,IAAA,oBAAY,EAAC,sBAAc,CAAC,GAAG,CACnE,CACF,CAAC;SACH;QAED,+CAA+C;QAC/C,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/stats.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/stats.js new file mode 100644 index 00000000..6139ca3c --- /dev/null +++ b/1_ActivityWatchProducer/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 ?? {}; + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/stats.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/stats.js.map new file mode 100644 index 00000000..321a494c --- /dev/null +++ b/1_ActivityWatchProducer/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,IAAI,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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/update.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/update.js new file mode 100644 index 00000000..122dc7d3 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/update.js @@ -0,0 +1,183 @@ +"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) { + const options = this.options ?? {}; + 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 unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + callback(new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`)); + 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) => { + 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: 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 + }); + }); + } +} +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) => { + 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: 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 + }); + }); + } +} +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) => { + 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: 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 + }); + }); + } +} +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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/update.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/update.js.map new file mode 100644 index 00000000..4488092a --- /dev/null +++ b/1_ActivityWatchProducer/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,oCAA0E;AAC1E,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,IAAI,CAAC,OAAO,IAAI,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,OAAO,CAAC,wBAAwB,KAA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AChC,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;AACH,IAAA,yBAAa,EAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/validate_collection.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/validate_collection.js new file mode 100644 index 00000000..1a7c978e --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/validate_collection.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/operations/validate_collection.js.map new file mode 100644 index 00000000..9d72c418 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/read_concern.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/read_concern.js new file mode 100644 index 00000000..28580c33 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/read_concern.js @@ -0,0 +1,73 @@ +"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) { + /** + * 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 = exports.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) { + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/read_concern.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/read_concern.js.map new file mode 100644 index 00000000..5df31985 --- /dev/null +++ b/1_ActivityWatchProducer/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,wBAAgB,CAAC,KAAK,CAAC,IAAI,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/1_ActivityWatchProducer/node_modules/mongodb/lib/read_preference.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 00000000..e192281a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,195 @@ +"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' +}); +/** + * 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/ + */ +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?.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + options = 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) { + 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, 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; + } + /** + * 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 + * @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; + } +} +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/1_ActivityWatchProducer/node_modules/mongodb/lib/read_preference.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/read_preference.js.map new file mode 100644 index 00000000..7c6ac51d --- /dev/null +++ b/1_ActivityWatchProducer/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,CAA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C,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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/common.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/common.js new file mode 100644 index 00000000..60b96aa3 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/common.js @@ -0,0 +1,56 @@ +"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; +const timers_1 = require("timers"); +// 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(timers_1.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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/common.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/common.js.map new file mode 100644 index 00000000..95a76c42 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/sdam/common.ts"],"names":[],"mappings":";;;AAAA,mCAAsC;AAMtC,qBAAqB;AACR,QAAA,aAAa,GAAG,SAAS,CAAC;AAC1B,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,gBAAgB,GAAG,YAAY,CAAC;AAChC,QAAA,eAAe,GAAG,WAAW,CAAC;AAE3C;;;GAGG;AACU,QAAA,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC;IACxC,MAAM,EAAE,QAAQ;IAChB,mBAAmB,EAAE,qBAAqB;IAC1C,qBAAqB,EAAE,uBAAuB;IAC9C,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAKZ;;;GAGG;AACU,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IACtC,UAAU,EAAE,YAAY;IACxB,MAAM,EAAE,QAAQ;IAChB,eAAe,EAAE,iBAAiB;IAClC,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,aAAa;IAC1B,SAAS,EAAE,WAAW;IACtB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAQZ,gBAAgB;AAChB,SAAgB,eAAe,CAAC,KAAiB;IAC/C,KAAK,CAAC,OAAO,CAAC,qBAAY,CAAC,CAAC;IAC5B,KAAK,CAAC,KAAK,EAAE,CAAC;AAChB,CAAC;AAHD,0CAGC;AAWD,+EAA+E;AAC/E,SAAgB,mBAAmB,CACjC,MAAgC,EAChC,YAAyB;IAEzB,IAAI,MAAM,CAAC,WAAW,IAAI,IAAI,EAAE;QAC9B,MAAM,CAAC,WAAW,GAAG,YAAY,CAAC;KACnC;SAAM;QACL,IAAI,YAAY,CAAC,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE;YACxE,MAAM,CAAC,WAAW,GAAG,YAAY,CAAC;SACnC;KACF;AACH,CAAC;AAXD,kDAWC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/events.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/events.js new file mode 100644 index 00000000..686f82d0 --- /dev/null +++ b/1_ActivityWatchProducer/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 ?? {}; + } +} +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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/events.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/events.js.map new file mode 100644 index 00000000..67f5af72 --- /dev/null +++ b/1_ActivityWatchProducer/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;IACvC,CAAC;CACF;AAtBD,sEAsBC;AAED;;;;GAIG;AACH,MAAa,kBAAkB;IAM7B,gBAAgB;IAChB,YAAY,UAAkB,EAAE,OAAe;QAC7C,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAXD,gDAWC;AAED;;;;GAIG;AACH,MAAa,iBAAiB;IAM5B,gBAAgB;IAChB,YAAY,UAAkB,EAAE,OAAe;QAC7C,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAXD,8CAWC;AAED;;;;GAIG;AACH,MAAa,+BAA+B;IAQ1C,gBAAgB;IAChB,YACE,UAAkB,EAClB,mBAAwC,EACxC,cAAmC;QAEnC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;QAC/C,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;CACF;AAlBD,0EAkBC;AAED;;;;GAIG;AACH,MAAa,oBAAoB;IAI/B,gBAAgB;IAChB,YAAY,UAAkB;QAC5B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;CACF;AARD,oDAQC;AAED;;;;GAIG;AACH,MAAa,mBAAmB;IAI9B,gBAAgB;IAChB,YAAY,UAAkB;QAC5B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;CACF;AARD,kDAQC;AAED;;;;;;GAMG;AACH,MAAa,2BAA2B;IAItC,gBAAgB;IAChB,YAAY,YAAoB;QAC9B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,CAAC;CACF;AARD,kEAQC;AAED;;;;GAIG;AACH,MAAa,6BAA6B;IAQxC,gBAAgB;IAChB,YAAY,YAAoB,EAAE,QAAgB,EAAE,KAAsB;QACxE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/monitor.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/monitor.js new file mode 100644 index 00000000..2d96fe75 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/monitor.js @@ -0,0 +1,417 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MonitorInterval = 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 { + get connection() { + return this[kConnection]; + } + constructor(server, options) { + 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: 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: '', + generation: server.s.pool.generation, + connectionType: connection_1.Connection, + cancellationToken, + hostAddress: server.description.hostAddress + }, options, + // force BSON serialization options + { + raw: false, + useBigInt64: 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() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; + } + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: minHeartbeatFrequencyMS, + immediate: true + }); + } + requestCheck() { + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + this[kMonitorId]?.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] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: 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) { + 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, callback) { + let start = (0, utils_1.now)(); + monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address)); + function failureHandler(err) { + monitor[kConnection]?.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)); + const error = !(err instanceof error_1.MongoError) ? new error_1.MongoError(err) : err; + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + if (error instanceof error_1.MongoNetworkTimeoutError) { + error.addErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections); + } + monitor.emit('resetServer', error); + 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' : constants_1.LEGACY_HELLO_COMMAND]: 1, + ...(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) => { + 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 { + monitor[kRTTPinger]?.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; + 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) => { + if (monitor.s.state === STATE_MONITORING) { + process.nextTick(callback); + return; + } + 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) { + return done(); + } + } + // if the check indicates streaming is supported, immediately reschedule monitoring + if (hello && hello.topologyVersion) { + (0, timers_1.setTimeout)(() => { + if (!isInCloseState(monitor)) { + monitor[kMonitorId]?.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 + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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() { + this.closed = true; + (0, timers_1.clearTimeout)(this[kMonitorId]); + this[kConnection]?.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?.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(); + }); +} +/** + * @internal + */ +class MonitorInterval { + constructor(fn, options = {}) { + this.isExpeditedCallToFnScheduled = false; + this.stopped = false; + this.isExecutionInProgress = false; + this.hasExecutedOnce = false; + this._executeAndReschedule = () => { + if (this.stopped) + return; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + } + this.isExpeditedCallToFnScheduled = false; + this.isExecutionInProgress = true; + this.fn(() => { + this.lastExecutionEnded = (0, utils_1.now)(); + this.isExecutionInProgress = false; + this._reschedule(this.heartbeatFrequencyMS); + }); + }; + this.fn = fn; + this.lastExecutionEnded = -Infinity; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1000; + this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500; + if (options.immediate) { + this._executeAndReschedule(); + } + else { + this._reschedule(undefined); + } + } + wake() { + const currentTime = (0, utils_1.now)(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + // TODO(NODE-4674): Add error handling and logging to the monitor + if (timeSinceLastCall < 0) { + return this._executeAndReschedule(); + } + if (this.isExecutionInProgress) { + return; + } + // debounce multiple calls to wake within the `minInterval` + if (this.isExpeditedCallToFnScheduled) { + return; + } + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeSinceLastCall < this.minHeartbeatFrequencyMS) { + this.isExpeditedCallToFnScheduled = true; + this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall); + return; + } + this._executeAndReschedule(); + } + stop() { + this.stopped = true; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + this.timerId = undefined; + } + this.lastExecutionEnded = -Infinity; + this.isExpeditedCallToFnScheduled = false; + } + toString() { + return JSON.stringify(this); + } + toJSON() { + const currentTime = (0, utils_1.now)(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + return { + timerId: this.timerId != null ? 'set' : 'cleared', + lastCallTime: this.lastExecutionEnded, + isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled, + stopped: this.stopped, + heartbeatFrequencyMS: this.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS, + currentTime, + timeSinceLastCall + }; + } + _reschedule(ms) { + if (this.stopped) + return; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + } + this.timerId = (0, timers_1.setTimeout)(this._executeAndReschedule, ms || this.heartbeatFrequencyMS); + } +} +exports.MonitorInterval = MonitorInterval; +//# sourceMappingURL=monitor.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/monitor.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/monitor.js.map new file mode 100644 index 00000000..4edb22be --- /dev/null +++ b/1_ActivityWatchProducer/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,mCAAkD;AAElD,kCAAyC;AACzC,6CAA0C;AAC1C,mDAAmE;AACnE,4CAAoD;AACpD,oCAAiF;AACjF,gDAAsE;AAEtE,oCAAmG;AACnG,qCAAmE;AACnE,qCAIkB;AAClB,qCAAkC;AAGlC,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACvD,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAE/C,MAAM,UAAU,GAAG,MAAM,CAAC;AAC1B,MAAM,gBAAgB,GAAG,YAAY,CAAC;AACtC,MAAM,eAAe,GAAG,IAAA,wBAAgB,EAAC;IACvC,CAAC,sBAAa,CAAC,EAAE,CAAC,sBAAa,EAAE,UAAU,EAAE,qBAAY,CAAC;IAC1D,CAAC,qBA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YAC3B,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;SAC1B;QAED,IAAI,CAAC,kBAAkB,GAAG,CAAC,QAAQ,CAAC;QACpC,IAAI,CAAC,4BAA4B,GAAG,KAAK,CAAC;IAC5C,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,MAAM;QACJ,MAAM,WAAW,GAAG,IAAA,WAAG,GAAE,CAAC;QAC1B,MAAM,iBAAiB,GAAG,WAAW,GAAG,IAAI,CAAC,kBAAkB,CAAC;QAChE,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;YACjD,YAAY,EAAE,IAAI,CAAC,kBAAkB;YACrC,yBAAyB,EAAE,IAAI,CAAC,4BAA4B;YAC5D,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,WAAW;YACX,iBAAiB;SAClB,CAAC;IACJ,CAAC;IAEO,WAAW,CAAC,EAAW;QAC7B,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QACzB,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,IAAA,qBAAY,EAAC,IAAI,CAAC,OAAO,CAAC,CAAC;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,IAAA,mBAAU,EAAC,IAAI,CAAC,qBAAqB,EAAE,EAAE,IAAI,IAAI,CAAC,oBAAoB,CAAC,CAAC;IACzF,CAAC;CAiBF;AA7GD,0CA6GC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server.js new file mode 100644 index 00000000..90f43051 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server.js @@ -0,0 +1,369 @@ +"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 errors_1 = require("../cmap/errors"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +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, + state: common_1.STATE_CLOSED, + topology, + pool: new connection_pool_1.ConnectionPool(this, 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('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() { + 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) { + this[kMonitor]?.connect(); + } + else { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + } + /** Destroy the server connection */ + destroy(options, callback) { + if (typeof options === 'function') { + callback = options; + options = { force: false }; + } + 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) { + this[kMonitor]?.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() { + if (!this.loadBalanced) { + this[kMonitor]?.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; + } + 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; + if (!err) { + return cb(new error_1.MongoRuntimeError('Failed to create connection without error')); + } + if (!(err instanceof errors_1.PoolClearedError)) { + this.handleError(err); + } + return cb(err); + } + conn.command(ns, cmd, finalOptions, makeOperationHandler(this, conn, cmd, finalOptions, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + })); + }, callback); + } + /** + * Handle SDAM error + * @internal + */ + handleError(error, connection) { + if (!(error instanceof error_1.MongoError)) { + return; + } + const isStaleError = error.connectionGeneration && error.connectionGeneration < this.s.pool.generation; + if (isStaleError) { + return; + } + const isNetworkNonTimeoutError = error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError); + const isNetworkTimeoutBeforeHandshakeError = (0, error_1.isNetworkErrorBeforeHandshake)(error); + const isAuthHandshakeError = error.hasErrorLabel(error_1.MongoErrorLabel.HandshakeError); + if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + if (!this.loadBalanced) { + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + markServerUnknown(this, error); + } + else if (connection) { + this.s.pool.clear({ serviceId: connection.serviceId }); + } + } + else { + if ((0, error_1.isSDAMUnrecoverableError)(error)) { + if (shouldHandleStateChangeError(this, error)) { + const shouldClearPool = (0, utils_1.maxWireVersion)(this) <= 7 || (0, error_1.isNodeShuttingDownError)(error); + if (this.loadBalanced && connection && shouldClearPool) { + this.s.pool.clear({ serviceId: connection.serviceId }); + } + if (!this.loadBalanced) { + if (shouldClearPool) { + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + } + markServerUnknown(this, error); + process.nextTick(() => this.requestCheck()); + } + } + } + } + } +} +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) { + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) { + server[kMonitor]?.reset(); + } + server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, undefined, { error })); +} +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?.session; + return function handleOperationResult(error, result) { + // We should not swallow an error if it is present. + if (error == null && result != null) { + return callback(undefined, result); + } + if (options != null && 'noResponse' in options && options.noResponse === true) { + return callback(undefined, null); + } + 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); + } + } + 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 (session && + session.isPinned && + error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + session.unpin({ force: true }); + } + server.handleError(error, connection); + return callback(error); + }; +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server.js.map new file mode 100644 index 00000000..7e621e42 --- /dev/null +++ b/1_ActivityWatchProducer/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,mDAAgF;AAChF,6DAIiC;AACjC,2CAAkD;AAClD,4CAWsB;AAEtB,oCAekB;AAElB,gDAAmD;AAGnD,kDAAuD;AACvD,oCAOkB;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,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,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,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;QAEtC,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_description.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_description.js new file mode 100644 index 00000000..1cf4da37 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_description.js @@ -0,0 +1,189 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compareTopologyVersion = exports.parseServerType = exports.ServerDescription = void 0; +const bson_1 = require("../bson"); +const error_1 = require("../error"); +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 = {}) { + if (address == null || address === '') { + throw new error_1.MongoRuntimeError('ServerDescription must be provided with a non-empty address'); + } + this.address = + typeof address === 'string' + ? utils_1.HostAddress.fromString(address).toString() // Use HostAddress to normalize + : address.toString(); + this.type = parseServerType(hello, options); + this.hosts = hello?.hosts?.map((host) => host.toLowerCase()) ?? []; + this.passives = hello?.passives?.map((host) => host.toLowerCase()) ?? []; + this.arbiters = hello?.arbiters?.map((host) => host.toLowerCase()) ?? []; + this.tags = hello?.tags ?? {}; + this.minWireVersion = hello?.minWireVersion ?? 0; + this.maxWireVersion = hello?.maxWireVersion ?? 0; + this.roundTripTime = options?.roundTripTime ?? -1; + this.lastUpdateTime = (0, utils_1.now)(); + this.lastWriteDate = hello?.lastWrite?.lastWriteDate ?? 0; + this.error = options.error ?? null; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this.topologyVersion = this.error?.topologyVersion ?? hello?.topologyVersion ?? null; + this.setName = hello?.setName ?? null; + this.setVersion = hello?.setVersion ?? null; + this.electionId = hello?.electionId ?? null; + this.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes ?? null; + this.primary = hello?.primary ?? null; + this.me = hello?.me?.toLowerCase() ?? null; + this.$clusterTime = hello?.$clusterTime ?? null; + } + get hostAddress() { + return utils_1.HostAddress.fromString(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) { + // Despite using the comparator that would determine a nullish topologyVersion as greater than + // for equality we should only always perform direct equality comparison + const topologyVersionsEqual = this.topologyVersion === other?.topologyVersion || + compareTopologyVersion(this.topologyVersion, other?.topologyVersion) === 0; + const electionIdsEqual = this.electionId != null && other?.electionId != null + ? (0, utils_1.compareObjectId)(this.electionId, other.electionId) === 0 + : 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?.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. + * + * 1. If the response topologyVersion is unset or the ServerDescription's + * topologyVersion is null, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is not equal to the + * ServerDescription's, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is equal to the + * ServerDescription's, the client MUST use the counter field to determine + * which topologyVersion is more recent. + * + * ```ts + * currentTv < newTv === -1 + * currentTv === newTv === 0 + * currentTv > newTv === 1 + * ``` + */ +function compareTopologyVersion(currentTv, newTv) { + if (currentTv == null || newTv == null) { + return -1; + } + if (!currentTv.processId.equals(newTv.processId)) { + return -1; + } + // TODO(NODE-2674): Preserve int64 sent from MongoDB + const currentCounter = bson_1.Long.isLong(currentTv.counter) + ? currentTv.counter + : bson_1.Long.fromNumber(currentTv.counter); + const newCounter = bson_1.Long.isLong(newTv.counter) ? newTv.counter : bson_1.Long.fromNumber(newTv.counter); + return currentCounter.compare(newCounter); +} +exports.compareTopologyVersion = compareTopologyVersion; +//# sourceMappingURL=server_description.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_description.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_description.js.map new file mode 100644 index 00000000..7e851737 --- /dev/null +++ b/1_ActivityWatchProducer/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;AACnD,oCAA2E;AAC3E,oCAAiG;AAEjG,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;AAuBH;;;;;GAKG;AACH,MAAa,iBAAiB;IAwB5B;;;;;;OAMG;IACH,YACE,OAA6B,EAC7B,KAAgB,EAChB,UAAoC,EAAE;QAEtC,IAAI,OAAO,IAAI,IAAI,IAAI,OAAO,KAAK,EAAE,EAAE;YACrC,MAAM,IAAI,yBAAiB,CAA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AM,QAAQ,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACnC,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAErC,OAAO,CACL,QAAQ,CAAC,MAAM,KAAK,SAAS,CAAC,MAAM;QACpC,QAAQ,CAAC,KAAK,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,SAAgB,sBAAsB,CACpC,SAAkC,EAClC,KAA8B;IAE9B,IAAI,SAAS,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI,EAAE;QACtC,OAAO,CAAC,CAAC,CAAC;KACX;IAED,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE;QAChD,OAAO,CAAC,CAAC,CAAC;KACX;IAED,oDAAoD;IACpD,MAAM,cAAc,GAAG,WAAI,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC;QACnD,CAAC,CAAC,SAAS,CAAC,OAAO;QACnB,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,UAAU,GAAG,WAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAE/F,OAAO,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAC5C,CAAC;AAnBD,wDAmBC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_selection.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_selection.js new file mode 100644 index 00000000..36e28162 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_selection.js @@ -0,0 +1,226 @@ +"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) => { + 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 === 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) => { + 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, 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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_selection.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/server_selection.js.map new file mode 100644 index 00000000..50c687dc --- /dev/null +++ b/1_ActivityWatchProducer/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,GA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;IACzB,CAAC,CAAC;AACJ,CAAC;AA9DD,oEA8DC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/srv_polling.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/srv_polling.js new file mode 100644 index 00000000..8714ad1e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/srv_polling.js @@ -0,0 +1,117 @@ +"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 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) { + super(); + if (!options || !options.srvHost) { + throw new error_1.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.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) { + (0, timers_1.clearTimeout)(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + // TODO(NODE-4994): implement new logging logic for SrvPoller failures + schedule() { + if (this._timeout) { + (0, timers_1.clearTimeout)(this._timeout); + } + this._timeout = (0, timers_1.setTimeout)(() => { + this._poll().catch(() => null); + }, this.intervalMS); + } + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + failure() { + this.haMode = true; + this.schedule(); + } + async _poll() { + const generation = this.generation; + let srvRecords; + try { + srvRecords = await dns.promises.resolveSrv(this.srvAddress); + } + catch (dnsError) { + this.failure(); + return; + } + if (generation !== this.generation) { + return; + } + const finalAddresses = []; + for (const record of srvRecords) { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } + } + if (!finalAddresses.length) { + this.failure(); + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/srv_polling.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/srv_polling.js.map new file mode 100644 index 00000000..ab1714c1 --- /dev/null +++ b/1_ActivityWatchProducer/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,mCAAkD;AAElD,oCAA6C;AAC7C,gDAAmD;AACnD,oCAAuC;AAEvC;;;;;;;GAOG;AACH,SAAS,mBAAmB,CAAC,UAAkB,EAAE,YAAoB;IACnE,MAAM,KAAK,GAAG,QAAQ,CAAC;IACvB,MAAM,G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AC,UAAU,CAAC;QACnC,IAAI,UAAU,CAAC;QAEf,IAAI;YACF,UAAU,GAAG,MAAM,GAAG,CAAC,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;SAC7D;QAAC,OAAO,QAAQ,EAAE;YACjB,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,OAAO;SACR;QAED,IAAI,UAAU,KAAK,IAAI,CAAC,UAAU,EAAE;YAClC,OAAO;SACR;QAED,MAAM,cAAc,GAAoB,EAAE,CAAC;QAC3C,KAAK,MAAM,MAAM,IAAI,UAAU,EAAE;YAC/B,IAAI,mBAAmB,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE;gBAClD,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;aAC7B;SACF;QAED,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE;YAC1B,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,OAAO;SACR;QAED,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IAC/B,CAAC;;AAxGH,8BAyGC;AA/FC,aAAa;AACG,8BAAoB,GAAG,oBAA6B,CAAC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology.js new file mode 100644 index 00000000..69240eba --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology.js @@ -0,0 +1,636 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerCapabilities = exports.Topology = void 0; +const timers_1 = require("timers"); +const util_1 = require("util"); +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) { + super(); + this.selectServerAsync = (0, util_1.promisify)((selector, options, callback) => this.selectServer(selector, options, callback)); + // Options should only be undefined in tests, MongoClient will always have defined options + options = 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 utils_1.List(); + 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?.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 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) { + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded; + const srvListeners = this.s.srvPoller?.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!srvListeners?.includes(this.s.detectSrvRecords); + if (transitionToSharded && !listeningToSrvPolling) { + this.s.srvPoller?.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + this.s.srvPoller?.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()); + } + connect(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = 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 = options.readPreference ?? 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?.(undefined, this); + }); + return; + } + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + callback?.(undefined, this); + }); + } + close(options, callback) { + options = options ?? { force: false }; + if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) { + return callback?.(); + } + const destroyedServers = Array.from(this.s.servers.values(), server => { + return (0, util_1.promisify)(destroyServer)(server, this, { force: !!options?.force }); + }); + 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?.()); + } + /** + * 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; + } + // 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 ?? { force: false }; + 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?.directConnection) { + return common_1.TopologyType.Single; + } + if (options?.replicaSet) { + return common_1.TopologyType.ReplicaSetNoPrimary; + } + if (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; + if (incomingServerDescription.error instanceof error_1.MongoError && + incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.ResetPool)) { + const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections); + server.s.pool.clear({ interruptInUseConnections }); + } + else if (incomingServerDescription.error == null) { + const newTopologyType = topology.s.description.type; + const shouldMarkPoolReady = incomingServerDescription.isDataBearing || + (incomingServerDescription.type !== common_1.ServerType.Unknown && + newTopologyType === common_1.TopologyType.Single); + if (shouldMarkPoolReady) { + server.s.pool.ready(); + } + } + } + } + // 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) { + (0, timers_1.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) { + (0, timers_1.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 { + const descriptions = (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) { + (0, timers_1.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?.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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology.js.map new file mode 100644 index 00000000..12802282 --- /dev/null +++ b/1_ActivityWatchProducer/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,mCAAkD;AAClD,+BAAiC;AAMjC,4DAAsE;AACtE,4CAcsB;AACtB,oCAQkB;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,C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,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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology_description.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology_description.js new file mode 100644 index 00000000..6ee1b0c2 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology_description.js @@ -0,0 +1,360 @@ +"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 = null, setName = null, maxSetVersion = null, maxElectionId = null, commonWireVersion = null, options = null) { + options = options ?? {}; + this.type = topologyType ?? common_1.TopologyType.Unknown; + this.servers = serverDescriptions ?? new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0; + this.localThresholdMS = options.localThresholdMS ?? 15; + this.setName = setName ?? null; + this.maxElectionId = maxElectionId ?? null; + this.maxSetVersion = maxSetVersion ?? null; + this.commonWireVersion = commonWireVersion ?? 0; + // 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 = null; + 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 = null; + 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; + 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); + } + } + if (typeof serverDescription.setName === 'string' && + typeof setName === 'string' && + serverDescription.setName !== setName) { + if (topologyType === common_1.TopologyType.Single) { + // "Single" Topology with setName mismatch is direct connection usage, mark unknown do not remove + serverDescription = new server_description_1.ServerDescription(address); + } + else { + serverDescriptions.delete(address); + } + } + // 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 null; + } + /** + * 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; + } +} +function updateRsFromPrimary(serverDescriptions, serverDescription, setName = null, maxSetVersion = null, maxElectionId = null) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + if (serverDescription.maxWireVersion >= 17) { + const electionIdComparison = (0, utils_1.compareObjectId)(maxElectionId, serverDescription.electionId); + const maxElectionIdIsEqual = electionIdComparison === 0; + const maxElectionIdIsLess = electionIdComparison === -1; + const maxSetVersionIsLessOrEqual = (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1); + if (maxElectionIdIsLess || (maxElectionIdIsEqual && maxSetVersionIsLessOrEqual)) { + // The reported electionId was greater + // or the electionId was equal and reported setVersion was greater + // Always update both values, they are a tuple + maxElectionId = serverDescription.electionId; + maxSetVersion = serverDescription.setVersion; + } + else { + // Stale primary + // replace serverDescription with a default ServerDescription of type "Unknown" + serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address)); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + else { + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if (maxSetVersion > serverDescription.setVersion || + (0, utils_1.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 = null) { + 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 = null) { + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology_description.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology_description.js.map new file mode 100644 index 00000000..c11143c5 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sdam/topology_description.js.map @@ -0,0 +1 @@ +{"version":3,"file":"topology_description.js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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/1_ActivityWatchProducer/node_modules/mongodb/lib/sessions.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sessions.js new file mode 100644 index 00000000..f3cadfdf --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sessions.js @@ -0,0 +1,738 @@ +"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 util_1 = require("util"); +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 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 ?? {}; + 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; + const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true; + this.supports = { + // if we can enable causal consistency, do so by default + causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue + }; + 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() { + return this[kServerSession]?.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() { + return this.client.topology?.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; + } + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + */ + async endSession(options) { + try { + if (this.inTransaction()) { + await this.abortTransaction(); + } + if (!this.hasEnded) { + 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); + } + } + catch { + // spec indicates that we should ignore all errors for `endSessions` + } + finally { + maybeClearPinnedConnection(this, { force: true, ...options }); + } + } + /** + * 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) { + 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 || + clusterTime.signature.hash?._bsontype !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'bigint' && + typeof clusterTime.signature.keyId !== 'number' && + clusterTime.signature.keyId?._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 utils_1.ByteUtils.equals(this.id.id.buffer, 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) { + if (this[kSnapshotEnabled]) { + throw new error_1.MongoCompatibilityError('Transactions are not supported in 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: 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(transactions_1.TxnState.STARTING_TRANSACTION); + } + /** + * Commits the currently active transaction in this session. + */ + async commitTransaction() { + return endTransactionAsync(this, 'commitTransaction'); + } + /** + * Aborts the currently active transaction in this session. + */ + async abortTransaction() { + return endTransactionAsync(this, 'abortTransaction'); + } + /** + * 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 + */ + async 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?.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?.error == null || 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?.forceClear) { + loadBalancer.s.pool.clear({ serviceId: 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) { + 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); + }); +} +const endTransactionAsync = (0, util_1.promisify)(endTransaction); +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 = new utils_1.List(); + } + /** + * 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() { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + let session = 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) { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + if (this.client.topology?.loadBalanced && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + if (!sessionTimeoutMinutes) { + return; + } + this.sessions.prune(session => session.hasTimedOut(sessionTimeoutMinutes)); + 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) { + 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 (options.writeConcern?.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; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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 || 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; +} +exports.applySession = applySession; +function updateSessionFromResponse(session, document) { + 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?.[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; + } + } +} +exports.updateSessionFromResponse = updateSessionFromResponse; +//# sourceMappingURL=sessions.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/sessions.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sessions.js.map new file mode 100644 index 00000000..d39bffc1 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/sessions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sessions.js","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":";;;;AAAA,+BAAiC;AAEjC,iCAA2D;AAE3D,4CAAuD;AACvD,wDAAwD;AACxD,2CAA+C;AAE/C,mCAciB;A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,OAAO,CAAC,aAAa,EAAE;YAC/D,OAAO,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,IAAI,EAAE,CAAC;YAChD,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,EAAE,gBAAgB,EAAE,OAAO,CAAC,aAAa,EAAE,CAAC,CAAC;SACjF;KACF;IACD,OAAO;AACT,CAAC;AAhFD,oCAgFC;AAED,SAAgB,yBAAyB,CAAC,OAAsB,EAAE,QAAkB;IAClF,IAAI,QAAQ,CAAC,YAAY,EAAE;QACzB,IAAA,4BAAmB,EAAC,OAAO,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAC;KACrD;IAED,IAAI,QAAQ,CAAC,aAAa,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,iBAAiB,EAAE;QAC3E,OAAO,CAAC,oBAAoB,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;KACtD;IAED,IAAI,QAAQ,CAAC,aAAa,IAAI,OAAO,IAAI,OAAO,CAAC,aAAa,EAAE,EAAE;QAChE,OAAO,CAAC,WAAW,CAAC,cAAc,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC7D;IAED,IAAI,OAAO,EAAE,CAAC,gBAAgB,CAAC,IAAI,OAAO,CAAC,aAAa,CAAC,IAAI,IAAI,EAAE;QACjE,iEAAiE;QACjE,4CAA4C;QAC5C,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,EAAE,aAAa,IAAI,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/1_ActivityWatchProducer/node_modules/mongodb/lib/sort.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/sort.js new file mode 100644 index 00000000..c04b6b54 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/lib/sort.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/sort.js.map new file mode 100644 index 00000000..4072af4c --- /dev/null +++ b/1_ActivityWatchProducer/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;QAClB,KAAK,MAAM,CAAC;QACZ,KAAK,IAAI;YACP,OAAO,CAAC,CAAC,CAAC;QACZ;YACE,MAAM,IAAI,iCAAyB,CAAC,2BAA2B,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;KAC/F;AACH,CAAC;AAED,gBAAgB;AAChB,SAAS,MAAM,CAAC,CAAgB;IAC9B,OAAO,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,IAAI,IAAI,IAAI,OAAO,IAAI,CAAC,IAAI,OAAO,CAAC,CAAC,KAAK,KAAK,QAAQ,CAAC;AAC3F,CAAC;AAED,gBAAgB;AAChB,SAAS,MAAM,CAAC,CAAO;IACrB,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE;QACtC,IAAI;YACF,gBAAgB,C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,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/1_ActivityWatchProducer/node_modules/mongodb/lib/transactions.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/transactions.js new file mode 100644 index 00000000..a4235b07 --- /dev/null +++ b/1_ActivityWatchProducer/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 ?? {}; + 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/1_ActivityWatchProducer/node_modules/mongodb/lib/transactions.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/transactions.js.map new file mode 100644 index 00000000..8a6982e2 --- /dev/null +++ b/1_ActivityWatchProducer/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;AAE9D,uDAAmD;AAEnD,mDAA+C;AAE/C,gBAAgB;AACH,QAAA,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,cAAc,EAAE,gBAAgB;IAChC,oBAAoB,EAAE,sBAAsB;IAC5C,uBAAuB,EAAE,yBAAyB;IAClD,qBAAqB,EAAE,uBAAuB;IAC9C,2BAA2B,EAAE,6BAA6B;IAC1D,mBAAmB,EAAE,qBAAqB;CAClC,CAAC,CAAC;AAKZ,MAAM,YAAY,GAAwC;IACxD,CAAC,gBAAQ,CAAC,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AO,gBAAgB,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC1C,CAAC;IACD;;;;OAIG;IACH,UAAU,CAAC,SAAmB;QAC5B,MAAM,UAAU,GAAG,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC5C,IAAI,UAAU,IAAI,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;YAChD,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;YACvB,IACE,IAAI,CAAC,KAAK,KAAK,gBAAQ,CAAC,cAAc;gBACtC,IAAI,CAAC,KAAK,KAAK,gBAAQ,CAAC,oBAAoB;gBAC5C,IAAI,CAAC,KAAK,KAAK,gBAAQ,CAAC,mBAAmB,EAC3C;gBACA,IAAI,CAAC,WAAW,EAAE,CAAC;aACpB;YACD,OAAO;SACR;QAED,MAAM,IAAI,yBAAiB,CACzB,4CAA4C,IAAI,CAAC,KAAK,SAAS,SAAS,GAAG,CAC5E,CAAC;IACJ,CAAC;IAED,gBAAgB;IAChB,SAAS,CAAC,MAAc;QACtB,IAAI,IAAI,CAAC,QAAQ,EAAE;YACjB,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC;SAC7B;IACH,CAAC;IAED,gBAAgB;IAChB,WAAW;QACT,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC;IACjC,CAAC;CACF;AAxGD,kCAwGC;AAED,SAAgB,oBAAoB,CAAC,OAAiB;IACpD,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAAC;AACnE,CAAC;AAFD,oDAEC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/utils.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/utils.js new file mode 100644 index 00000000..9a2d657d --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/utils.js @@ -0,0 +1,1055 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseUnsignedInteger = exports.parseInteger = exports.compareObjectId = exports.getMongoDBClientEncryption = exports.commandSupportsReadConcern = exports.shuffle = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isHello = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.calculateDurationInMs = exports.now = exports.makeClientMetadata = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.eachAsyncSeries = exports.eachAsync = exports.maxWireVersion = exports.uuidV4 = exports.databaseNamespace = exports.maybeCallback = exports.makeCounter = exports.MongoDBNamespace = exports.ns = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyWriteConcern = exports.applyRetryableWrites = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.normalizeHintField = exports.checkCollectionName = exports.ByteUtils = void 0; +const crypto = require("crypto"); +const os = require("os"); +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 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.ByteUtils = { + toLocalBufferType(buffer) { + return Buffer.isBuffer(buffer) + ? buffer + : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + }, + equals(seqA, seqB) { + return exports.ByteUtils.toLocalBufferType(seqA).equals(seqB); + }, + compare(seqA, seqB) { + return exports.ByteUtils.toLocalBufferType(seqA).compare(seqB); + }, + toBase64(uint8array) { + return exports.ByteUtils.toLocalBufferType(uint8array).toString('base64'); + } +}; +/** + * 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; +/** + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal + */ +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; +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) { + if (db && db.s.options?.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 ?? {}; + 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 resolution type of the possible promise + * @param value - An object that could be a promise + * @returns true if the provided value is a Promise + */ +function isPromiseLike(value) { + return !!value && typeof value.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; +/** + * 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 + */ +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; +/** @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 === '' ? undefined : collection; + } + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + withCollection(collection) { + return new MongoDBNamespace(this.db, collection); + } + static fromString(namespace) { + if (typeof namespace !== 'string' || namespace === '') { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + const [db, ...collectionParts] = namespace.split('.'); + const collection = collectionParts.join('.'); + return new MongoDBNamespace(db, collection === '' ? undefined : collection); + } +} +exports.MongoDBNamespace = MongoDBNamespace; +/** @internal */ +function* makeCounter(seed = 0) { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} +exports.makeCounter = makeCounter; +function maybeCallback(promiseFn, callback) { + const promise = promiseFn(); + if (callback == null) { + return promise; + } + promise.then(result => callback(undefined, result), error => callback(error)); + return; +} +exports.maybeCallback = maybeCallback; +/** @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 available 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; +/** + * 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 ?? {}; + 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; +/** @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) { + 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?.session; + if (!session?.inTransaction()) { + const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? parent?.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? parent?.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; + } + } + const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? 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; +/** + * A sequential list of items in a circularly linked list + * @remarks + * The head node is special, it is always defined and has a value of null. + * It is never "included" in the list, in that, it is not returned by pop/shift or yielded by the iterator. + * The circular linkage and always defined head node are to reduce checks for null next/prev references to zero. + * New nodes are declared as object literals with keys always in the same order: next, prev, value. + * @internal + */ +class List { + get length() { + return this.count; + } + get [Symbol.toStringTag]() { + return 'List'; + } + constructor() { + this.count = 0; + // this is carefully crafted: + // declaring a complete and consistently key ordered + // object is beneficial to the runtime optimizations + this.head = { + next: null, + prev: null, + value: null + }; + this.head.next = this.head; + this.head.prev = this.head; + } + toArray() { + return Array.from(this); + } + toString() { + return `head <=> ${this.toArray().join(' <=> ')} <=> head`; + } + *[Symbol.iterator]() { + for (const node of this.nodes()) { + yield node.value; + } + } + *nodes() { + let ptr = this.head.next; + while (ptr !== this.head) { + // Save next before yielding so that we make removing within iteration safe + const { next } = ptr; + yield ptr; + ptr = next; + } + } + /** Insert at end of list */ + push(value) { + this.count += 1; + const newNode = { + next: this.head, + prev: this.head.prev, + value + }; + this.head.prev.next = newNode; + this.head.prev = newNode; + } + /** Inserts every item inside an iterable instead of the iterable itself */ + pushMany(iterable) { + for (const value of iterable) { + this.push(value); + } + } + /** Insert at front of list */ + unshift(value) { + this.count += 1; + const newNode = { + next: this.head.next, + prev: this.head, + value + }; + this.head.next.prev = newNode; + this.head.next = newNode; + } + remove(node) { + if (node === this.head || this.length === 0) { + return null; + } + this.count -= 1; + const prevNode = node.prev; + const nextNode = node.next; + prevNode.next = nextNode; + nextNode.prev = prevNode; + return node.value; + } + /** Removes the first node at the front of the list */ + shift() { + return this.remove(this.head.next); + } + /** Removes the last node at the end of the list */ + pop() { + return this.remove(this.head.prev); + } + /** Iterates through the list and removes nodes where filter returns true */ + prune(filter) { + for (const node of this.nodes()) { + if (filter(node.value)) { + this.remove(node); + } + } + } + clear() { + this.count = 0; + this.head.next = this.head; + this.head.prev = this.head; + } + /** Returns the first item in the list, does not remove */ + first() { + // If the list is empty, value will be the head's null + return this.head.next.value; + } + /** Returns the last item in the list, does not remove */ + last() { + // If the list is empty, value will be the head's null + return this.head.prev.value; + } +} +exports.List = List; +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +class BufferPool { + constructor() { + this.buffers = new List(); + this.totalByteLength = 0; + } + get length() { + return this.totalByteLength; + } + /** Adds a buffer to the internal buffer pool list */ + append(buffer) { + this.buffers.push(buffer); + this.totalByteLength += buffer.length; + } + /** + * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes, + * otherwise return null. Size can be negative, caller should error check. + */ + getInt32() { + if (this.totalByteLength < 4) { + return null; + } + const firstBuffer = this.buffers.first(); + if (firstBuffer != null && firstBuffer.byteLength >= 4) { + return firstBuffer.readInt32LE(0); + } + // Unlikely case: an int32 is split across buffers. + // Use read and put the returned buffer back on top + const top4Bytes = this.read(4); + const value = top4Bytes.readInt32LE(0); + // Put it back. + this.totalByteLength += 4; + this.buffers.unshift(top4Bytes); + return value; + } + /** Reads the requested number of bytes, optionally consuming them */ + read(size) { + if (typeof size !== 'number' || size < 0) { + throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + // oversized request returns empty buffer + if (size > this.totalByteLength) { + return Buffer.alloc(0); + } + // We know we have enough, we just don't know how it is spread across chunks + // TODO(NODE-4732): alloc API should change based on raw option + const result = Buffer.allocUnsafe(size); + for (let bytesRead = 0; bytesRead < size;) { + const buffer = this.buffers.shift(); + if (buffer == null) { + break; + } + const bytesRemaining = size - bytesRead; + const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); + const bytes = buffer.subarray(0, bytesReadable); + result.set(bytes, bytesRead); + bytesRead += bytesReadable; + this.totalByteLength -= bytesReadable; + if (bytesReadable < buffer.byteLength) { + this.buffers.unshift(buffer.subarray(bytesReadable)); + } + } + return result; + } +} +exports.BufferPool = BufferPool; +/** @public */ +class HostAddress { + constructor(hostString) { + this.host = undefined; + this.port = undefined; + this.socketPath = undefined; + this.isIPv6 = false; + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + if (escapedHost.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(escapedHost); + return; + } + const urlString = `iLoveJS://${escapedHost}`; + let url; + try { + url = new url_1.URL(urlString); + } + catch (urlError) { + const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); + runtimeError.cause = urlError; + throw runtimeError; + } + const hostname = url.hostname; + const port = url.port; + 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'); + } + Object.freeze(this); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new HostAddress('${this.toString()}')`; + } + toString() { + if (typeof this.host === 'string') { + if (this.isIPv6) { + 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 + * ```ts + * 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; +/** + * 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(NODE-4936): read concern eligibility for commands 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. */ +function getMongoDBClientEncryption() { + let mongodbClientEncryption = null; + // 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) { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require(process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE); + } + catch { + // ignore + } + } + else { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require('mongodb-client-encryption'); + } + catch { + // ignore + } + } + return mongodbClientEncryption; +} +exports.getMongoDBClientEncryption = getMongoDBClientEncryption; +/** + * Compare objectIds. `null` is always less + * - `+1 = oid1 is greater than oid2` + * - `-1 = oid1 is less than oid2` + * - `+0 = oid1 is equal oid2` + */ +function compareObjectId(oid1, oid2) { + if (oid1 == null && oid2 == null) { + return 0; + } + if (oid1 == null) { + return -1; + } + if (oid2 == null) { + return 1; + } + return exports.ByteUtils.compare(oid1.id, oid2.id); +} +exports.compareObjectId = compareObjectId; +function parseInteger(value) { + if (typeof value === 'number') + return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + return Number.isNaN(parsedValue) ? null : parsedValue; +} +exports.parseInteger = parseInteger; +function parseUnsignedInteger(value) { + const parsedInt = parseInteger(value); + return parsedInt != null && parsedInt >= 0 ? parsedInt : null; +} +exports.parseUnsignedInteger = parseUnsignedInteger; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/utils.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/utils.js.map new file mode 100644 index 00000000..0447c4df --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/lib/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";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oBAAoB,CAAC,KAAc;IACjD,MAAM,SAAS,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IAEtC,OAAO,SAAS,IAAI,IAAI,IAAI,SAAS,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;AAChE,CAAC;AAJD,oDAIC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/write_concern.js b/1_ActivityWatchProducer/node_modules/mongodb/lib/write_concern.js new file mode 100644 index 00000000..43cdeec8 --- /dev/null +++ b/1_ActivityWatchProducer/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 ?? {}; + 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 ?? wtimeoutMS, j ?? journal, fsync); + } + return undefined; + } +} +exports.WriteConcern = WriteConcern; +//# sourceMappingURL=write_concern.js.map \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/lib/write_concern.js.map b/1_ActivityWatchProducer/node_modules/mongodb/lib/write_concern.js.map new file mode 100644 index 00000000..039f92b0 --- /dev/null +++ b/1_ActivityWatchProducer/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,IAAI,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,IAAI,UAAU,EAAE,CAAC,IAAI,OAAO,EAAE,KAAK,CAAC,CAAC;SACzE;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA7ED,oCA6EC"} \ No newline at end of file diff --git a/1_ActivityWatchProducer/node_modules/mongodb/mongodb.d.ts b/1_ActivityWatchProducer/node_modules/mongodb/mongodb.d.ts new file mode 100644 index 00000000..ea1ce8c2 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/mongodb.d.ts @@ -0,0 +1,6239 @@ +/// + +import { Binary } from 'bson'; +import { BSON } from 'bson'; +import { BSONRegExp } from 'bson'; +import { BSONSymbol } from 'bson'; +import { BSONType } from 'bson'; +import { Code } from 'bson'; +import type { ConnectionOptions as ConnectionOptions_2 } from 'tls'; +import { DBRef } from 'bson'; +import { Decimal128 } from 'bson'; +import { deserialize } 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 { MaxKey } from 'bson'; +import { MinKey } from 'bson'; +import { ObjectId } from 'bson'; +import type { ObjectIdLike } from 'bson'; +import { Readable } from 'stream'; +import { serialize } 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](): AsyncGenerator; + stream(options?: CursorStreamOptions): Readable & AsyncIterable; + hasNext(): Promise; + /** Get the next available document from the cursor, returns null if no more documents are available. */ + next(): Promise; + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + */ + forEach(iterator: (doc: TSchema) => boolean | void): Promise; + close(): Promise; + /** + * 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. + */ + toArray(): Promise; + /** + * 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** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **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; + /** + * Specifies the number of documents to return in each response from MongoDB + */ + batchSize?: number; + /** + * When applicable `maxTimeMS` controls the amount of time the initial command + * that constructs a cursor should take. (ex. find, aggregate, listCollections) + */ + maxTimeMS?: number; + /** + * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores + * that a cursor uses to fetch more data should take. (ex. cursor.next()) + */ + 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; + /** + * By default, MongoDB will automatically close a cursor when the + * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections) + * you may use a Tailable Cursor that remains open after the client exhausts + * the results in the initial cursor. + */ + tailable?: boolean; + /** + * If awaitData is set to true, when the cursor reaches the end of the capped collection, + * MongoDB blocks the query thread for a period of time waiting for new data to arrive. + * When new data is inserted into the capped collection, the blocked thread is signaled + * to wake up and return the next batch to the client. + */ + 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 { + /** 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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +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 + */ + command(command: Document, options?: RunCommandOptions): Promise; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + buildInfo(options?: CommandOperationOptions): Promise; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + serverInfo(options?: CommandOperationOptions): Promise; + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + serverStatus(options?: CommandOperationOptions): Promise; + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + ping(options?: CommandOperationOptions): Promise; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + addUser(username: string, passwordOrOptions?: string | AddUserOptions, options?: AddUserOptions): Promise; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + removeUser(username: string, options?: RemoveUserOptions): Promise; + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + validateCollection(collectionName: string, options?: ValidateCollectionOptions): Promise; + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + listDatabases(options?: ListDatabasesOptions): Promise; + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + replSetGetStatus(options?: CommandOperationOptions): Promise; +} + +/* 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(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; + /** 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"; + /* Excluded from this release type: MONGODB_OIDC */ +}>; + +/** @public */ +export declare type AuthMechanism = typeof AuthMechanism[keyof typeof AuthMechanism]; + +/** + * TODO: NODE-5035: Make OIDC properties public. + * + * @public + * */ +export declare interface AuthMechanismProperties extends Document { + SERVICE_HOST?: string; + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue; + AWS_SESSION_TOKEN?: string; + /* Excluded from this release type: DEVICE_NAME */ + /* Excluded from this release type: PRINCIPAL_NAME */ + /* Excluded from this release type: REQUEST_TOKEN_CALLBACK */ + /* Excluded from this release type: REFRESH_TOKEN_CALLBACK */ +} + +/** @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: 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; + } | Record; + /** 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; + } | { + /** + * If present, an access token to authenticate with Azure. + */ + accessToken: string; + }; + /** 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; + } | { + /** + * If present, an access token to authenticate with GCP. + */ + accessToken: string; + } | Record; + /** + * 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 Field Level 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 { BSON } + +export { BSONRegExp } + +/** + * BSON Serialization options. + * @public + */ +export declare interface BSONSerializeOptions extends Omit, Omit { + /** + * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html) + * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize). + * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe) + * for more detail about what "unsafe" refers to in this context. + * If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate + * your own buffer and clone the contents: + * + * @example + * ```ts + * const raw = await collection.findOne({}, { raw: true }); + * const myBuffer = Buffer.alloc(raw.byteLength); + * myBuffer.set(raw, 0); + * // Only save and use `myBuffer` beyond this point + * ``` + * + * @remarks + * Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)). + * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work. + */ + raw?: boolean; + /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */ + enableUtf8Validation?: boolean; +} + +export { BSONSymbol } + +export { 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 + * ```ts + * 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 + * ```ts + * 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; + /* Excluded from this release type: handleWriteError */ + abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/* Excluded from this release type: BulkOperationPrivate */ + +/* Excluded from this release type: BulkResult */ + +/** @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; + /** 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 { + private readonly result; + /** Number of documents inserted. */ + readonly insertedCount: number; + /** Number of documents matched for update. */ + readonly matchedCount: number; + /** Number of documents modified. */ + readonly modifiedCount: number; + /** Number of documents deleted. */ + readonly deletedCount: number; + /** Number of documents upserted. */ + readonly upsertedCount: number; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + readonly upsertedIds: { + [key: number]: any; + }; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + readonly insertedIds: { + [key: number]: any; + }; + private static generateIdMap; + /* Excluded from this release type: __constructor */ + /** 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 the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined; + 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[]; + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + options: ChangeStreamOptions & { + writeConcern?: never; + }; + 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; + /** Get the next available document from the Change Stream. */ + next(): Promise; + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + [Symbol.asyncIterator](): AsyncGenerator; + /** Is the cursor closed */ + get closed(): boolean; + /** Close the Change Stream */ + close(): Promise; + /** + * 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: 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 occurred 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. + * + * @sinceServerVersion 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. + * + * @sinceServerVersion 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 occurred 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 occurred 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 Omit { + /** + * 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 occurred 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 occurred 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 occurred 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 + */ + endSession(options?: EndSessionOptions): Promise; + /** + * 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. + */ + commitTransaction(): Promise; + /** + * Aborts the currently active transaction in this session. + */ + abortTransaction(): Promise; + /** + * 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 + * @see https://www.mongodb.com/docs/manual/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/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +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 + */ + insertOne(doc: OptionalUnlessRequiredId, options?: InsertOneOptions): Promise>; + /** + * 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 + */ + insertMany(docs: OptionalUnlessRequiredId[], options?: BulkWriteOptions): Promise>; + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * 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 + * @throws MongoDriverError if operations is not an array + */ + bulkWrite(operations: AnyBulkWriteOperation[], options?: BulkWriteOptions): Promise; + /** + * 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 + */ + updateOne(filter: Filter, update: UpdateFilter | Partial, options?: UpdateOptions): Promise; + /** + * 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 + */ + replaceOne(filter: Filter, replacement: WithoutId, options?: ReplaceOptions): Promise; + /** + * 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 + */ + updateMany(filter: Filter, update: UpdateFilter, options?: UpdateOptions): Promise; + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + deleteOne(filter?: Filter, options?: DeleteOptions): Promise; + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + deleteMany(filter?: Filter, options?: DeleteOptions): Promise; + /** + * 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 + */ + rename(newName: string, options?: RenameOptions): Promise; + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + drop(options?: DropCollectionOptions): Promise; + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + */ + findOne(): Promise | null>; + findOne(filter: Filter): Promise | null>; + findOne(filter: Filter, options: FindOptions): Promise | null>; + findOne(): Promise; + findOne(filter: Filter): Promise; + findOne(filter: Filter, options?: FindOptions): Promise; + /** + * 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 + */ + options(options?: OperationOptions): Promise; + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + isCapped(options?: OperationOptions): Promise; + /** + * 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 + * + * @example + * ```ts + * 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, options?: CreateIndexesOptions): Promise; + /** + * 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 + * + * @example + * ```ts + * 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[], options?: CreateIndexesOptions): Promise; + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + dropIndex(indexName: string, options?: DropIndexesOptions): Promise; + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + dropIndexes(options?: DropIndexesOptions): Promise; + /** + * 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 + */ + indexExists(indexes: string | string[], options?: IndexInformationOptions): Promise; + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + indexInformation(options?: IndexInformationOptions): Promise; + /** + * 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 + */ + estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise; + /** + * 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 + * + * @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(filter?: Document, options?: CountDocumentsOptions): Promise; + /** + * 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 + */ + distinct>(key: Key): Promise[Key]>>>; + distinct>(key: Key, filter: Filter): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, options: DistinctOptions): Promise[Key]>>>; + distinct(key: string): Promise; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + indexes(options?: IndexInformationOptions): Promise; + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + */ + stats(options?: CollStatsOptions): Promise; + /** + * 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 + */ + findOneAndDelete(filter: Filter, options?: FindOneAndDeleteOptions): Promise>; + /** + * 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 + */ + findOneAndReplace(filter: Filter, replacement: WithoutId, options?: FindOneAndReplaceOptions): Promise>; + /** + * 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 + */ + findOneAndUpdate(filter: Filter, update: UpdateFilter, options?: FindOneAndUpdateOptions): Promise>; + /** + * 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 use cases: + * - 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; + /** + * 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 implementation. + * 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 implementation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation; + /** + * 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 + */ + count(filter?: Filter, options?: CountOptions): Promise; +} + +/** @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 { + /** 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 { + /** 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 */ + interruptInUseConnections?: boolean; + /* 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; + connectionPoolReady(event: ConnectionPoolReadyEvent): 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; + /* Excluded from this release type: minPoolSizeCheckFrequencyMS */ +} + +/** + * An event published when a connection pool is ready + * @public + * @category Event + */ +export declare class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: __constructor */ +} + +/** + * 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. This option is deprecated in MongoDB 3.2+ and will be removed once no longer supported by the server. */ + 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 */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection */ + 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) */ + 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 */ + 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 Omit { + /** 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 */ +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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +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; + /** + * 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 + */ + createCollection(name: string, options?: CreateCollectionOptions): Promise>; + /** + * 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 + */ + command(command: Document, options?: RunCommandOptions): Promise; + /** + * 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 + */ + stats(options?: DbStatsOptions): Promise; + /** + * 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 + */ + renameCollection(fromCollection: string, toCollection: string, options?: RenameOptions): Promise>; + /** + * 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 + */ + dropCollection(name: string, options?: DropCollectionOptions): Promise; + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + dropDatabase(options?: DropDatabaseOptions): Promise; + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + collections(options?: ListCollectionsOptions): Promise; + /** + * 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 + */ + createIndex(name: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + addUser(username: string, passwordOrOptions?: string | AddUserOptions, options?: AddUserOptions): Promise; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + removeUser(username: string, options?: RemoveUserOptions): Promise; + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + setProfilingLevel(level: ProfilingLevel, options?: SetProfilingLevelOptions): Promise; + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + profilingLevel(options?: ProfilingLevelOptions): Promise; + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + indexInformation(name: string, options?: IndexInformationOptions): Promise; + /** + * 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 use cases: + * - 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; +} + +/* Excluded from this release type: DB_AGGREGATE_COLLECTION */ + +/** @public */ +export declare interface DbOptions extends BSONSerializeOptions, WriteConcernOptions { + /** 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; +} + +/** @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; +} + +export { deserialize } + +/* Excluded from this release type: DestroyOptions */ + +/** @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 = { + [P in keyof WithId]?: Condition[P]>; +} & 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 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(options?: CountOptions): Promise; + /** Execute the explain for the cursor */ + 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 | Document[]): BulkOperationBase; + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document | 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; + /** Specifies hint for the bulk operation. */ + hint(hint: Hint): this; +} + +/** + * @public + * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic + */ +export declare interface FindOptions extends Omit { + /** 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; + /** + * Option to enable an optimized code path for queries looking for a particular range of `ts` values in the oplog. Requires `tailable` to be true. + * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored. + */ + oplogReplay?: boolean; +} + +/** @public */ +export declare type Flatten = Type extends ReadonlyArray ? Item : Type; + +/** @public */ +export declare type GenericListener = (...args: any[]) => void; + +/** + * 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; + /** 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; + /** Removes this bucket's files collection, followed by its chunks collection. */ + drop(): Promise; +} + +/** @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. + */ + abort(): Promise; +} + +/** @public */ +export declare interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** + * 0-indexed non-negative byte offset from the beginning of the file + */ + start?: number; + /** + * 0-indexed non-negative byte offset to the end of the file contents + * to be returned by the stream. `end` is non-inclusive + */ + 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. + */ + abort(): Promise; + /** + * 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; + constructor(hostString: string); + inspect(): string; + toString(): 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: { + [key: string]: IndexDirection; + } | Map; +} + +/** @public */ +export declare type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | 'hashed' | 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 | bigint; + +/* Excluded from this release type: InternalAbstractCursorOptions */ + +/** @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: 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: 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: 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: 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: kPoolState */ + +/* 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: kServer_3 */ + +/* 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"]; + +/* Excluded from this release type: List */ + +/** @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 Omit { + /** 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 Omit { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +export { Long } + +/** @public */ +export declare type MatchKeysAndValues = Readonly> & Record; + +export { MaxKey } + +/* Excluded from this release type: MessageHeader */ + +/* Excluded from this release type: MessageStream */ + +/* Excluded from this release type: MessageStreamOptions */ +export { MinKey } + +/** + * @public + * @deprecated This type will be completely removed and findOneAndUpdate, + * findOneAndDelete, and findOneAndReplace will then return the + * actual result document. + */ +export declare interface ModifyResult { + value: WithId | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export declare const MONGO_CLIENT_EVENTS: readonly ["connectionPoolCreated", "connectionPoolReady", "connectionPoolCleared", "connectionPoolClosed", "connectionCreated", "connectionReady", "connectionClosed", "connectionCheckOutStarted", "connectionCheckOutFailed", "connectionCheckedOut", "connectionCheckedIn", "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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +export declare class MongoClient extends TypedEventEmitter { + /* Excluded from this release type: s */ + /* Excluded from this release type: topology */ + /* Excluded from this release type: mongoLogger */ + /* 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; + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + connect(): Promise; + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + close(force?: boolean): Promise; + /** + * 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, options?: MongoClientOptions): Promise; + /** Starts a new session on the server */ + 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 use cases: + * - 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; +} + +/** @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 + * @deprecated Please use the `writeConcern` option instead + */ + w?: W; + /** + * The write concern timeout + * @deprecated Please use the `writeConcern` option instead + */ + wtimeoutMS?: number; + /** + * The journal write concern + * @deprecated Please use the `writeConcern` option instead + */ + journal?: boolean; + /** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + writeConcern?: WriteConcern | WriteConcernSettings; + /** 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; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable in-use 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 | undefined; + /** + * 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 + * mongodb-client-encryption 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; + connectionGeneration?: number; + cause?: Error; + 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"; + readonly ResetPool: "ResetPool"; + readonly InterruptInUseConnections: "InterruptInUseConnections"; + readonly NoWritesPerformed: "NoWritesPerformed"; +}>; + +/** @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; +} + +/* Excluded from this release type: MongoLoggableComponent */ + +/* Excluded from this release type: MongoLogger */ + +/* Excluded from this release type: MongoLoggerEnvOptions */ + +/* Excluded from this release type: MongoLoggerMongoClientOptions */ + +/* Excluded from this release type: MongoLoggerOptions */ + +/** + * 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 + * mongodb-client-encryption 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 */ + /* Excluded from this release type: mongoLoggerOptions */ +} + +/** + * 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?: MongoError): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; + +/* Excluded from this release type: MonitorInterval */ + +/* Excluded from this release type: MonitorIntervalOptions */ + +/** @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/ + * + * @remarks + * Through testing we determined that a depth of 8 is safe for the typescript compiler + * and provides reasonable compilation times. This number is otherwise not special and + * should be changed if issues are found with this level of checking. Beyond this + * depth any helpers that make use of NestedPaths should devolve to not asserting any + * type safety on the input. + */ +export declare type NestedPaths = Depth['length'] extends 8 ? [] : Type extends string | number | bigint | 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 + ] : // child is not structured the same as the parent + [ + Key, + ...NestedPaths + ] | [Key]; +}[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; + +export { ObjectId } + +/* Excluded from this release type: OIDCMechanismServerStep1 */ + +/* Excluded from this release type: OIDCRefreshFunction */ + +/* Excluded from this release type: OIDCRequestFunction */ + +/* Excluded from this release type: OIDCRequestTokenResult */ + +/** @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: 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 required 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 { + /* Excluded from this release type: __constructor */ + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/** @public */ +export declare interface PkFactory { + createPk(): any; +} + +/* Excluded from this release type: PoolState */ + +/** @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 */ +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 */ + +/** + * 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 + * @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 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; +} + +export { 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 { + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error: MongoError | null; + topologyVersion: TopologyVersion | null; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me: string | null; + primary: string | null; + setName: string | null; + setVersion: number | null; + electionId: ObjectId | null; + logicalSessionTimeoutMinutes: number | null; + $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 | null): 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 */ +} + +/* Excluded from this release type: ServerOptions */ + +/* Excluded from this release type: ServerPrivate */ + +/* Excluded from this release type: ServerSelectionCallback */ + +/* Excluded from this release type: ServerSelectionRequest */ + +/* Excluded from this release type: ServerSelector */ + +/** + * 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; + +/* Excluded from this release type: SeverityLevel */ + +/** @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 + * @experimental + */ +export declare type StrictFilter = Partial | ({ + [Property in Join, []>, '.'>]?: Condition, Property>>; +} & RootFilterOperators>); + +/** + * @public + * @experimental + */ +export declare type StrictMatchKeysAndValues = Readonly<{ + [Property in Join, '.'>]?: PropertyType; +} & { + [Property in `${NestedPathsOfType}.$${`[${string}]` | ''}`]?: ArrayElement>; +} & { + [Property in `${NestedPathsOfType[]>}.$${`[${string}]` | ''}.${string}`]?: any; +} & Document>; + +/** + * @public + * @experimental + */ +export declare type StrictUpdateFilter = { + $currentDate?: OnlyFieldsOfType; + $inc?: OnlyFieldsOfType; + $min?: StrictMatchKeysAndValues; + $max?: StrictMatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: StrictMatchKeysAndValues; + $setOnInsert?: StrictMatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType; +} & Document; + +/** @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 | null; + maxSetVersion: number | null; + maxElectionId: ObjectId | null; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes: number | null; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion: number; + /** + * Create a TopologyDescription + */ + constructor(topologyType: TopologyType, serverDescriptions?: Map | null, setName?: string | null, maxSetVersion?: number | null, maxElectionId?: ObjectId | null, commonWireVersion?: number | null, options?: TopologyDescriptionOptions | null); + /* Excluded from this release type: updateFromSrvPollingEvent */ + /* Excluded from this release type: update */ + get error(): MongoServerError | null; + /** + * 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 */ +} + +/* Excluded from this release type: TopologyOptions */ + +/* 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?: ReadPreferenceLike; + /** 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 { + /* Excluded from this release type: __constructor */ + 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; + }>; + /** + * A document containing additional information about any ambiguous update paths from the update event. The document + * maps the full ambiguous update path to an array containing the actual resolved components of the path. For example, + * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like + * the following: + * + * ``` + * { + * 'a.0': ['a', '0'] + * } + * ``` + * + * This field is only present when there are ambiguous paths that are updated as a part of the update event and `showExpandedEvents` + * is enabled for the change stream. + * @sinceServerVersion 6.1.0 + */ + disambiguatedPaths?: Document; +} + +/** @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?: Hint; + /** 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; + 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/1_ActivityWatchProducer/node_modules/mongodb/package.json b/1_ActivityWatchProducer/node_modules/mongodb/package.json new file mode 100644 index 00000000..308108ce --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/package.json @@ -0,0 +1,156 @@ +{ + "name": "mongodb", + "version": "5.1.0", + "description": "The official MongoDB driver for Node.js", + "main": "lib/index.js", + "files": [ + "lib", + "src", + "etc/prepare.js", + "mongodb.d.ts", + "tsconfig.json" + ], + "types": "mongodb.d.ts", + "repository": { + "type": "git", + "url": "git@github.com:mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "official" + ], + "author": { + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" + }, + "dependencies": { + "bson": "^5.0.1", + "mongodb-connection-string-url": "^2.6.0", + "socks": "^2.7.1" + }, + "optionalDependencies": { + "saslprep": "^1.0.3" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.201.0", + "mongodb-client-encryption": "^2.3.0", + "snappy": "^7.2.2" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "snappy": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + } + }, + "devDependencies": { + "@iarna/toml": "^2.2.5", + "@istanbuljs/nyc-config-typescript": "^1.0.2", + "@microsoft/api-extractor": "^7.33.7", + "@microsoft/tsdoc-config": "^0.16.2", + "@mongodb-js/zstd": "^1.0.0", + "@types/chai": "^4.3.3", + "@types/chai-subset": "^1.3.3", + "@types/express": "^4.17.14", + "@types/kerberos": "^1.1.1", + "@types/mocha": "^10.0.0", + "@types/node": "^18.11.0", + "@types/saslprep": "^1.0.1", + "@types/semver": "^7.3.12", + "@types/sinon": "^10.0.13", + "@types/sinon-chai": "^3.2.8", + "@types/whatwg-url": "^11.0.0", + "@typescript-eslint/eslint-plugin": "^5.48.0", + "@typescript-eslint/parser": "^5.48.0", + "chai": "^4.3.6", + "chai-subset": "^1.6.0", + "chalk": "^4.1.2", + "eslint": "^8.31.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-simple-import-sort": "^8.0.0", + "eslint-plugin-tsdoc": "^0.2.17", + "express": "^4.18.2", + "js-yaml": "^4.1.0", + "mocha": "^9.2.2", + "mocha-sinon": "^2.1.2", + "mongodb-legacy": "^4.0.0", + "nyc": "^15.1.0", + "prettier": "^2.7.1", + "rimraf": "^3.0.2", + "semver": "^7.3.8", + "sinon": "^13.0.1", + "sinon-chai": "^3.7.0", + "snappy": "^7.2.2", + "source-map-support": "^0.5.21", + "standard-version": "^9.5.0", + "ts-node": "^10.9.1", + "tsd": "^0.25.0", + "typescript": "^4.9.4", + "typescript-cached-transpile": "^0.0.6", + "v8-heapsnapshot": "^1.2.0", + "xml2js": "^0.4.23", + "yargs": "^17.6.0" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=14.20.1" + }, + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "scripts": { + "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:lambda": "mocha --config test/mocha_lambda.json test/integration/node-specific/examples/handler.test.js", + "check:lambda:aws": "mocha --config test/mocha_lambda.json test/integration/node-specific/examples/aws_handler.test.js", + "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:dependencies": "mocha test/action/dependency.test.ts", + "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.ts", + "check:oidc": "mocha --config test/mocha_mongodb.json test/integration/auth/mongodb_oidc.test.ts", + "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": "bash etc/check-remote.sh && 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" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/admin.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/admin.ts new file mode 100644 index 00000000..9e9a64e0 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/admin.ts @@ -0,0 +1,174 @@ +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'; + +/** @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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +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 + */ + async command(command: Document, options?: RunCommandOptions): Promise { + return executeOperation( + this.s.db.s.client, + new RunCommandOperation(this.s.db, command, { dbName: 'admin', ...options }) + ); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async buildInfo(options?: CommandOperationOptions): Promise { + return this.command({ buildinfo: 1 }, options); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async serverInfo(options?: CommandOperationOptions): Promise { + return this.command({ buildinfo: 1 }, options); + } + + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + async serverStatus(options?: CommandOperationOptions): Promise { + return this.command({ serverStatus: 1 }, options); + } + + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + async ping(options?: CommandOperationOptions): Promise { + return this.command({ ping: 1 }, options); + } + + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + async addUser( + username: string, + passwordOrOptions?: string | AddUserOptions, + options?: AddUserOptions + ): Promise { + options = + options != null && typeof options === 'object' + ? options + : passwordOrOptions != null && typeof passwordOrOptions === 'object' + ? passwordOrOptions + : undefined; + const password = typeof passwordOrOptions === 'string' ? passwordOrOptions : undefined; + return executeOperation( + this.s.db.s.client, + new AddUserOperation(this.s.db, username, password, { dbName: 'admin', ...options }) + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username: string, options?: RemoveUserOptions): Promise { + return executeOperation( + this.s.db.s.client, + new RemoveUserOperation(this.s.db, username, { dbName: 'admin', ...options }) + ); + } + + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + async validateCollection( + collectionName: string, + options: ValidateCollectionOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new ValidateCollectionOperation(this, collectionName, options) + ); + } + + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + async listDatabases(options?: ListDatabasesOptions): Promise { + return executeOperation(this.s.db.s.client, new ListDatabasesOperation(this.s.db, options)); + } + + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + async replSetGetStatus(options?: CommandOperationOptions): Promise { + return this.command({ replSetGetStatus: 1 }, options); + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/bson.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/bson.ts new file mode 100644 index 00000000..7f335f1c --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/bson.ts @@ -0,0 +1,117 @@ +import type { DeserializeOptions, SerializeOptions } from 'bson'; + +export { + Binary, + BSON, + BSONRegExp, + BSONSymbol, + BSONType, + calculateObjectSize, + Code, + DBRef, + Decimal128, + deserialize, + Document, + Double, + Int32, + Long, + MaxKey, + MinKey, + ObjectId, + serialize, + Timestamp +} from 'bson'; + +/** + * BSON Serialization options. + * @public + */ +export interface BSONSerializeOptions + extends Omit, + Omit< + DeserializeOptions, + | 'evalFunctions' + | 'cacheFunctions' + | 'cacheFunctionsCrc32' + | 'allowObjectSmallerThanBufferSize' + | 'index' + | 'validation' + > { + /** + * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html) + * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize). + * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe) + * for more detail about what "unsafe" refers to in this context. + * If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate + * your own buffer and clone the contents: + * + * @example + * ```ts + * const raw = await collection.findOne({}, { raw: true }); + * const myBuffer = Buffer.alloc(raw.byteLength); + * myBuffer.set(raw, 0); + * // Only save and use `myBuffer` beyond this point + * ``` + * + * @remarks + * Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)). + * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work. + */ + raw?: boolean; + + /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */ + enableUtf8Validation?: boolean; +} + +export function pluckBSONSerializeOptions(options: BSONSerializeOptions): BSONSerializeOptions { + const { + fieldsAsRaw, + useBigInt64, + promoteValues, + promoteBuffers, + promoteLongs, + serializeFunctions, + ignoreUndefined, + bsonRegExp, + raw, + enableUtf8Validation + } = options; + return { + fieldsAsRaw, + useBigInt64, + 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, + useBigInt64: options?.useBigInt64 ?? parentOptions?.useBigInt64 ?? 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/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/common.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/common.ts new file mode 100644 index 00000000..566c2464 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/common.ts @@ -0,0 +1,1282 @@ +import { BSONSerializeOptions, Document, ObjectId, resolveBSONOptions } 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 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 }; + +/** @internal */ +export interface BulkResult { + ok: number; + writeErrors: WriteError[]; + writeConcernErrors: WriteConcernError[]; + insertedIds: Document[]; + nInserted: number; + nUpserted: number; + nMatched: number; + nModified: number; + nRemoved: number; + upserted: 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 { + private readonly result: BulkResult; + /** Number of documents inserted. */ + readonly insertedCount: number; + /** Number of documents matched for update. */ + readonly matchedCount: number; + /** Number of documents modified. */ + readonly modifiedCount: number; + /** Number of documents deleted. */ + readonly deletedCount: number; + /** Number of documents upserted. */ + readonly upsertedCount: number; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + readonly upsertedIds: { [key: number]: any }; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + readonly insertedIds: { [key: number]: any }; + + private static generateIdMap(ids: Document[]): { [key: number]: any } { + const idMap: { [index: number]: any } = {}; + for (const doc of ids) { + idMap[doc.index] = doc._id; + } + return idMap; + } + + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult: BulkResult) { + this.result = bulkResult; + this.insertedCount = this.result.nInserted ?? 0; + this.matchedCount = this.result.nMatched ?? 0; + this.modifiedCount = this.result.nModified ?? 0; + this.deletedCount = this.result.nRemoved ?? 0; + this.upsertedCount = this.result.upserted.length ?? 0; + this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted); + this.insertedIds = BulkWriteResult.generateIdMap(this.result.insertedIds); + Object.defineProperty(this, 'result', { value: this.result, enumerable: false }); + } + + /** 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 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 }); + } + } + + toString(): string { + return `BulkWriteResult(${this.result})`; + } + + 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; + } + + 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())})`; + } +} + +/** 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; + } + + // 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 + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + 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 | 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 | 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; + } + + /** Specifies hint for the bulk operation. */ + hint(hint: Hint): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.hint = hint; + 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; + /** 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 + * ```ts + * 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 + * ```ts + * 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; + } + + async execute(options: BulkWriteOptions = {}): Promise { + if (this.s.executed) { + throw new MongoBatchReExecutionError(); + } + + 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) { + throw new MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + } + + 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); + } + + /** + * 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; + } +}); + +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/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/ordered.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/ordered.ts new file mode 100644 index 00000000..97ee6444 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/ordered.ts @@ -0,0 +1,83 @@ +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 { + /** @internal */ + 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/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/unordered.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/unordered.ts new file mode 100644 index 00000000..5f2e562f --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/bulk/unordered.ts @@ -0,0 +1,110 @@ +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 { + /** @internal */ + 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/1_ActivityWatchProducer/node_modules/mongodb/src/change_stream.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/change_stream.ts new file mode 100644 index 00000000..d4b1c7ee --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/change_stream.ts @@ -0,0 +1,958 @@ +import type { Readable } from 'stream'; + +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 { filterOptions, getTopology, 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; + +/** + * 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 Omit { + /** + * 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. + * + * @sinceServerVersion 6.1.0 + */ + collectionUUID: Binary; +} + +/** @public */ +export interface ChangeStreamDocumentOperationDescription { + /** + * An description of the operation. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * @sinceServerVersion 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 occurred 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 occurred 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 occurred 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 occurred 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 occurred 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 occurred 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; + }>; + + /** + * A document containing additional information about any ambiguous update paths from the update event. The document + * maps the full ambiguous update path to an array containing the actual resolved components of the path. For example, + * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like + * the following: + * + * ``` + * { + * 'a.0': ['a', '0'] + * } + * ``` + * + * This field is only present when there are ambiguous paths that are updated as a part of the update event and `showExpandedEvents` + * is enabled for the change stream. + * @sinceServerVersion 6.1.0 + */ + disambiguatedPaths?: Document; +} + +/** @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[]; + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + options: ChangeStreamOptions & { writeConcern?: never }; + 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 }; + delete this.options.writeConcern; + + 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 */ + async hasNext(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const hasNext = await this.cursor.hasNext(); + return hasNext; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + /** Get the next available document from the Change Stream. */ + async next(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.next(); + const processedChange = this._processChange(change ?? null); + return processedChange; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + async tryNext(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.tryNext(); + return change ?? null; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + async *[Symbol.asyncIterator](): AsyncGenerator { + if (this.closed) { + return; + } + + try { + // Change streams run indefinitely as long as errors are resumable + // So the only loop breaking condition is if `next()` throws + while (true) { + yield await this.next(); + } + } finally { + try { + await this.close(); + } catch { + // we're not concerned with errors from close() + } + } + } + + /** Is the cursor closed */ + get closed(): boolean { + return this[kClosed] || this.cursor.closed; + } + + /** Close the Change Stream */ + async close(): Promise { + this[kClosed] = true; + + const cursor = this.cursor; + try { + await cursor.close(); + } finally { + this._endStream(); + } + } + + /** + * 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().catch(() => null); + } + + /** @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 */ + private async _processErrorIteratorMode(changeStreamError: AnyError) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + + if (!isResumableError(changeStreamError, this.cursor.maxWireVersion)) { + try { + await this.close(); + } catch { + // ignore errors from close + } + throw changeStreamError; + } + + await this.cursor.close().catch(() => null); + const topology = getTopology(this.parent); + try { + await topology.selectServerAsync(this.cursor.readPreference, {}); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + } catch { + // if the topology can't reconnect, close the stream + await this.close(); + throw changeStreamError; + } + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/auth_provider.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/auth_provider.ts new file mode 100644 index 00000000..2a38abe9 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/gssapi.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/gssapi.ts new file mode 100644 index 00000000..924fbde6 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/gssapi.ts @@ -0,0 +1,239 @@ +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 = { + 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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts new file mode 100644 index 00000000..384c8331 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts @@ -0,0 +1,236 @@ +// Resolves the default auth mechanism according to +import type { Document } from '../../bson'; +import { + MongoAPIError, + MongoInvalidArgumentError, + MongoMissingCredentialsError +} from '../../error'; +import { GSSAPICanonicalizationValue } from './gssapi'; +import type { OIDCRefreshFunction, OIDCRequestFunction } from './mongodb_oidc'; +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; +} + +/** + * TODO: NODE-5035: Make OIDC properties public. + * + * @public + * */ +export interface AuthMechanismProperties extends Document { + SERVICE_HOST?: string; + SERVICE_NAME?: string; + SERVICE_REALM?: string; + CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue; + AWS_SESSION_TOKEN?: string; + /** @internal Name for the OIDC device workflow */ + DEVICE_NAME?: 'aws' | 'azure' | 'gcp'; + /** @internal Similar to a username, is require by OIDC when more than one IDP is configured. */ + PRINCIPAL_NAME?: string; + /** @internal User provided callback to get OIDC auth credentials */ + REQUEST_TOKEN_CALLBACK?: OIDCRequestFunction; + /** @internal User provided callback to refresh OIDC auth credentials */ + REFRESH_TOKEN_CALLBACK?: OIDCRefreshFunction; +} + +/** @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 + }; + } + } + + 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 (this.mechanism === AuthMechanism.MONGODB_OIDC) { + if (this.username) { + throw new MongoInvalidArgumentError( + `Username not permitted for mechanism '${this.mechanism}'. Use PRINCIPAL_NAME instead.` + ); + } + + if (this.mechanismProperties.PRINCIPAL_NAME && this.mechanismProperties.DEVICE_NAME) { + throw new MongoInvalidArgumentError( + `PRINCIPAL_NAME and DEVICE_NAME may not be used together for mechanism '${this.mechanism}'.` + ); + } + + if (this.mechanismProperties.DEVICE_NAME && this.mechanismProperties.DEVICE_NAME !== 'aws') { + throw new MongoInvalidArgumentError( + `Currently only a DEVICE_NAME of 'aws' is supported for mechanism '${this.mechanism}'.` + ); + } + + if ( + this.mechanismProperties.REFRESH_TOKEN_CALLBACK && + !this.mechanismProperties.REQUEST_TOKEN_CALLBACK + ) { + throw new MongoInvalidArgumentError( + `A REQUEST_TOKEN_CALLBACK must be provided when using a REFRESH_TOKEN_CALLBACK for mechanism '${this.mechanism}'` + ); + } + + if ( + !this.mechanismProperties.DEVICE_NAME && + !this.mechanismProperties.REQUEST_TOKEN_CALLBACK + ) { + throw new MongoInvalidArgumentError( + `Either a DEVICE_NAME or a REQUEST_TOKEN_CALLBACK must be specified 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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongocr.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongocr.ts new file mode 100644 index 00000000..232378f0 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts new file mode 100644 index 00000000..5d9007dc --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts @@ -0,0 +1,336 @@ +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, getAwsCredentialProvider } from '../../deps'; +import { + MongoAWSError, + MongoCompatibilityError, + MongoMissingCredentialsError, + MongoRuntimeError +} from '../../error'; +import { ByteUtils, 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 = { + useBigInt64: false, + 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 (!ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) { + // throw because the serverNonce's leading 32 bytes must equal the client nonce's 32 bytes + // https://github.com/mongodb/specifications/blob/875446db44aade414011731840831f38a6c668df/source/auth/auth.rst#id11 + + // 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': ByteUtils.toBase64(serverNonce), + '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; +} + +/* @internal */ +export interface AWSCredentials { + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: 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 + } + }) + ); + } + + const credentialProvider = getAwsCredentialProvider(); + + // Check if the AWS credential provider from the SDK is present. If not, + // use the old method. + if ('kModuleError' in credentialProvider) { + // 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); + } + ); + } + ); + } + ); + } else { + /* + * Creates a credential provider that will attempt to find credentials from the + * following sources (listed in order of precedence): + * + * - Environment variables exposed via process.env + * - SSO credentials from token cache + * - Web identity token credentials + * - Shared credentials and config ini files + * - The EC2/ECS Instance Metadata Service + */ + const { fromNodeProviderChain } = credentialProvider; + const provider = fromNodeProviderChain(); + provider() + .then((creds: AWSCredentials) => { + done({ + AccessKeyId: creds.accessKeyId, + SecretAccessKey: creds.secretAccessKey, + Token: creds.sessionToken, + Expiration: creds.expiration + }); + }) + .catch((error: Error) => { + callback(new MongoAWSError(error.message)); + }); + } +} + +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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongodb_oidc.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongodb_oidc.ts new file mode 100644 index 00000000..2763ef54 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/mongodb_oidc.ts @@ -0,0 +1,39 @@ +/** + * TODO: NODE-5035: Make API public + * + * @internal */ +export interface OIDCMechanismServerStep1 { + authorizeEndpoint?: string; + tokenEndpoint?: string; + deviceAuthorizeEndpoint?: string; + clientId: string; + clientSecret?: string; + requestScopes?: string[]; +} + +/** + * TODO: NODE-5035: Make API public + * + * @internal */ +export interface OIDCRequestTokenResult { + accessToken: string; + expiresInSeconds?: number; + refreshToken?: string; +} + +/** + * TODO: NODE-5035: Make API public + * + * @internal */ +export type OIDCRequestFunction = ( + idl: OIDCMechanismServerStep1 +) => Promise; + +/** + * TODO: NODE-5035: Make API public + * + * @internal */ +export type OIDCRefreshFunction = ( + idl: OIDCMechanismServerStep1, + result: OIDCRequestTokenResult +) => Promise; diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/plain.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/plain.ts new file mode 100644 index 00000000..94b19a52 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/providers.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/providers.ts new file mode 100644 index 00000000..dc286a4b --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/providers.ts @@ -0,0 +1,24 @@ +/** @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', + /** @internal TODO: NODE-5035: Make mechanism public. */ + MONGODB_OIDC: 'MONGODB-OIDC' +} 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_OIDC, + AuthMechanism.MONGODB_X509 +]); diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/scram.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/scram.ts new file mode 100644 index 00000000..7a339151 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/x509.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/auth/x509.ts new file mode 100644 index 00000000..a12e6f9d --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/command_monitoring_events.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/command_monitoring_events.ts new file mode 100644 index 00000000..40c3419a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/command_monitoring_events.ts @@ -0,0 +1,301 @@ +import type { Document, ObjectId } from '../bson'; +import { LEGACY_HELLO_COMMAND, LEGACY_HELLO_COMMAND_CAMEL_CASE } from '../constants'; +import { calculateDurationInMs, deepCopy } from '../utils'; +import { 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 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 (!reply) { + return reply; + } + + 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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/commands.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/commands.ts new file mode 100644 index 00000000..6364d33d --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/commands.ts @@ -0,0 +1,712 @@ +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_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; + +/** @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(): Uint8Array[] { + 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 MessageHeader { + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; +} + +/** @internal */ +export interface OpResponseOptions extends BSONSerializeOptions { + 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; + useBigInt64: 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 ?? { + useBigInt64: false, + 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.useBigInt64 = typeof this.opts.useBigInt64 === 'boolean' ? this.opts.useBigInt64 : false; + 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 useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64; + 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 = { + useBigInt64, + 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: Uint8Array[], 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): Uint8Array { + 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; + useBigInt64: 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 ?? { + useBigInt64: false, + 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.useBigInt64 = typeof this.opts.useBigInt64 === 'boolean' ? this.opts.useBigInt64 : false; + 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 useBigInt64 = options.useBigInt64 ?? this.opts.useBigInt64; + 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 = { + useBigInt64, + 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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connect.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connect.ts new file mode 100644 index 00000000..a69289be --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connect.ts @@ -0,0 +1,523 @@ +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({ force: false }); + } + _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; +} + +/** + * @internal + * + * This function is only exposed for testing purposes. + */ +export 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]: 1, + helloOk: true, + client: options.metadata || makeClientMetadata(options), + compression: compressors + }; + + if (options.loadBalanced === true) { + handshakeDoc.loadBalanced = true; + } + + 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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection.ts new file mode 100644 index 00000000..4ee55d3e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection.ts @@ -0,0 +1,743 @@ +import { clearTimeout, setTimeout } from 'timers'; + +import type { BSONSerializeOptions, Document, ObjectId } 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 { 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, Msg, Query, Response, WriteProtocolMessageType } from './commands'; +import type { Stream } from './connect'; +import { MessageStream, OperationDescription } from './message_stream'; +import { StreamDescription, StreamDescriptionOptions } from './stream_description'; +import { 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 kDelayedTimeoutId = Symbol('delayedTimeoutId'); + +const INVALID_QUEUE_SIZE = 'Connection internal queue contains more than 1 operation description'; + +/** @internal */ +export interface CommandOptions extends BSONSerializeOptions { + command?: boolean; + secondaryOk?: boolean; + /** Specify read preference if command supports it */ + readPreference?: ReadPreferenceLike; + monitoring?: 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; +} + +/** @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; +} + +/** @internal */ +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; + /** Indicates that the connection (including underlying TCP socket) has been closed. */ + closed: 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[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) { + this.cleanup(true, error); + } + + onClose() { + const message = `connection ${this.id} to ${this.address} closed`; + this.cleanup(true, new MongoNetworkError(message)); + } + + onTimeout() { + this[kDelayedTimeoutId] = setTimeout(() => { + const message = `connection ${this.id} to ${this.address} timed out`; + const beforeHandshake = this.hello == null; + this.cleanup(true, new MongoNetworkTimeoutError(message, { beforeHandshake })); + }, 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); + let operationDescription = this[kQueue].get(message.responseTo); + + if (!operationDescription && this.isMonitoringConnection) { + // This is how we recover when the initial hello's requestId is not + // the responseTo when hello responses have been skipped: + + // First check if the map is of invalid size + if (this[kQueue].size > 1) { + this.cleanup(true, new MongoRuntimeError(INVALID_QUEUE_SIZE)); + } else { + // Get the first orphaned operation description. + const entry = this[kQueue].entries().next(); + if (entry.value != null) { + const [requestId, orphaned]: [number, OperationDescription] = entry.value; + // If the orphaned operation description exists then set it. + operationDescription = orphaned; + // Remove the entry with the bad request id from the queue. + this[kQueue].delete(requestId); + } + } + } + + 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) { + // If the operation description check above does find an orphaned + // description and sets the operationDescription then this line will put one + // back in the queue with the correct requestId and will resolve not being able + // to find the next one via the responseTo of the next streaming hello. + 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), 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, message.documents[0]); + } + + destroy(options: DestroyOptions, callback?: Callback): void { + if (this.closed) { + process.nextTick(() => callback?.()); + return; + } + if (typeof callback === 'function') { + this.once('close', () => process.nextTick(() => callback())); + } + + // load balanced mode requires that these listeners remain on the connection + // after cleanup on timeouts, errors or close so we remove them before calling + // cleanup. + this.removeAllListeners(Connection.PINNED); + this.removeAllListeners(Connection.UNPINNED); + const message = `connection ${this.id} to ${this.address} closed`; + this.cleanup(options.force, new MongoNetworkError(message)); + } + + /** + * A method that cleans up the connection. When `force` is true, this method + * forcibly destroys the socket. + * + * If an error is provided, any in-flight operations will be closed with the error. + * + * This method does nothing if the connection is already closed. + */ + private cleanup(force: boolean, error?: Error): void { + if (this.closed) { + return; + } + + this.closed = true; + + const completeCleanup = () => { + for (const op of this[kQueue].values()) { + op.cb(error); + } + + this[kQueue].clear(); + + this.emit(Connection.CLOSE); + }; + + this[kStream].removeAllListeners(); + this[kMessageStream].removeAllListeners(); + + this[kMessageStream].destroy(); + + if (force) { + this[kStream].destroy(); + completeCleanup(); + return; + } + + if (!this[kStream].writableEnded) { + this[kStream].end(() => { + this[kStream].destroy(); + completeCleanup(); + }); + } else { + completeCleanup(); + } + } + + command( + ns: MongoDBNamespace, + cmd: Document, + options: CommandOptions | undefined, + callback: Callback + ): void { + 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); + } + } +} + +/** @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; + } + + // Save sort or indexKeys based on the command being run + // the encrypt API serializes our JS objects to BSON to pass to the native code layer + // and then deserializes the encrypted result, the protocol level components + // of the command (ex. sort) are then converted to JS objects potentially losing + // import key order information. These fields are never encrypted so we can save the values + // from before the encryption and replace them after encryption has been performed + const sort: Map | null = cmd.find || cmd.findAndModify ? cmd.sort : null; + const indexKeys: Map[] | null = cmd.createIndexes + ? cmd.indexes.map((index: { key: Map }) => index.key) + : null; + + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + + // Replace the saved values + if (sort != null && (cmd.find || cmd.findAndModify)) { + encrypted.sort = sort; + } + if (indexKeys != null && cmd.createIndexes) { + for (const [offset, index] of indexKeys.entries()) { + encrypted.indexes[offset].key = index; + } + } + + 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(); + } + + const { remoteAddress, remotePort } = stream; + if (typeof remoteAddress === 'string' && typeof remotePort === 'number') { + return HostAddress.fromHostPort(remoteAddress, remotePort).toString(); + } + + return uuidV4().toString('hex'); +} + +function write( + conn: Connection, + command: WriteProtocolMessageType, + options: CommandOptions, + callback: Callback +) { + options = options ?? {}; + const operationDescription: OperationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + noResponse: typeof options.noResponse === 'boolean' ? options.noResponse : false, + documentsReturnedIn: options.documentsReturnedIn, + command: !!options.command, + + // for BSON parsing + useBigInt64: typeof options.useBigInt64 === 'boolean' ? options.useBigInt64 : 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, + 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) => { + // Command monitoring spec states that if ok is 1, then we must always emit + // a command suceeded event, even if there's an error. Write concern errors + // will have an ok: 1 in their reply. + if (err && reply?.ok !== 1) { + 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') { + // Since we're passing through the reply with the write concern error now, we + // need it not to be provided to the original callback in this case so + // retryability does not get tricked into thinking the command actually + // succeeded. + callback(err, err instanceof MongoWriteConcernError ? undefined : 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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection_pool.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection_pool.ts new file mode 100644 index 00000000..ca3270db --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection_pool.ts @@ -0,0 +1,841 @@ +import { clearTimeout, 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_POOL_READY, + CONNECTION_READY +} from '../constants'; +import { + MongoError, + MongoInvalidArgumentError, + MongoNetworkError, + MongoRuntimeError, + MongoServerError +} from '../error'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import { Callback, eachAsync, List, makeCounter } from '../utils'; +import { connect } from './connect'; +import { Connection, ConnectionEvents, ConnectionOptions } from './connection'; +import { + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionPoolReadyEvent, + ConnectionReadyEvent +} from './connection_pool_events'; +import { + PoolClearedError, + PoolClearedOnNetworkError, + PoolClosedError, + WaitQueueTimeoutError +} from './errors'; +import { ConnectionPoolMetrics } from './metrics'; + +/** @internal */ +const kServer = Symbol('server'); +/** @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'); +/** @internal */ +const kPoolState = Symbol('poolState'); + +/** @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 */ + minPoolSizeCheckFrequencyMS?: number; +} + +/** @internal */ +export interface WaitQueueMember { + callback: Callback; + timer?: NodeJS.Timeout; + [kCancelled]?: boolean; +} + +/** @internal */ +export const PoolState = Object.freeze({ + paused: 'paused', + ready: 'ready', + closed: 'closed' +} as const); + +/** @public */ +export interface CloseOptions { + force?: boolean; +} + +/** @public */ +export type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolReady(event: ConnectionPoolReadyEvent): 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 { + options: Readonly; + [kPoolState]: typeof PoolState[keyof typeof PoolState]; + [kServer]: Server; + [kConnections]: List; + [kPending]: number; + [kCheckedOut]: Set; + [kMinPoolSizeTimer]?: NodeJS.Timeout; + /** + * An integer representing the SDAM generation of the pool + */ + [kGeneration]: number; + /** + * A map of generations to service ids + */ + [kServiceGenerations]: Map; + [kConnectionCounter]: Generator; + [kCancellationToken]: CancellationToken; + [kWaitQueue]: List; + [kMetrics]: ConnectionPoolMetrics; + [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 each time the connection pool is marked ready + * @event + */ + static readonly CONNECTION_POOL_READY = CONNECTION_POOL_READY; + /** + * 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; + + constructor(server: Server, options: ConnectionPoolOptions) { + super(); + + 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, + minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100, + 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[kPoolState] = PoolState.paused; + this[kServer] = server; + this[kConnections] = new List(); + this[kPending] = 0; + this[kCheckedOut] = new Set(); + 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 List(); + this[kMetrics] = new ConnectionPoolMetrics(); + this[kProcessingWaitQueue] = false; + + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new ConnectionPoolCreatedEvent(this)); + }); + } + + /** The address of the endpoint the pool is connected to */ + get address(): string { + return this.options.hostAddress.toString(); + } + + /** + * Check if the pool has been closed + * + * TODO(NODE-3263): We can remove this property once shell no longer needs it + */ + get closed(): boolean { + return this[kPoolState] === PoolState.closed; + } + + /** 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].size; + } + + get waitQueueSize(): number { + return this[kWaitQueue].length; + } + + get loadBalanced(): boolean { + return this.options.loadBalanced; + } + + get serviceGenerations(): Map { + return this[kServiceGenerations]; + } + + get serverError() { + return this[kServer].description.error; + } + + /** + * This is exposed ONLY for use in mongosh, to enable + * killing all connections if a user quits the shell with + * operations in progress. + * + * This property may be removed as a part of NODE-3263. + */ + get checkedOutConnections() { + return this[kCheckedOut]; + } + + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + private waitQueueErrorMetrics(): string { + return this[kMetrics].info(this.options.maxPoolSize); + } + + /** + * Set the pool state to "ready" + */ + ready(): void { + if (this[kPoolState] !== PoolState.paused) { + return; + } + this[kPoolState] = PoolState.ready; + this.emit(ConnectionPool.CONNECTION_POOL_READY, new ConnectionPoolReadyEvent(this)); + clearTimeout(this[kMinPoolSizeTimer]); + this.ensureMinPoolSize(); + } + + /** + * 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) + ); + + 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(() => this.processWaitQueue()); + } + + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection: Connection): void { + if (!this[kCheckedOut].has(connection)) { + return; + } + const poolClosed = this.closed; + const stale = this.connectionIsStale(connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + + this[kCheckedOut].delete(connection); + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new ConnectionCheckedInEvent(this, connection)); + + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + this.destroyConnection(connection, reason); + } + + process.nextTick(() => this.processWaitQueue()); + } + + /** + * 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(options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {}): void { + if (this.closed) { + return; + } + + // handle load balanced case + if (this.loadBalanced) { + const { serviceId } = options; + if (!serviceId) { + throw new MongoRuntimeError( + 'ConnectionPool.clear() called in load balanced mode with no 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) { + 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); + } + this.emit( + ConnectionPool.CONNECTION_POOL_CLEARED, + new ConnectionPoolClearedEvent(this, { serviceId }) + ); + return; + } + // handle non load-balanced case + const interruptInUseConnections = options.interruptInUseConnections ?? false; + const oldGeneration = this[kGeneration]; + this[kGeneration] += 1; + const alreadyPaused = this[kPoolState] === PoolState.paused; + this[kPoolState] = PoolState.paused; + + this.clearMinPoolSizeTimer(); + if (!alreadyPaused) { + this.emit( + ConnectionPool.CONNECTION_POOL_CLEARED, + new ConnectionPoolClearedEvent(this, { interruptInUseConnections }) + ); + } + + if (interruptInUseConnections) { + process.nextTick(() => this.interruptInUseConnections(oldGeneration)); + } + + this.processWaitQueue(); + } + + /** + * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError. + * + * Only connections where `connection.generation <= minGeneration` are killed. + */ + private interruptInUseConnections(minGeneration: number) { + for (const connection of this[kCheckedOut]) { + if (connection.generation <= minGeneration) { + this.checkIn(connection); + connection.onError(new PoolClearedOnNetworkError(this)); + } + } + } + + /** 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'); + + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + + this[kPoolState] = PoolState.closed; + this.clearMinPoolSizeTimer(); + this.processWaitQueue(); + + eachAsync( + this[kConnections].toArray(), + (conn, cb) => { + this.emit( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, conn, 'poolClosed') + ); + conn.destroy({ force: !!options.force }, 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); + } + }); + }); + } + + /** Clear the min pool size timer */ + private clearMinPoolSizeTimer(): void { + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + clearTimeout(minPoolSizeTimer); + } + } + + private destroyConnection(connection: Connection, reason: string) { + this.emit( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, connection, reason) + ); + // destroy the connection + process.nextTick(() => connection.destroy({ force: false })); + } + + private connectionIsStale(connection: Connection) { + const serviceId = connection.serviceId; + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + return connection.generation !== generation; + } + + return connection.generation !== this[kGeneration]; + } + + private connectionIsIdle(connection: Connection) { + return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS); + } + + /** + * Destroys a connection if the connection is perished. + * + * @returns `true` if the connection was destroyed, `false` otherwise. + */ + private destroyConnectionIfPerished(connection: Connection): boolean { + const isStale = this.connectionIsStale(connection); + const isIdle = this.connectionIsIdle(connection); + if (!isStale && !isIdle && !connection.closed) { + return false; + } + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + this.destroyConnection(connection, reason); + return true; + } + + private createConnection(callback: Callback) { + const connectOptions: ConnectionOptions = { + ...this.options, + id: this[kConnectionCounter].next().value, + generation: this[kGeneration], + cancellationToken: this[kCancellationToken] + }; + + this[kPending]++; + // This is our version of a "virtual" no-I/O connection as the spec requires + this.emit( + ConnectionPool.CONNECTION_CREATED, + new ConnectionCreatedEvent(this, { id: connectOptions.id }) + ); + + connect(connectOptions, (err, connection) => { + if (err || !connection) { + this[kPending]--; + this.emit( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, { id: connectOptions.id, serviceId: undefined }, 'error') + ); + if (err instanceof MongoNetworkError || err instanceof MongoServerError) { + err.connectionGeneration = connectOptions.generation; + } + callback(err ?? new MongoRuntimeError('Connection creation failed without error')); + return; + } + + // The pool might have closed since we started trying to create a connection + if (this[kPoolState] !== PoolState.ready) { + this[kPending]--; + connection.destroy({ force: true }); + callback(this.closed ? new PoolClosedError(this) : new PoolClearedError(this)); + 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) => this.emit(event, e)); + } + + if (this.loadBalanced) { + connection.on(Connection.PINNED, pinType => this[kMetrics].markPinned(pinType)); + connection.on(Connection.UNPINNED, pinType => this[kMetrics].markUnpinned(pinType)); + + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = this.serviceGenerations.get(sid))) { + connection.generation = generation; + } else { + this.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + + connection.markAvailable(); + this.emit(ConnectionPool.CONNECTION_READY, new ConnectionReadyEvent(this, connection)); + + this[kPending]--; + callback(undefined, connection); + return; + }); + } + + private ensureMinPoolSize() { + const minPoolSize = this.options.minPoolSize; + if (this[kPoolState] !== PoolState.ready || minPoolSize === 0) { + return; + } + + this[kConnections].prune(connection => this.destroyConnectionIfPerished(connection)); + + if ( + this.totalConnectionCount < minPoolSize && + this.pendingConnectionCount < this.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 + this.createConnection((err, connection) => { + if (err) { + this[kServer].handleError(err); + } + if (!err && connection) { + this[kConnections].push(connection); + process.nextTick(() => this.processWaitQueue()); + } + if (this[kPoolState] === PoolState.ready) { + clearTimeout(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = setTimeout( + () => this.ensureMinPoolSize(), + this.options.minPoolSizeCheckFrequencyMS + ); + } + }); + } else { + clearTimeout(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = setTimeout( + () => this.ensureMinPoolSize(), + this.options.minPoolSizeCheckFrequencyMS + ); + } + } + + private processWaitQueue() { + if (this[kProcessingWaitQueue]) { + return; + } + this[kProcessingWaitQueue] = true; + + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].first(); + if (!waitQueueMember) { + this[kWaitQueue].shift(); + continue; + } + + if (waitQueueMember[kCancelled]) { + this[kWaitQueue].shift(); + continue; + } + + if (this[kPoolState] !== PoolState.ready) { + const reason = this.closed ? 'poolClosed' : 'connectionError'; + const error = this.closed ? new PoolClosedError(this) : new PoolClearedError(this); + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, reason) + ); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + this[kWaitQueue].shift(); + waitQueueMember.callback(error); + continue; + } + + if (!this.availableConnectionCount) { + break; + } + + const connection = this[kConnections].shift(); + if (!connection) { + break; + } + + if (!this.destroyConnectionIfPerished(connection)) { + this[kCheckedOut].add(connection); + this.emit( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(this, connection) + ); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + this[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + } + } + + const { maxPoolSize, maxConnecting } = this.options; + while ( + this.waitQueueSize > 0 && + this.pendingConnectionCount < maxConnecting && + (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize) + ) { + const waitQueueMember = this[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + continue; + } + this.createConnection((err, connection) => { + if (waitQueueMember[kCancelled]) { + if (!err && connection) { + this[kConnections].push(connection); + } + } else { + if (err) { + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, 'connectionError') + ); + } else if (connection) { + this[kCheckedOut].add(connection); + this.emit( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(this, connection) + ); + } + + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + } + process.nextTick(() => this.processWaitQueue()); + }); + } + this[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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection_pool_events.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection_pool_events.ts new file mode 100644 index 00000000..0f56bf6b --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/connection_pool_events.ts @@ -0,0 +1,201 @@ +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 ready + * @public + * @category Event + */ +export class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * 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: Pick, + 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; + + interruptInUseConnections?: boolean; + + /** @internal */ + constructor( + pool: ConnectionPool, + options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {} + ) { + super(pool); + this.serviceId = options.serviceId; + this.interruptInUseConnections = options.interruptInUseConnections; + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/errors.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/errors.ts new file mode 100644 index 00000000..f6d2ed58 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/errors.ts @@ -0,0 +1,75 @@ +import { MongoDriverError, MongoErrorLabel, MongoNetworkError } 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 indicating a connection pool is currently paused + * @category Error + */ +export class PoolClearedError extends MongoNetworkError { + /** The address of the connection pool */ + address: string; + + constructor(pool: ConnectionPool, message?: string) { + const errorMessage = message + ? message + : `Connection pool for ${pool.address} was cleared because another operation failed with: "${pool.serverError?.message}"`; + super(errorMessage); + this.address = pool.address; + + this.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + + override get name(): string { + return 'MongoPoolClearedError'; + } +} + +/** + * An error indicating that a connection pool has been cleared after the monitor for that server timed out. + * @category Error + */ +export class PoolClearedOnNetworkError extends PoolClearedError { + constructor(pool: ConnectionPool) { + super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`); + } + + override get name(): string { + return 'PoolClearedOnNetworkError'; + } +} + +/** + * 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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/message_stream.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/message_stream.ts new file mode 100644 index 00000000..409e9997 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/message_stream.ts @@ -0,0 +1,230 @@ +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, 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; + 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 { + const agreedCompressor = operationDescription.agreedCompressor ?? 'none'; + if (agreedCompressor === '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); + + const options = { + agreedCompressor, + zlibCompressionLevel: operationDescription.zlibCompressionLevel ?? 0 + }; + // Compress the message body + compress(options, messageToBeCompressed).then( + compressedMessage => { + // 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[agreedCompressor], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }, + error => { + operationDescription.cb(error); + } + ); + } +} + +// 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.query; + const commandName = Object.keys(commandDoc)[0]; + return !uncompressibleCommands.has(commandName); +} + +function processIncomingData(stream: MessageStream, callback: Callback): void { + const buffer = stream[kBuffer]; + const sizeOfMessage = buffer.getInt32(); + + if (sizeOfMessage == null) { + return callback(); + } + + if (sizeOfMessage < 0) { + return callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + } + + if (sizeOfMessage > stream.maxBsonMessageSize) { + return callback( + new MongoParseError( + `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` + ) + ); + } + + if (sizeOfMessage > buffer.length) { + return callback(); + } + + 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? + const sizeOfMessage = buffer.getInt32(); + if (sizeOfMessage != null && sizeOfMessage <= buffer.length) { + return true; + } + } + return false; + }; + + let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; + if (messageHeader.opCode !== OP_COMPRESSED) { + const messageBody = message.subarray(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()) { + return processIncomingData(stream, callback); + } + + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + + if (buffer.length >= 4) { + return processIncomingData(stream, callback); + } + return callback(); + } + + 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 === OP_MSG ? BinMsg : Response; + decompress(compressorID, compressedBuffer).then( + messageBody => { + if (messageBody.length !== messageHeader.length) { + return callback( + new MongoDecompressionError('Message body and message header must be the same length') + ); + } + + // 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()) { + return processIncomingData(stream, callback); + } + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + + if (buffer.length >= 4) { + return processIncomingData(stream, callback); + } + return callback(); + }, + error => { + return callback(error); + } + ); +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/metrics.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/metrics.ts new file mode 100644 index 00000000..b825b539 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/stream_description.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/stream_description.ts new file mode 100644 index 00000000..c5fbec0f --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/compression.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/compression.ts new file mode 100644 index 00000000..090c42e9 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/compression.ts @@ -0,0 +1,104 @@ +import { promisify } from 'util'; +import * as zlib from 'zlib'; + +import { LEGACY_HELLO_COMMAND } from '../../constants'; +import { Snappy, ZStandard } from '../../deps'; +import { MongoDecompressionError, MongoInvalidArgumentError } from '../../error'; + +/** @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 ZSTD_COMPRESSION_LEVEL = 3; + +const zlibInflate = promisify(zlib.inflate.bind(zlib)); +const zlibDeflate = promisify(zlib.deflate.bind(zlib)); + +// Facilitate compressing a message using an agreed compressor +export async function compress( + options: { zlibCompressionLevel: number; agreedCompressor: CompressorName }, + dataToBeCompressed: Buffer +): Promise { + const zlibOptions = {} as zlib.ZlibOptions; + switch (options.agreedCompressor) { + case 'snappy': + if ('kModuleError' in Snappy) { + throw Snappy['kModuleError']; + } + return Snappy.compress(dataToBeCompressed); + + case 'zstd': + if ('kModuleError' in ZStandard) { + throw ZStandard['kModuleError']; + } + return ZStandard.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL); + + case 'zlib': + if (options.zlibCompressionLevel) { + zlibOptions.level = options.zlibCompressionLevel; + } + return zlibDeflate(dataToBeCompressed, zlibOptions); + + default: + throw new MongoInvalidArgumentError( + `Unknown compressor ${options.agreedCompressor} failed to compress` + ); + } +} + +// Decompress a message using the given compressor +export async function decompress(compressorID: number, compressedData: Buffer): Promise { + if ( + compressorID !== Compressor.snappy && + compressorID !== Compressor.zstd && + compressorID !== Compressor.zlib && + compressorID !== Compressor.none + ) { + throw new MongoDecompressionError( + `Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})` + ); + } + + switch (compressorID) { + case Compressor.snappy: + if ('kModuleError' in Snappy) { + throw Snappy['kModuleError']; + } + return Snappy.uncompress(compressedData, { asBuffer: true }); + + case Compressor.zstd: + if ('kModuleError' in ZStandard) { + throw ZStandard['kModuleError']; + } + return ZStandard.decompress(compressedData); + + case Compressor.zlib: + return zlibInflate(compressedData); + + default: + return compressedData; + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/constants.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/constants.ts new file mode 100644 index 00000000..75c26d7f --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/constants.ts @@ -0,0 +1,11 @@ +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_DELETE = 2006; +export const OP_COMPRESSED = 2012; +export const OP_MSG = 2013; diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/shared.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cmap/wire_protocol/shared.ts new file mode 100644 index 00000000..bc13ff6d --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/collection.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/collection.ts new file mode 100644 index 00000000..38437c26 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/collection.ts @@ -0,0 +1,983 @@ +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 { 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 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 { + checkCollectionName, + DEFAULT_PK_FACTORY, + MongoDBNamespace, + normalizeHintField, + resolveOptions +} from './utils'; +import { WriteConcern, WriteConcernOptions } from './write_concern'; + +/** + * @public + * @deprecated This type will be completely removed and findOneAndUpdate, + * findOneAndDelete, and findOneAndReplace will then return the + * actual result document. + */ +export interface ModifyResult { + value: WithId | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions { + /** 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/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +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 + */ + async insertOne( + doc: OptionalUnlessRequiredId, + options?: InsertOneOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new InsertOneOperation( + this as TODO_NODE_3286, + doc, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async insertMany( + docs: OptionalUnlessRequiredId[], + options?: BulkWriteOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new InsertManyOperation( + this as TODO_NODE_3286, + docs, + resolveOptions(this, options ?? { ordered: true }) + ) as TODO_NODE_3286 + ); + } + + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * 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 + * @throws MongoDriverError if operations is not an array + */ + async bulkWrite( + operations: AnyBulkWriteOperation[], + options?: BulkWriteOptions + ): Promise { + 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 ?? { ordered: true }) + ) + ); + } + + /** + * 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 + */ + async updateOne( + filter: Filter, + update: UpdateFilter | Partial, + options?: UpdateOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new UpdateOneOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async replaceOne( + filter: Filter, + replacement: WithoutId, + options?: ReplaceOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new ReplaceOneOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ) + ); + } + + /** + * 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 + */ + async updateMany( + filter: Filter, + update: UpdateFilter, + options?: UpdateOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new UpdateManyOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + async deleteOne( + filter: Filter = {}, + options: DeleteOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new DeleteOneOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + async deleteMany( + filter: Filter = {}, + options: DeleteOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new DeleteManyOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async rename(newName: string, options?: RenameOptions): Promise { + // 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 + }) as TODO_NODE_3286 + ); + } + + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + async drop(options?: DropCollectionOptions): Promise { + return executeOperation( + this.s.db.s.client, + new DropCollectionOperation(this.s.db, this.collectionName, options) + ); + } + + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + */ + async findOne(): Promise | null>; + async findOne(filter: Filter): Promise | null>; + async findOne(filter: Filter, options: FindOptions): Promise | null>; + + // allow an override of the schema. + async findOne(): Promise; + async findOne(filter: Filter): Promise; + async findOne(filter: Filter, options?: FindOptions): Promise; + + async findOne( + filter: Filter = {}, + options: FindOptions = {} + ): Promise | null> { + return this.find(filter, options).limit(-1).batchSize(1).next(); + } + + /** + * 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> { + 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 + */ + async options(options?: OperationOptions): Promise { + return executeOperation( + this.s.db.s.client, + new OptionsOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + async isCapped(options?: OperationOptions): Promise { + return executeOperation( + this.s.db.s.client, + new IsCappedOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * 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 + * + * @example + * ```ts + * 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' }]) + * ``` + */ + async createIndex( + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new CreateIndexOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpec, + resolveOptions(this, options) + ) + ); + } + + /** + * 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 + * + * @example + * ```ts + * 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' + * } + * ]); + * ``` + */ + async createIndexes( + indexSpecs: IndexDescription[], + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new CreateIndexesOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpecs, + resolveOptions(this, { ...options, maxTimeMS: undefined }) + ) + ); + } + + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + async dropIndex(indexName: string, options?: DropIndexesOptions): Promise { + return executeOperation( + this.s.db.s.client, + new DropIndexOperation(this as TODO_NODE_3286, indexName, { + ...resolveOptions(this, options), + readPreference: ReadPreference.primary + }) + ); + } + + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + async dropIndexes(options?: DropIndexesOptions): Promise { + return executeOperation( + this.s.db.s.client, + new DropIndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async indexExists( + indexes: string | string[], + options?: IndexInformationOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new IndexExistsOperation(this as TODO_NODE_3286, indexes, resolveOptions(this, options)) + ); + } + + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + async indexInformation(options?: IndexInformationOptions): Promise { + return executeOperation( + this.s.db.s.client, + new IndexInformationOperation(this.s.db, this.collectionName, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise { + return executeOperation( + this.s.db.s.client, + new EstimatedDocumentCountOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * 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 + * + * @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 + */ + async countDocuments( + filter: Document = {}, + options: CountDocumentsOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new CountDocumentsOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + distinct>( + key: Key + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter, + options: DistinctOptions + ): Promise[Key]>>>; + + // Embedded documents overload + distinct(key: string): Promise; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + + async distinct>( + key: Key, + filter: Filter = {}, + options: DistinctOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new DistinctOperation( + this as TODO_NODE_3286, + key as TODO_NODE_3286, + filter, + resolveOptions(this, options) + ) + ); + } + + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + async indexes(options?: IndexInformationOptions): Promise { + return executeOperation( + this.s.db.s.client, + new IndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + */ + async stats(options?: CollStatsOptions): Promise { + return executeOperation( + this.s.db.s.client, + new CollStatsOperation(this as TODO_NODE_3286, options) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async findOneAndDelete( + filter: Filter, + options?: FindOneAndDeleteOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new FindOneAndDeleteOperation( + this as TODO_NODE_3286, + filter, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options?: FindOneAndReplaceOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new FindOneAndReplaceOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options?: FindOneAndUpdateOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new FindOneAndUpdateOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 (!Array.isArray(pipeline)) { + throw new MongoInvalidArgumentError( + 'Argument "pipeline" must be an array of aggregation stages' + ); + } + + 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 use cases: + * - 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)); + } + + /** + * 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 implementation. + * 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 implementation. + * 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)); + } + + /** + * 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 + */ + async count(filter: Filter = {}, options: CountOptions = {}): Promise { + return executeOperation( + this.s.db.s.client, + new CountOperation( + MongoDBNamespace.fromString(this.namespace), + filter, + resolveOptions(this, options) + ) + ); + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/connection_string.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/connection_string.ts new file mode 100644 index 00000000..b282afc4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/connection_string.ts @@ -0,0 +1,1301 @@ +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, + MongoMissingCredentialsError, + MongoParseError +} from './error'; +import { + DriverInfo, + MongoClient, + MongoClientOptions, + MongoOptions, + PkFactory, + ServerApi, + ServerApiVersion +} from './mongo_client'; +import { MongoLogger, MongoLoggerEnvOptions, MongoLoggerMongoClientOptions } from './mongo_logger'; +import { ReadConcern, ReadConcernLevel } from './read_concern'; +import { ReadPreference, ReadPreferenceMode } from './read_preference'; +import type { TagSet } from './sdam/server_description'; +import { + DEFAULT_PK_FACTORY, + emitWarning, + emitWarningOnce, + HostAddress, + isRecord, + makeClientMetadata, + parseInteger, + 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 async function resolveSRVRecord(options: MongoOptions): Promise { + if (typeof options.srvHost !== 'string') { + throw new MongoAPIError('Option "srvHost" must not be empty'); + } + + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + throw 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; + const addresses = await dns.promises.resolveSrv( + `_${options.srvServiceName}._tcp.${lookupAddress}` + ); + + if (addresses.length === 0) { + throw new MongoAPIError('No addresses found at host'); + } + + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + throw new MongoAPIError('Server record does not share hostname with parent URI'); + } + } + + const hostAddresses = addresses.map(r => HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)); + + validateLoadBalancedOptions(hostAddresses, options, true); + + // Resolve TXT record and add options from there if they exist. + let record; + try { + record = await dns.promises.resolveTxt(lookupAddress); + } catch (error) { + if (error.code !== 'ENODATA' && error.code !== 'ENOTFOUND') { + throw error; + } + return hostAddresses; + } + + if (record.length > 1) { + throw 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))) { + throw new MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`); + } + + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + throw 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) { + throw new MongoParseError('Cannot combine replicaSet option with srvMaxHosts'); + } + + validateLoadBalancedOptions(hostAddresses, options, true); + + return hostAddresses; +} + +/** + * Checks if TLS options are valid + * + * @param allOptions - All options provided by user or included in default options map + * @throws MongoAPIError if TLS options are invalid + */ +function checkTLSOptions(allOptions: CaseInsensitiveMap): void { + if (!allOptions) return; + const check = (a: string, b: string) => { + if (allOptions.has(a) && allOptions.has(b)) { + throw new MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`); + } + }; + 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 getIntFromOptions(name: string, value: unknown): number { + const parsedInt = parseInteger(value); + if (parsedInt != null) { + return parsedInt; + } + throw new MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} + +function getUIntFromOptions(name: string, value: unknown): number { + const parsedValue = getIntFromOptions(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; + } + + // validate BSONOptions + if (options.useBigInt64 && typeof options.promoteLongs === 'boolean' && !options.promoteLongs) { + throw new MongoAPIError('Must request either bigint or Long for int64 deserialization'); + } + + if (options.useBigInt64 && typeof options.promoteValues === 'boolean' && !options.promoteValues) { + throw new MongoAPIError('Must request either bigint or Long for int64 deserialization'); + } + + 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.'); + } + } + + checkTLSOptions(allOptions); + + 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; + const isOidc = mongoOptions.credentials.mechanism === AuthMechanism.MONGODB_OIDC; + 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 || isOidc) && + 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 + }); + } + + if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) { + throw new MongoMissingCredentialsError( + `When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified` + ); + } + + 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'; + } + + validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + + 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' + ); + } + + const loggerFeatureFlag = Symbol.for('@@mdb.enableMongoLogger'); + mongoOptions[loggerFeatureFlag] = mongoOptions[loggerFeatureFlag] ?? false; + + let loggerEnvOptions: MongoLoggerEnvOptions = {}; + let loggerClientOptions: MongoLoggerMongoClientOptions = {}; + if (mongoOptions[loggerFeatureFlag]) { + loggerEnvOptions = { + MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND, + MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY, + MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION, + MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION, + MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL, + MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH, + MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH + }; + loggerClientOptions = { + mongodbLogPath: mongoOptions.mongodbLogPath + }; + } + mongoOptions.mongoLoggerOptions = MongoLogger.resolveOptions( + loggerEnvOptions, + loggerClientOptions + ); + + return mongoOptions; +} + +/** + * #### Throws if LB mode is true: + * - hosts contains more than one host + * - there is a replicaSet name set + * - directConnection is set + * - if srvMaxHosts is used when an srv connection string is passed in + * + * @throws MongoParseError + */ +function validateLoadBalancedOptions( + hosts: HostAddress[] | string[], + mongoOptions: MongoOptions, + isSrv: boolean +): void { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + throw new MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + throw new MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + throw new MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + + if (isSrv && mongoOptions.srvMaxHosts > 0) { + throw 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] = getIntFromOptions(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUIntFromOptions(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 }): MongoCredentials { + // We can have a combination of options passed in the URI and options passed + // as an object to the MongoClient. So we must transform the string options + // as well as merge them together with a potentially provided object. + let mechanismProperties = Object.create(null); + + for (const optionValue of values) { + if (typeof optionValue === 'string') { + for (const [key, value] of entriesFromString(optionValue)) { + try { + mechanismProperties[key] = getBoolean(key, value); + } catch { + mechanismProperties[key] = value; + } + } + } else { + if (!isRecord(optionValue)) { + throw new MongoParseError('AuthMechanismProperties must be an object'); + } + mechanismProperties = { ...optionValue }; + } + } + return MongoCredentials.merge(options.credentials, { + mechanismProperties + }); + } + }, + 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 = getIntFromOptions(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' + }, + maxConnecting: { + default: 2, + transform({ name, values: [value] }): number { + const maxConnecting = getUIntFromOptions(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 = getUIntFromOptions(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}` + ); + } + }, + promoteBuffers: { + type: 'boolean' + }, + promoteLongs: { + type: 'boolean' + }, + promoteValues: { + type: 'boolean' + }, + useBigInt64: { + 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)}`); + } + }, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUIntFromOptions('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: getUIntFromOptions('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'), + Symbol.for('@@mdb.enableMongoLogger') +]); diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/constants.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/constants.ts new file mode 100644 index 00000000..eec4b075 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/constants.ts @@ -0,0 +1,136 @@ +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_POOL_READY = 'connectionPoolReady' 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_READY, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_CREATED, + CONNECTION_READY, + CONNECTION_CLOSED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECKED_OUT, + CONNECTION_CHECKED_IN +] 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/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/abstract_cursor.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/abstract_cursor.ts new file mode 100644 index 00000000..a115d971 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/abstract_cursor.ts @@ -0,0 +1,927 @@ +import { Readable, Transform } from 'stream'; +import { promisify } from 'util'; + +import { BSONSerializeOptions, Document, Long, pluckBSONSerializeOptions } from '../bson'; +import { + AnyError, + MongoAPIError, + 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, List, 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 */ +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; + /** + * Specifies the number of documents to return in each response from MongoDB + */ + batchSize?: number; + /** + * When applicable `maxTimeMS` controls the amount of time the initial command + * that constructs a cursor should take. (ex. find, aggregate, listCollections) + */ + maxTimeMS?: number; + /** + * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores + * that a cursor uses to fetch more data should take. (ex. cursor.next()) + */ + 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; + /** + * By default, MongoDB will automatically close a cursor when the + * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections) + * you may use a Tailable Cursor that remains open after the client exhausts + * the results in the initial cursor. + */ + tailable?: boolean; + /** + * If awaitData is set to true, when the cursor reaches the end of the capped collection, + * MongoDB blocks the query thread for a period of time waiting for new data to arrive. + * When new data is inserted into the capped collection, the blocked thread is signaled + * to wake up and return the next batch to the client. + */ + 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 | null; + /** @internal */ + [kSession]: ClientSession; + /** @internal */ + [kServer]?: Server; + /** @internal */ + [kNamespace]: MongoDBNamespace; + /** @internal */ + [kDocuments]: List; + /** @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[kId] = null; + this[kDocuments] = new List(); + 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 (typeof options.maxAwaitTimeMS === 'number') { + this[kOptions].maxAwaitTimeMS = options.maxAwaitTimeMS; + } + + 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] ?? undefined; + } + + /** @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[] { + const bufferedDocs: TSchema[] = []; + const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length); + + for (let count = 0; count < documentsToRead; count++) { + const document = this[kDocuments].shift(); + if (document != null) { + bufferedDocs.push(document); + } + } + + return bufferedDocs; + } + + async *[Symbol.asyncIterator](): AsyncGenerator { + if (this.closed) { + return; + } + + try { + while (true) { + const document = await this.next(); + + // Intentional strict null check, because users can map cursors to falsey values. + // We allow mapping to all values except for null. + // eslint-disable-next-line no-restricted-syntax + if (document === null) { + if (!this.closed) { + const message = + 'Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.'; + + await cleanupCursorAsync(this, { needsToEmitClosed: true }).catch(() => null); + + throw new MongoAPIError(message); + } + break; + } + + yield document; + + if (this[kId] === Long.ZERO) { + // Cursor exhausted + break; + } + } + } finally { + // Only close the cursor if it has not already been closed. This finally clause handles + // the case when a user would break out of a for await of loop early. + if (!this.closed) { + await this.close().catch(() => null); + } + } + } + + 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); + } + + async hasNext(): Promise { + if (this[kId] === Long.ZERO) { + return false; + } + + if (this[kDocuments].length !== 0) { + return true; + } + + const doc = await nextAsync(this, true); + + if (doc) { + this[kDocuments].unshift(doc); + return true; + } + + return false; + } + + /** Get the next available document from the cursor, returns null if no more documents are available. */ + async next(): Promise { + if (this[kId] === Long.ZERO) { + throw new MongoCursorExhaustedError(); + } + + return nextAsync(this, true); + } + + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + async tryNext(): Promise { + if (this[kId] === Long.ZERO) { + throw new MongoCursorExhaustedError(); + } + + return nextAsync(this, false); + } + + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + */ + async forEach(iterator: (doc: TSchema) => boolean | void): Promise { + if (typeof iterator !== 'function') { + throw new MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + for await (const document of this) { + const result = iterator(document); + if (result === false) { + break; + } + } + } + + async close(): Promise { + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + await cleanupCursorAsync(this, { needsToEmitClosed }); + } + + /** + * 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. + */ + async toArray(): Promise { + const array = []; + for await (const document of this) { + array.push(document); + } + return array; + } + + /** + * 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** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **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] = null; + this[kDocuments].clear(); + 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 { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const getMoreOperation = new GetMoreOperation(this[kNamespace], this[kId]!, this[kServer]!, { + ...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], (error, state) => { + if (state) { + const response = state.response; + this[kServer] = state.server; + + if (response.cursor) { + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this[kId] = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : typeof response.cursor.id === 'bigint' + ? Long.fromBigInt(response.cursor.id) + : response.cursor.id; + + if (response.cursor.ns) { + this[kNamespace] = ns(response.cursor.ns); + } + + this[kDocuments].pushMany(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].push(state.response as TODO_NODE_3286); + } + } + + // the cursor is now initialized, even if an error occurred or it is dead + this[kInitialized] = true; + + if (error) { + return cleanupCursor(this, { error }, () => callback(error, undefined)); + } + + if (cursorIsDead(this)) { + return cleanupCursor(this, undefined, () => callback()); + } + + callback(); + }); + } +} + +function nextDocument(cursor: AbstractCursor): T | null { + const doc = cursor[kDocuments].shift(); + + if (doc && cursor[kTransform]) { + return cursor[kTransform](doc) as T; + } + + return doc; +} + +const nextAsync = promisify( + next as ( + cursor: AbstractCursor, + blocking: boolean, + callback: (e: Error, r: T | null) => void + ) => void +); + +/** + * @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].length !== 0) { + 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 => { + if (err) return callback(err); + 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, (error, response) => { + if (response) { + const cursorId = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : typeof response.cursor.id === 'bigint' + ? Long.fromBigInt(response.cursor.id) + : response.cursor.id; + + cursor[kDocuments].pushMany(response.cursor.nextBatch); + cursor[kId] = cursorId; + } + + if (error || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error }, () => callback(error, 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(); +} + +const cleanupCursorAsync = promisify(cleanupCursor); + +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) { + session.endSession({ error }).finally(() => { + callback(); + }); + return; + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + return callback(); + } + + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + session.endSession({ error }).finally(() => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + return; + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + + cursor[kKilled] = true; + + if (session.hasEnded) { + return completeCleanup(); + } + + executeOperation( + cursor[kClient], + new KillCursorsOperation(cursorId, cursorNs, server, { session }) + ) + .catch(() => null) + .finally(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().then( + () => callback(error), + closeError => callback(closeError) + ); + } + + 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 was 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(/operation was interrupted/)) { + return this.push(null); + } + + // NOTE: The two above checks on the message of the error will cause a null to be pushed + // to the stream, thus closing the stream before the destroy call happens. This means + // that either of those error messages on a change stream will not get a proper + // 'error' event to be emitted (the error passed to destroy). Change stream resumability + // relies on that error event to be emitted to create its new cursor and thus was not + // working on 4.4 servers because the error emitted on failover was "interrupted at + // shutdown" while on 5.0+ it is "The server is in quiesce mode and will shut down". + // See NODE-4475. + 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/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/aggregation_cursor.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/aggregation_cursor.ts new file mode 100644 index 00000000..f57969d3 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/aggregation_cursor.ts @@ -0,0 +1,208 @@ +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 */ + async explain(verbosity?: ExplainVerbosityLike): Promise { + 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 ?? true + }) + ); + } + + /** 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; + } + + /** Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/change_stream_cursor.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/change_stream_cursor.ts new file mode 100644 index 00000000..b5a4ae46 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/find_cursor.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/find_cursor.ts new file mode 100644 index 00000000..ff4cd6dd --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/find_cursor.ts @@ -0,0 +1,456 @@ +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 = {}, + 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) { + this.close().finally(() => callback()); + return; + } + } + + 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 + */ + async count(options?: CountOptions): Promise { + 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'); + } + 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 + }) + ); + } + + /** Execute the explain for the cursor */ + async explain(verbosity?: ExplainVerbosityLike): Promise { + 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 ?? true + }) + ); + } + + /** 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 behavior. + 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/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/list_collections_cursor.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/list_collections_cursor.ts new file mode 100644 index 00000000..460126be --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/list_indexes_cursor.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/cursor/list_indexes_cursor.ts new file mode 100644 index 00000000..25336d84 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/db.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/db.ts new file mode 100644 index 00000000..4381caa7 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/db.ts @@ -0,0 +1,524 @@ +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 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 { DEFAULT_PK_FACTORY, filterOptions, 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', + 'useBigInt64', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'enableUtf8Validation', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** @internal */ +export interface DbPrivate { + client: MongoClient; + options?: DbOptions; + readPreference?: ReadPreference; + pkFactory: PkFactory; + readConcern?: ReadConcern; + bsonOptions: BSONSerializeOptions; + writeConcern?: WriteConcern; + namespace: MongoDBNamespace; +} + +/** @public */ +export interface DbOptions extends BSONSerializeOptions, WriteConcernOptions { + /** 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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +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, + // 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; + } + + /** + * 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 + */ + async createCollection( + name: string, + options?: CreateCollectionOptions + ): Promise> { + return executeOperation( + this.s.client, + new CreateCollectionOperation(this, name, resolveOptions(this, options)) 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 + */ + async command(command: Document, options?: RunCommandOptions): Promise { + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation(this.s.client, new RunCommandOperation(this, command, options)); + } + + /** + * 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 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.'); + } + return new Collection(this, name, resolveOptions(this, options)); + } + + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + */ + async stats(options?: DbStatsOptions): Promise { + return executeOperation( + this.s.client, + new DbStatsOperation(this, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async renameCollection( + fromCollection: string, + toCollection: string, + options?: RenameOptions + ): Promise> { + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + this.s.client, + new RenameOperation( + this.collection(fromCollection) as TODO_NODE_3286, + toCollection, + { ...options, new_collection: true, readPreference: ReadPreference.primary } + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async dropCollection(name: string, options?: DropCollectionOptions): Promise { + return executeOperation( + this.s.client, + new DropCollectionOperation(this, name, resolveOptions(this, options)) + ); + } + + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + async dropDatabase(options?: DropDatabaseOptions): Promise { + return executeOperation( + this.s.client, + new DropDatabaseOperation(this, resolveOptions(this, options)) + ); + } + + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + async collections(options?: ListCollectionsOptions): Promise { + return executeOperation( + this.s.client, + new CollectionsOperation(this, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async createIndex( + name: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.s.client, + new CreateIndexOperation(this, name, indexSpec, resolveOptions(this, options)) + ); + } + + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + async addUser( + username: string, + passwordOrOptions?: string | AddUserOptions, + options?: AddUserOptions + ): Promise { + options = + options != null && typeof options === 'object' + ? options + : passwordOrOptions != null && typeof passwordOrOptions === 'object' + ? passwordOrOptions + : undefined; + const password = typeof passwordOrOptions === 'string' ? passwordOrOptions : undefined; + return executeOperation( + this.s.client, + new AddUserOperation(this, username, password, resolveOptions(this, options)) + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username: string, options?: RemoveUserOptions): Promise { + return executeOperation( + this.s.client, + new RemoveUserOperation(this, username, resolveOptions(this, options)) + ); + } + + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + async setProfilingLevel( + level: ProfilingLevel, + options?: SetProfilingLevelOptions + ): Promise { + return executeOperation( + this.s.client, + new SetProfilingLevelOperation(this, level, resolveOptions(this, options)) + ); + } + + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + async profilingLevel(options?: ProfilingLevelOptions): Promise { + return executeOperation( + this.s.client, + new ProfilingLevelOperation(this, resolveOptions(this, options)) + ); + } + + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + async indexInformation(name: string, options?: IndexInformationOptions): Promise { + return executeOperation( + this.s.client, + new IndexInformationOperation(this, name, resolveOptions(this, options)) + ); + } + + /** + * 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 use cases: + * - 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)); + } +} + +// 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/1_ActivityWatchProducer/node_modules/mongodb/src/deps.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/deps.ts new file mode 100644 index 00000000..e3e931e5 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/deps.ts @@ -0,0 +1,394 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +import type { Document } from './bson'; +import type { AWSCredentials } from './cmap/auth/mongodb_aws'; +import type { ProxyOptions } from './cmap/connection'; +import { MongoMissingDependencyError } from './error'; +import type { MongoClient } from './mongo_client'; +import type { Callback } from './utils'; + +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 CredentialProvider = { + fromNodeProviderChain(this: void): () => Promise; +}; + +export function getAwsCredentialProvider(): + | CredentialProvider + | { kModuleError: MongoMissingDependencyError } { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const credentialProvider = require('@aws-sdk/credential-providers'); + return credentialProvider; + } catch { + return makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `@aws-sdk/credential-providers` not found.' + + ' Please install it to enable getting aws credentials via the official sdk.' + ) + ); + } +} + +type SnappyLib = { + /** + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + */ + compress(buf: Buffer): Promise; + + /** + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + */ + uncompress(buf: Buffer, opt: { asBuffer: true }): Promise; +}; + +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'); +} 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 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; + } + | Record; + /** 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; + } + | { + /** + * If present, an access token to authenticate with Azure. + */ + accessToken: string; + }; + /** 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; + } + | { + /** + * If present, an access token to authenticate with GCP. + */ + accessToken: string; + } + | Record; + /** + * 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 Field Level 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/1_ActivityWatchProducer/node_modules/mongodb/src/encrypter.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/encrypter.ts new file mode 100644 index 00000000..d24e0de2 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/encrypter.ts @@ -0,0 +1,131 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ + +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: { new (...args: ConstructorParameters): 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 + }; + } + + 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; + } + + async connectInternalClient(): Promise { + // TODO(NODE-4144): Remove new variable for type narrowing + const internalClient = this[kInternalClient]; + if (this.needsConnecting && internalClient != null) { + this.needsConnecting = false; + await internalClient.connect(); + } + } + + close(client: MongoClient, force: boolean, callback: Callback): void { + this.autoEncrypter.teardown(!!force, e => { + const internalClient = this[kInternalClient]; + if (internalClient != null && client !== internalClient) { + internalClient.close(force).then( + () => callback(), + error => callback(error) + ); + return; + } + callback(e); + }); + } + + static checkForMongoCrypt(): void { + const mongodbClientEncryption = getMongoDBClientEncryption(); + if (mongodbClientEncryption == null) { + throw new MongoMissingDependencyError( + 'Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project' + ); + } + AutoEncrypterClass = mongodbClientEncryption.extension(require('../lib/index')).AutoEncrypter; + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/error.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/error.ts new file mode 100644 index 00000000..1dd426cb --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/error.ts @@ -0,0 +1,932 @@ +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', + ResetPool: 'ResetPool', + InterruptInUseConnections: 'InterruptInUseConnections', + NoWritesPerformed: 'NoWritesPerformed' +} 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 + * mongodb-client-encryption 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; + connectionGeneration?: number; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + cause?: Error; // depending on the node version, this may or may not exist on the base + + constructor(message: string | Error) { + if (message instanceof Error) { + super(message.message); + this.cause = 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 + * mongodb-client-encryption 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/1_ActivityWatchProducer/node_modules/mongodb/src/explain.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/explain.ts new file mode 100644 index 00000000..0d08e694 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/download.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/download.ts new file mode 100644 index 00000000..0053ecc9 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/download.ts @@ -0,0 +1,474 @@ +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-indexed non-negative byte offset from the beginning of the file + */ + start?: number; + /** + * 0-indexed non-negative byte offset to the end of the file contents + * to be returned by the stream. `end` is non-inclusive + */ + 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; + + /** + * @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 + * @internal + */ + 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. + */ + async abort(): Promise { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + try { + await this.s.cursor.close(); + } finally { + this.emit(GridFSBucketReadStream.CLOSE); + } + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); + } + } + } +} + +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; + + const handleReadResult = ({ + error, + doc + }: { error: Error; doc: null } | { error: null; doc: any }) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + + stream.s.cursor?.close().then( + () => { + stream.emit(GridFSBucketReadStream.CLOSE); + }, + error => { + stream.emit(GridFSBucketReadStream.ERROR, error); + } + ); + 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; + }; + + stream.s.cursor.next().then( + doc => handleReadResult({ error: null, doc }), + error => handleReadResult({ error, doc: null }) + ); +} + +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; + } + + const handleReadResult = ({ + error, + doc + }: { error: Error; doc: null } | { error: null; doc: any }) => { + 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; + }; + + stream.s.files.findOne(stream.s.filter, findOneOptions).then( + doc => handleReadResult({ error: null, doc }), + error => handleReadResult({ error, doc: null }) + ); +} + +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/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/index.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/index.ts new file mode 100644 index 00000000..8471859a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/index.ts @@ -0,0 +1,209 @@ +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 { Filter, TypedEventEmitter } from '../mongo_types'; +import type { ReadPreference } from '../read_preference'; +import type { Sort } from '../sort'; +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 + */ + async delete(id: ObjectId): Promise { + const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id }); + + // Delete orphaned chunks before returning FileNotFound + await this.s._chunksCollection.deleteMany({ files_id: id }); + + if (deletedCount === 0) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + throw new MongoRuntimeError(`File not found for id ${id}`); + } + } + + /** Convenience wrapper around find on the files collection */ + find(filter: Filter = {}, options: FindOptions = {}): FindCursor { + 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 + */ + async rename(id: ObjectId, filename: string): Promise { + const filter = { _id: id }; + const update = { $set: { filename } }; + const { matchedCount } = await this.s._filesCollection.updateOne(filter, update); + if (matchedCount === 0) { + throw new MongoRuntimeError(`File with id ${id} not found`); + } + } + + /** Removes this bucket's files collection, followed by its chunks collection. */ + async drop(): Promise { + await this.s._filesCollection.drop(); + await this.s._chunksCollection.drop(); + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/upload.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/upload.ts new file mode 100644 index 00000000..a5dabc56 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/gridfs/upload.ts @@ -0,0 +1,523 @@ +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 type { Callback } 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'; + + /** + * @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. + * @internal + */ + 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).then( + () => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }, + () => null + ); + } + } + + /** + * 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)); + } + + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + */ + async abort(): Promise { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new MongoAPIError('Cannot abort a stream that has already completed'); + } + + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new MongoAPIError('Cannot call abort() on a stream twice'); + } + + this.state.aborted = true; + await this.chunks.deleteMany({ files_id: this.id }); + } + + /** + * 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 + }; +} + +async function checkChunksIndex(stream: GridFSBucketWriteStream): Promise { + const index = { files_id: 1, n: 1 }; + + let indexes; + try { + indexes = await stream.chunks.listIndexes().toArray(); + } catch (error) { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } else { + throw error; + } + } + + const hasChunksIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + return true; + } + return false; + }); + + if (!hasChunksIndex) { + const writeConcernOptions = getWriteOptions(stream); + await stream.chunks.createIndex(index, { + ...writeConcernOptions, + background: true, + unique: true + }); + } +} + +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)).then( + () => { + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }, + error => { + return __handleError(stream, error, callback); + } + ); + + return true; + } + + return false; +} + +async function checkIndexes(stream: GridFSBucketWriteStream): Promise { + const doc = await stream.files.findOne({}, { projection: { _id: 1 } }); + if (doc != null) { + // If at least one document exists assume the collection has the required index + return; + } + + const index = { filename: 1, uploadDate: 1 }; + + let indexes; + try { + indexes = await stream.files.listIndexes().toArray(); + } catch (error) { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } else { + throw error; + } + } + + const hasFileIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + return true; + } + return false; + }); + + if (!hasFileIndex) { + await stream.files.createIndex(index, { background: false }); + } + + await checkChunksIndex(stream); +} + +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)).then( + () => { + --stream.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }, + error => { + return __handleError(stream, error); + } + ); + + 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)).then( + () => { + --stream.state.outstandingRequests; + checkDone(stream); + }, + error => { + return __handleError(stream, error); + } + ); + 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/1_ActivityWatchProducer/node_modules/mongodb/src/index.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/index.ts new file mode 100644 index 00000000..22ab7f4b --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/index.ts @@ -0,0 +1,472 @@ +import { Admin } from './admin'; +import { OrderedBulkOperation } from './bulk/ordered'; +import { UnorderedBulkOperation } from './bulk/unordered'; +import { ChangeStream } from './change_stream'; +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 { GridFSBucketReadStream } from './gridfs/download'; +import { GridFSBucketWriteStream } from './gridfs/upload'; +import { MongoClient } from './mongo_client'; +import { CancellationToken } from './mongo_types'; +import { ClientSession } from './sessions'; + +/** @public */ +export { BSON } from './bson'; +export { + Binary, + BSONRegExp, + BSONSymbol, + BSONType, + Code, + DBRef, + Decimal128, + Double, + Int32, + Long, + MaxKey, + MinKey, + ObjectId, + Timestamp +} from './bson'; +export { AnyBulkWriteOperation, BulkWriteOptions, MongoBulkWriteError } from './bulk/common'; +export { ChangeStreamCursor } from './cursor/change_stream_cursor'; +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, + ChangeStream, + ClientSession, + Collection, + Db, + FindCursor, + GridFSBucket, + GridFSBucketReadStream, + GridFSBucketWriteStream, + ListCollectionsCursor, + ListIndexesCursor, + MongoClient, + OrderedBulkOperation, + UnorderedBulkOperation +}; + +// 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 { ServerApiVersion } from './mongo_client'; +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, + ConnectionPoolReadyEvent, + 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 { + ChangeStreamCollModDocument, + ChangeStreamCreateDocument, + ChangeStreamCreateIndexDocument, + ChangeStreamDeleteDocument, + ChangeStreamDocument, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentOperationDescription, + ChangeStreamDropDatabaseDocument, + ChangeStreamDropDocument, + ChangeStreamDropIndexDocument, + ChangeStreamEvents, + ChangeStreamInsertDocument, + ChangeStreamInvalidateDocument, + ChangeStreamNameSpace, + ChangeStreamOptions, + ChangeStreamRefineCollectionShardKeyDocument, + ChangeStreamRenameDocument, + ChangeStreamReplaceDocument, + ChangeStreamReshardCollectionDocument, + ChangeStreamShardCollectionDocument, + ChangeStreamUpdateDocument, + OperationTime, + ResumeOptions, + ResumeToken, + UpdateDescription +} from './change_stream'; +export type { + AuthMechanismProperties, + MongoCredentials, + MongoCredentialsOptions +} from './cmap/auth/mongo_credentials'; +export type { + OIDCMechanismServerStep1, + OIDCRefreshFunction, + OIDCRequestFunction, + OIDCRequestTokenResult +} from './cmap/auth/mongodb_oidc'; +export type { + BinMsg, + MessageHeader, + Msg, + 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, + ProxyOptions +} from './cmap/connection'; +export type { + CloseOptions, + ConnectionPool, + ConnectionPoolEvents, + ConnectionPoolOptions, + PoolState, + 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, + 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 { + GridFSBucketReadStreamOptions, + GridFSBucketReadStreamOptionsWithRevision, + GridFSBucketReadStreamPrivate, + GridFSFile +} from './gridfs/download'; +export type { GridFSBucketEvents, GridFSBucketOptions, GridFSBucketPrivate } from './gridfs/index'; +export type { GridFSBucketWriteStreamOptions, GridFSChunk } from './gridfs/upload'; +export type { + Auth, + DriverInfo, + MongoClientEvents, + MongoClientOptions, + MongoClientPrivate, + MongoOptions, + PkFactory, + ServerApi, + SupportedNodeConnectionOptions, + SupportedSocketOptions, + SupportedTLSConnectionOptions, + SupportedTLSSocketOptions, + WithSessionCallback +} from './mongo_client'; +export type { + MongoLoggableComponent, + MongoLogger, + MongoLoggerEnvOptions, + MongoLoggerMongoClientOptions, + MongoLoggerOptions, + SeverityLevel +} from './mongo_logger'; +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, + PropertyType, + PullAllOperator, + PullOperator, + PushOperator, + RegExpOrString, + RootFilterOperators, + SchemaMember, + SetFields, + StrictFilter, + StrictMatchKeysAndValues, + StrictUpdateFilter, + 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 { 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, + MonitorInterval, + MonitorIntervalOptions, + 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 { + 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, + List, + MongoDBNamespace +} from './utils'; +export type { W, WriteConcernOptions, WriteConcernSettings } from './write_concern'; diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_client.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_client.ts new file mode 100644 index 00000000..391ab395 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_client.ts @@ -0,0 +1,729 @@ +import type { TcpNetConnectOpts } from 'net'; +import type { ConnectionOptions as TLSConnectionOptions, TLSSocketOptions } from 'tls'; +import { promisify } from 'util'; + +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, resolveSRVRecord } from './connection_string'; +import { 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 { MongoLogger, MongoLoggerOptions } from './mongo_logger'; +import { TypedEventEmitter } from './mongo_types'; +import type { ReadConcern, ReadConcernLevel, ReadConcernLike } from './read_concern'; +import { ReadPreference, ReadPreferenceMode } from './read_preference'; +import type { TagSet } from './sdam/server_description'; +import { readPreferenceServerSelector } from './sdam/server_selection'; +import type { SrvPoller } from './sdam/srv_polling'; +import { Topology, TopologyEvents } from './sdam/topology'; +import { ClientSession, ClientSessionOptions, ServerSessionPool } from './sessions'; +import { ClientMetadata, HostAddress, MongoDBNamespace, ns, resolveOptions } from './utils'; +import type { W, WriteConcern, WriteConcernSettings } 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 + * @deprecated Please use the `writeConcern` option instead + */ + w?: W; + /** + * The write concern timeout + * @deprecated Please use the `writeConcern` option instead + */ + wtimeoutMS?: number; + /** + * The journal write concern + * @deprecated Please use the `writeConcern` option instead + */ + journal?: boolean; + /** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + writeConcern?: WriteConcern | WriteConcernSettings; + /** 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; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable in-use 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 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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +export class MongoClient extends TypedEventEmitter { + /** @internal */ + s: MongoClientPrivate; + /** @internal */ + topology?: Topology; + /** @internal */ + readonly mongoLogger: MongoLogger; + + /** + * The consolidate, parsed, transformed and merged options. + * @internal + */ + [kOptions]: MongoOptions; + + constructor(url: string, options?: MongoClientOptions) { + super(); + + this[kOptions] = parseOptions(url, this, options); + this.mongoLogger = new MongoLogger(this[kOptions].mongoLoggerOptions); + + // 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 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; + } + + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + async connect(): Promise { + if (this.topology && this.topology.isConnected()) { + return this; + } + + const options = this[kOptions]; + + if (typeof options.srvHost === 'string') { + const hosts = await resolveSRVRecord(options); + + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + } + + 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 + this.topology = topology; + topology.client = this; + + topology.once(Topology.OPEN, () => this.emit('open', this)); + + for (const event of MONGO_CLIENT_EVENTS) { + topology.on(event, (...args: any[]) => this.emit(event, ...(args as any))); + } + + const topologyConnect = async () => { + try { + await promisify(callback => topology.connect(options, callback))(); + } catch (error) { + topology.close({ force: true }); + throw error; + } + }; + + if (this.autoEncrypter) { + const initAutoEncrypter = promisify(callback => this.autoEncrypter?.init(callback)); + await initAutoEncrypter(); + await topologyConnect(); + await options.encrypter.connectInternalClient(); + } else { + await topologyConnect(); + } + + return this; + } + + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + async close(force = false): Promise { + // There's no way to set hasBeenClosed back to false + Object.defineProperty(this.s, 'hasBeenClosed', { + value: true, + enumerable: true, + configurable: false, + writable: false + }); + + const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession()); + this.s.activeSessions.clear(); + + await Promise.all(activeSessionEnds); + + if (this.topology == null) { + return; + } + + // If we would attempt to select a server and get nothing back we short circuit + // to avoid the server selection timeout. + const selector = readPreferenceServerSelector(ReadPreference.primaryPreferred); + const topologyDescription = this.topology.description; + const serverDescriptions = Array.from(topologyDescription.servers.values()); + const servers = selector(topologyDescription, serverDescriptions); + if (servers.length !== 0) { + const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); + if (endSessions.length !== 0) { + await this.db('admin') + .command( + { endSessions }, + { readPreference: ReadPreference.primaryPreferred, noResponse: true } + ) + .catch(() => null); // outcome does not matter + } + } + + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + + await 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(); + }); + }); + } + + /** + * 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 async connect(url: string, options?: MongoClientOptions): Promise { + const client = new this(url, options); + return client.connect(); + } + + /** Starts a new session on the server */ + 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 + */ + async withSession(callback: WithSessionCallback): Promise; + async withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise; + async 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); + + try { + await withSessionCallback(session); + } finally { + try { + await session.endSession(); + } catch { + // We are not concerned with errors from endSession() + } + } + } + + /** + * 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 use cases: + * - 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)); + } +} + +/** + * Mongo Client Options + * @public + */ +export interface MongoOptions + extends Required< + Pick< + MongoClientOptions, + | 'autoEncryption' + | 'connectTimeoutMS' + | 'directConnection' + | 'driverInfo' + | 'forceServerObjectId' + | 'minHeartbeatFrequencyMS' + | 'heartbeatFrequencyMS' + | 'keepAlive' + | 'keepAliveInitialDelay' + | 'localThresholdMS' + | 'maxConnecting' + | 'maxIdleTimeMS' + | 'maxPoolSize' + | 'minPoolSize' + | 'monitorCommands' + | 'noDelay' + | 'pkFactory' + | '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; + + /** @internal */ + mongoLoggerOptions: MongoLoggerOptions; +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_logger.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_logger.ts new file mode 100644 index 00000000..81acd2af --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_logger.ts @@ -0,0 +1,201 @@ +import { Writable } from 'stream'; + +import { parseUnsignedInteger } from './utils'; + +/** @internal */ +export const SeverityLevel = Object.freeze({ + EMERGENCY: 'emergency', + ALERT: 'alert', + CRITICAL: 'critical', + ERROR: 'error', + WARNING: 'warn', + NOTICE: 'notice', + INFORMATIONAL: 'info', + DEBUG: 'debug', + TRACE: 'trace', + OFF: 'off' +} as const); + +/** @internal */ +export type SeverityLevel = typeof SeverityLevel[keyof typeof SeverityLevel]; + +/** @internal */ +export const MongoLoggableComponent = Object.freeze({ + COMMAND: 'command', + TOPOLOGY: 'topology', + SERVER_SELECTION: 'serverSelection', + CONNECTION: 'connection' +} as const); + +/** @internal */ +export type MongoLoggableComponent = + typeof MongoLoggableComponent[keyof typeof MongoLoggableComponent]; + +/** @internal */ +export interface MongoLoggerEnvOptions { + /** Severity level for command component */ + MONGODB_LOG_COMMAND?: string; + /** Severity level for topology component */ + MONGODB_LOG_TOPOLOGY?: string; + /** Severity level for server selection component */ + MONGODB_LOG_SERVER_SELECTION?: string; + /** Severity level for CMAP */ + MONGODB_LOG_CONNECTION?: string; + /** Default severity level to be if any of the above are unset */ + MONGODB_LOG_ALL?: string; + /** Max length of embedded EJSON docs. Setting to 0 disables truncation. Defaults to 1000. */ + MONGODB_LOG_MAX_DOCUMENT_LENGTH?: string; + /** Destination for log messages. Must be 'stderr', 'stdout'. Defaults to 'stderr'. */ + MONGODB_LOG_PATH?: string; +} + +/** @internal */ +export interface MongoLoggerMongoClientOptions { + /** Destination for log messages */ + mongodbLogPath?: 'stdout' | 'stderr' | Writable; +} + +/** @internal */ +export interface MongoLoggerOptions { + componentSeverities: { + /** Severity level for command component */ + command: SeverityLevel; + /** Severity level for topology component */ + topology: SeverityLevel; + /** Severity level for server selection component */ + serverSelection: SeverityLevel; + /** Severity level for connection component */ + connection: SeverityLevel; + /** Default severity level to be used if any of the above are unset */ + default: SeverityLevel; + }; + + /** Max length of embedded EJSON docs. Setting to 0 disables truncation. Defaults to 1000. */ + maxDocumentLength: number; + /** Destination for log messages. */ + logDestination: Writable; +} + +/** + * Parses a string as one of SeverityLevel + * + * @param s - the value to be parsed + * @returns one of SeverityLevel if value can be parsed as such, otherwise null + */ +function parseSeverityFromString(s?: string): SeverityLevel | null { + const validSeverities: string[] = Object.values(SeverityLevel); + const lowerSeverity = s?.toLowerCase(); + + if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { + return lowerSeverity as SeverityLevel; + } + + return null; +} + +/** + * resolves the MONGODB_LOG_PATH and mongodbLogPath options from the environment and the + * mongo client options respectively. + * + * @returns the Writable stream to write logs to + */ +function resolveLogPath( + { MONGODB_LOG_PATH }: MongoLoggerEnvOptions, + { + mongodbLogPath + }: { + mongodbLogPath?: unknown; + } +): Writable { + const isValidLogDestinationString = (destination: string) => + ['stdout', 'stderr'].includes(destination.toLowerCase()); + if (typeof mongodbLogPath === 'string' && isValidLogDestinationString(mongodbLogPath)) { + return mongodbLogPath.toLowerCase() === 'stderr' ? process.stderr : process.stdout; + } + + // TODO(NODE-4813): check for minimal interface instead of instanceof Writable + if (typeof mongodbLogPath === 'object' && mongodbLogPath instanceof Writable) { + return mongodbLogPath; + } + + if (typeof MONGODB_LOG_PATH === 'string' && isValidLogDestinationString(MONGODB_LOG_PATH)) { + return MONGODB_LOG_PATH.toLowerCase() === 'stderr' ? process.stderr : process.stdout; + } + + return process.stderr; +} + +/** @internal */ +export class MongoLogger { + componentSeverities: Record; + maxDocumentLength: number; + logDestination: Writable; + + constructor(options: MongoLoggerOptions) { + this.componentSeverities = options.componentSeverities; + this.maxDocumentLength = options.maxDocumentLength; + this.logDestination = options.logDestination; + } + + /* eslint-disable @typescript-eslint/no-unused-vars */ + /* eslint-disable @typescript-eslint/no-empty-function */ + emergency(component: any, message: any): void {} + + alert(component: any, message: any): void {} + + critical(component: any, message: any): void {} + + error(component: any, message: any): void {} + + warn(component: any, message: any): void {} + + notice(component: any, message: any): void {} + + info(component: any, message: any): void {} + + debug(component: any, message: any): void {} + + trace(component: any, message: any): void {} + + /** + * Merges options set through environment variables and the MongoClient, preferring environment + * variables when both are set, and substituting defaults for values not set. Options set in + * constructor take precedence over both environment variables and MongoClient options. + * + * @remarks + * When parsing component severity levels, invalid values are treated as unset and replaced with + * the default severity. + * + * @param envOptions - options set for the logger from the environment + * @param clientOptions - options set for the logger in the MongoClient options + * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger + */ + static resolveOptions( + envOptions: MongoLoggerEnvOptions, + clientOptions: MongoLoggerMongoClientOptions + ): MongoLoggerOptions { + // client options take precedence over env options + const combinedOptions = { + ...envOptions, + ...clientOptions, + mongodbLogPath: resolveLogPath(envOptions, clientOptions) + }; + const defaultSeverity = + parseSeverityFromString(combinedOptions.MONGODB_LOG_ALL) ?? SeverityLevel.OFF; + + return { + componentSeverities: { + command: parseSeverityFromString(combinedOptions.MONGODB_LOG_COMMAND) ?? defaultSeverity, + topology: parseSeverityFromString(combinedOptions.MONGODB_LOG_TOPOLOGY) ?? defaultSeverity, + serverSelection: + parseSeverityFromString(combinedOptions.MONGODB_LOG_SERVER_SELECTION) ?? defaultSeverity, + connection: + parseSeverityFromString(combinedOptions.MONGODB_LOG_CONNECTION) ?? defaultSeverity, + default: defaultSeverity + }, + maxDocumentLength: + parseUnsignedInteger(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1000, + logDestination: combinedOptions.mongodbLogPath + }; + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_types.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_types.ts new file mode 100644 index 00000000..ceee3aa6 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/mongo_types.ts @@ -0,0 +1,561 @@ +import type { BSONType, 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 required 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 = { + [P in keyof WithId]?: Condition[P]>; +} & 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 type BSONTypeAlias = keyof typeof BSONType; + +/** @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 | bigint; + +/** @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> & Record; + +/** @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/ + * + * @remarks + * Through testing we determined that a depth of 8 is safe for the typescript compiler + * and provides reasonable compilation times. This number is otherwise not special and + * should be changed if issues are found with this level of checking. Beyond this + * depth any helpers that make use of NestedPaths should devolve to not asserting any + * type safety on the input. + */ +export type NestedPaths = Depth['length'] extends 8 + ? [] + : Type extends + | string + | number + | bigint + | 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] | [Key]; + }[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 +>; + +/** + * @public + * @experimental + */ +export type StrictFilter = + | Partial + | ({ + [Property in Join, []>, '.'>]?: Condition< + PropertyType, Property> + >; + } & RootFilterOperators>); + +/** + * @public + * @experimental + */ +export type StrictUpdateFilter = { + $currentDate?: OnlyFieldsOfType< + TSchema, + Date | Timestamp, + true | { $type: 'date' | 'timestamp' } + >; + $inc?: OnlyFieldsOfType; + $min?: StrictMatchKeysAndValues; + $max?: StrictMatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: StrictMatchKeysAndValues; + $setOnInsert?: StrictMatchKeysAndValues; + $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 + * @experimental + */ +export type StrictMatchKeysAndValues = Readonly< + { + [Property in Join, '.'>]?: PropertyType; + } & { + [Property in `${NestedPathsOfType}.$${`[${string}]` | ''}`]?: ArrayElement< + PropertyType + >; + } & { + [Property in `${NestedPathsOfType[]>}.$${ + | `[${string}]` + | ''}.${string}`]?: any; // Could be further narrowed + } & Document +>; diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/add_user.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/add_user.ts new file mode 100644 index 00000000..be5982a4 --- /dev/null +++ b/1_ActivityWatchProducer/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 { + /** 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 + // v5 removed the digestPassword option from AddUserOptions but we still want to throw + // an error when digestPassword is provided. + if ('digestPassword' in options && 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/aggregate.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/aggregate.ts new file mode 100644 index 00000000..ea0b7fa4 --- /dev/null +++ b/1_ActivityWatchProducer/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; + } else { + delete this.options.writeConcern; + } + + 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 (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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/bulk_write.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/bulk_write.ts new file mode 100644 index 00000000..f56fd8c5 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/bulk_write.ts @@ -0,0 +1,62 @@ +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 }).then( + result => callback(undefined, result), + error => callback(error) + ); + } +} + +defineAspects(BulkWriteOperation, [Aspect.WRITE_OPERATION]); diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/collections.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/collections.ts new file mode 100644 index 00000000..14a1ccbb --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/collections.ts @@ -0,0 +1,50 @@ +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 { + // Let's get the collection names + this.db + .listCollections( + {}, + { ...this.options, nameOnly: true, readPreference: this.readPreference, session } + ) + .toArray() + .then( + documents => { + const collections = []; + for (const { name } of documents) { + if (!name.includes('$')) { + // Filter collections removing any illegal ones + collections.push(new Collection(this.db, name, this.db.s.options)); + } + } + // Return the collection objects + callback(undefined, collections); + }, + error => callback(error) + ); + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/command.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/command.ts new file mode 100644 index 00000000..0aa1a69e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/command.ts @@ -0,0 +1,159 @@ +import type { BSONSerializeOptions, Document } from '../bson'; +import { MongoInvalidArgumentError } from '../error'; +import { Explain, ExplainOptions } from '../explain'; +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'; + +/** @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 { + /** 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; + bsonOptions?: BSONSerializeOptions; +} + +/** @internal */ +export abstract class CommandOperation extends AbstractOperation { + override options: CommandOperationOptions; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + explain?: Explain; + + 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); + + 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; + } + + 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 (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + + 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) { + cmd = decorateWithExplain(cmd, this.explain); + } + + server.command(this.ns, cmd, options, callback); + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/common_functions.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/common_functions.ts new file mode 100644 index 00000000..63f7e1f2 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/common_functions.ts @@ -0,0 +1,105 @@ +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() + .then( + indexes => { + if (!Array.isArray(indexes)) return callback(undefined, []); + if (full) return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }, + error => callback(error) + ); +} + +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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/count.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/count.ts new file mode 100644 index 00000000..8d94b84e --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/count_documents.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/count_documents.ts new file mode 100644 index 00000000..c781329f --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/create_collection.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/create_collection.ts new file mode 100644 index 00000000..1d51d9af --- /dev/null +++ b/1_ActivityWatchProducer/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', + 'useBigInt64', + '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 + * @see https://www.mongodb.com/docs/manual/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. This option is deprecated in MongoDB 3.2+ and will be removed once no longer supported by the server. */ + 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 */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection */ + 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) */ + 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 */ + 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/delete.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/delete.ts new file mode 100644 index 00000000..f4234ef4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/delete.ts @@ -0,0 +1,174 @@ +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 type { Callback, 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; +} + +/** @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; + } + + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o: Document) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + callback(new MongoCompatibilityError(`hint is not supported with unacknowledged writes`)); + 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.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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/distinct.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/distinct.ts new file mode 100644 index 00000000..5fe8585e --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/distinct.ts @@ -0,0 +1,90 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, decorateWithCollation, decorateWithReadConcern } 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; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (typeof options.comment !== 'undefined') { + cmd.comment = options.comment; + } + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err); + } + + 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/drop.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/drop.ts new file mode 100644 index 00000000..2fd1569d --- /dev/null +++ b/1_ActivityWatchProducer/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 configured 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 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/estimated_document_count.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/estimated_document_count.ts new file mode 100644 index 00000000..22b29deb --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/eval.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/eval.ts new file mode 100644 index 00000000..3c34c59d --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/execute_operation.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/execute_operation.ts new file mode 100644 index 00000000..f8619de7 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/execute_operation.ts @@ -0,0 +1,287 @@ +import type { Document } from '../bson'; +import { + isRetryableReadError, + isRetryableWriteError, + MongoCompatibilityError, + MONGODB_ERROR_CODES, + MongoError, + MongoErrorLabel, + 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, maybeCallback, 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 { + return maybeCallback(() => executeOperationAsync(client, operation), callback); +} + +async function executeOperationAsync< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(client: MongoClient, operation: T): Promise { + if (!(operation instanceof AbstractOperation)) { + // TODO(NODE-3483): Extend MongoRuntimeError + throw new MongoRuntimeError('This method requires a valid operation instance'); + } + + if (client.topology == null) { + // Auto connect on operation + if (client.s.hasBeenClosed) { + throw new MongoNotConnectedError('Client must be connected before running operations'); + } + client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true; + try { + await client.connect(); + } finally { + delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')]; + } + } + + const { topology } = client; + if (topology == null) { + throw new MongoRuntimeError('client.connect did not create a topology but also did not throw'); + } + + if (topology.shouldCheckForSessionSupport()) { + await topology.selectServerAsync(ReadPreference.primaryPreferred, {}); + } + + // 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) { + throw new MongoExpiredSessionError('Use of expired sessions is not permitted'); + } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + throw 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. + throw 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; + } + } + + const readPreference = operation.readPreference ?? ReadPreference.primary; + const inTransaction = !!session?.inTransaction(); + + if (inTransaction && !readPreference.equals(ReadPreference.primary)) { + throw 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 server = await topology.selectServerAsync(selector, { session }); + + if (session == null) { + // No session also means it is not retryable, early exit + return operation.executeAsync(server, undefined); + } + + if (!operation.hasAspect(Aspect.RETRYABLE)) { + // non-retryable operation, early exit + try { + return await operation.executeAsync(server, session); + } finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } + } + + 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); + const willRetry = (hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite); + + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + + try { + return await operation.executeAsync(server, session); + } catch (operationError) { + if (willRetry && operationError instanceof MongoError) { + return await retryOperation(operation, operationError, { + session, + topology, + selector + }); + } + throw operationError; + } finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } +} + +/** @internal */ +type RetryOptions = { + session: ClientSession; + topology: Topology; + selector: ReadPreference | ServerSelector; +}; + +async function retryOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>( + operation: T, + originalError: MongoError, + { session, topology, selector }: RetryOptions +): Promise { + const isWriteOperation = operation.hasAspect(Aspect.WRITE_OPERATION); + const isReadOperation = operation.hasAspect(Aspect.READ_OPERATION); + + if (isWriteOperation && originalError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { + throw new MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError + }); + } + + if (isWriteOperation && !isRetryableWriteError(originalError)) { + throw originalError; + } + + if (isReadOperation && !isRetryableReadError(originalError)) { + throw 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 + const server = await topology.selectServerAsync(selector, { session }); + + if (isWriteOperation && !supportsRetryableWrites(server)) { + throw new MongoUnexpectedServerResponseError( + 'Selected server does not support retryable writes' + ); + } + + try { + return await operation.executeAsync(server, session); + } catch (retryError) { + if ( + retryError instanceof MongoError && + retryError.hasErrorLabel(MongoErrorLabel.NoWritesPerformed) + ) { + throw originalError; + } + throw retryError; + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/find.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/find.ts new file mode 100644 index 00000000..f1e98eb4 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/find.ts @@ -0,0 +1,272 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { 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, 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 Omit { + /** 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; + /** + * Option to enable an optimized code path for queries looking for a particular range of `ts` values in the oplog. Requires `tailable` to be true. + * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored. + */ + oplogReplay?: boolean; +} + +/** @internal */ +export class FindOperation extends CommandOperation { + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + override options: FindOptions & { writeConcern?: never }; + filter: Document; + + constructor( + collection: Collection | undefined, + ns: MongoDBNamespace, + filter: Document = {}, + options: FindOptions = {} + ) { + super(collection, options); + + this.options = { ...options }; + delete this.options.writeConcern; + 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 options = this.options; + + 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.oplogReplay === 'boolean') { + findCommand.oplogReplay = options.oplogReplay; + } + + 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/find_and_modify.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/find_and_modify.ts new file mode 100644 index 00000000..d292c423 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/find_and_modify.ts @@ -0,0 +1,286 @@ +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; + } + + // 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/get_more.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/get_more.ts new file mode 100644 index 00000000..c86c3f36 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/get_more.ts @@ -0,0 +1,106 @@ +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'; + +/** @internal */ +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; + /** TODO(NODE-4413): Address bug with maxAwaitTimeMS not being passed in from the cursor correctly */ + maxAwaitTimeMS?: number; +} + +/** + * GetMore command: https://www.mongodb.com/docs/manual/reference/command/getMore/ + * @internal + */ +export interface GetMoreCommand { + getMore: Long; + collection: string; + batchSize?: number; + maxTimeMS?: number; + /** Only supported on wire versions 10 or greater */ + comment?: unknown; +} + +/** @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; + 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') + ); + } + + if (this.cursorId == null || this.cursorId.isZero()) { + return callback(new MongoRuntimeError('Unable to iterate cursor with no id')); + } + + const collection = this.ns.collection; + if (collection == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + return callback(new MongoRuntimeError('A collection name must be determined before getMore')); + } + + const getMoreCmd: GetMoreCommand = { + getMore: this.cursorId, + collection + }; + + if (typeof this.options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(this.options.batchSize); + } + + if (typeof this.options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined && maxWireVersion(server) >= 9) { + getMoreCmd.comment = this.options.comment; + } + + const commandOptions = { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch', + ...this.options + }; + + server.command(this.ns, getMoreCmd, commandOptions, callback); + } +} + +defineAspects(GetMoreOperation, [Aspect.READ_OPERATION, Aspect.MUST_SELECT_SAME_SERVER]); diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/indexes.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/indexes.ts new file mode 100644 index 00000000..f8690836 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/indexes.ts @@ -0,0 +1,518 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import { MongoCompatibilityError, MONGODB_ERROR_CODES, MongoError } 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, isObject, maxWireVersion, MongoDBNamespace } 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' + | 'hashed' + | number; + +function isIndexDirection(x: unknown): x is IndexDirection { + return ( + typeof x === 'number' || x === '2d' || x === '2dsphere' || x === 'text' || x === 'geoHaystack' + ); +} +/** @public */ +export type IndexSpecification = OneOrMore< + | string + | [string, IndexDirection] + | { [key: string]: IndexDirection } + | Map +>; + +/** @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: { [key: string]: IndexDirection } | Map; +} + +/** @public */ +export interface CreateIndexesOptions extends Omit { + /** 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 isSingleIndexTuple(t: unknown): t is [string, IndexDirection] { + return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]); +} + +function makeIndexSpec( + indexSpec: IndexSpecification, + options?: CreateIndexesOptions +): IndexDescription { + const key: Map = new Map(); + + const indexSpecs = + !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec; + + // Iterate through array and handle different types + for (const spec of indexSpecs) { + if (typeof spec === 'string') { + key.set(spec, 1); + } else if (Array.isArray(spec)) { + key.set(spec[0], spec[1] ?? 1); + } else if (spec instanceof Map) { + for (const [property, value] of spec) { + key.set(property, value); + } + } else if (isObject(spec)) { + for (const [property, value] of Object.entries(spec)) { + key.set(property, value); + } + } + } + + return { ...options, key }; +} + +/** @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: ReadonlyArray & { key: Map }>; + + constructor( + parent: OperationParent, + collectionName: string, + indexes: IndexDescription[], + options?: CreateIndexesOptions + ) { + super(parent, options); + + this.options = options ?? {}; + this.collectionName = collectionName; + this.indexes = indexes.map(userIndex => { + // Ensure the key is a Map to preserve index key ordering + const key = + userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key)); + const name = userIndex.name != null ? userIndex.name : Array.from(key).flat().join('_'); + const validIndexOptions = Object.fromEntries( + Object.entries({ ...userIndex }).filter(([optionName]) => + VALID_INDEX_OPTIONS.has(optionName) + ) + ); + return { + ...validIndexOptions, + name, + key + }; + }); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const options = this.options; + const indexes = this.indexes; + + const serverWireVersion = maxWireVersion(server); + + 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 + ) { + 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().then( + indexes => { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + super.execute(server, session, callback); + }, + error => { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + // ignore "NamespaceNotFound" errors + return super.execute(server, session, callback); + } + return callback(error); + } + ); + } +} + +/** @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 Omit { + /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */ + batchSize?: number; +} + +/** @internal */ +export class ListIndexesOperation extends CommandOperation { + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + override options: ListIndexesOptions & { writeConcern?: never }; + collectionNamespace: MongoDBNamespace; + + constructor(collection: Collection, options?: ListIndexesOptions) { + super(collection, options); + + this.options = { ...options }; + delete this.options.writeConcern; + 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/insert.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/insert.ts new file mode 100644 index 00000000..6475a5cf --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/is_capped.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/is_capped.ts new file mode 100644 index 00000000..1219e79c --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/is_capped.ts @@ -0,0 +1,44 @@ +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() + .then( + collections => { + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new MongoAPIError(`collection ${coll.namespace} not found`)); + } + + callback(undefined, !!collections[0].options?.capped); + }, + error => callback(error) + ); + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/kill_cursors.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/kill_cursors.ts new file mode 100644 index 00000000..59c78c15 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/kill_cursors.ts @@ -0,0 +1,53 @@ +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'; + +/** + * https://www.mongodb.com/docs/manual/reference/command/killCursors/ + * @internal + */ +interface KillCursorsCommand { + killCursors: string; + cursors: Long[]; + comment?: unknown; +} + +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') + ); + } + + const killCursors = this.ns.collection; + if (killCursors == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + return callback( + new MongoRuntimeError('A collection name must be determined before killCursors') + ); + } + + const killCursorsCommand: KillCursorsCommand = { + killCursors, + cursors: [this.cursorId] + }; + + server.command(this.ns, killCursorsCommand, { session }, () => callback()); + } +} + +defineAspects(KillCursorsOperation, [Aspect.MUST_SELECT_SAME_SERVER]); diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/list_collections.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/list_collections.ts new file mode 100644 index 00000000..f9cb7d57 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/list_collections.ts @@ -0,0 +1,99 @@ +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 Omit { + /** 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 { + /** + * @remarks WriteConcern can still be present on the options because + * we inherit options from the client/db/collection. The + * key must be present on the options in order to delete it. + * This allows typescript to delete the key but will + * not allow a writeConcern to be assigned as a property on options. + */ + override options: ListCollectionsOptions & { writeConcern?: never }; + db: Db; + filter: Document; + nameOnly: boolean; + authorizedCollections: boolean; + batchSize?: number; + + constructor(db: Db, filter: Document, options?: ListCollectionsOptions) { + super(db, options); + + this.options = { ...options }; + delete this.options.writeConcern; + 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/list_databases.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/list_databases.ts new file mode 100644 index 00000000..537c9529 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/operation.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/operation.ts new file mode 100644 index 00000000..573a896b --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/operation.ts @@ -0,0 +1,139 @@ +import { promisify } from 'util'; + +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; + + executeAsync: (server: Server, session: ClientSession | undefined) => Promise; + + constructor(options: OperationOptions = {}) { + this.executeAsync = promisify( + ( + server: Server, + session: ClientSession | undefined, + callback: (e: Error, r: TResult) => void + ) => { + this.execute(server, session, callback as any); + } + ); + + 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/options_operation.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/options_operation.ts new file mode 100644 index 00000000..9c053938 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/options_operation.ts @@ -0,0 +1,45 @@ +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() + .then( + collections => { + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new MongoAPIError(`collection ${coll.namespace} not found`)); + } + + callback(undefined, collections[0].options); + }, + error => callback(error) + ); + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/operations/profiling_level.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/profiling_level.ts new file mode 100644 index 00000000..defe6b0d --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/remove_user.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/remove_user.ts new file mode 100644 index 00000000..f32c19c2 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/rename.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/rename.ts new file mode 100644 index 00000000..02e27a5b --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/run_command.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/run_command.ts new file mode 100644 index 00000000..b92237a9 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/set_profiling_level.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/set_profiling_level.ts new file mode 100644 index 00000000..6fc8502d --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/stats.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/stats.ts new file mode 100644 index 00000000..b63a70de --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/update.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/update.ts new file mode 100644 index 00000000..278a0b34 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/update.ts @@ -0,0 +1,306 @@ +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, hasAtomicOperators, 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?: Hint; + /** 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 unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o: Document) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + callback(new MongoCompatibilityError(`hint is not supported with unacknowledged writes`)); + 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 | 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/1_ActivityWatchProducer/node_modules/mongodb/src/operations/validate_collection.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/operations/validate_collection.ts new file mode 100644 index 00000000..ba6c85fa --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/read_concern.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/read_concern.ts new file mode 100644 index 00000000..09e39be5 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/read_preference.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/read_preference.ts new file mode 100644 index 00000000..1f3d2d0c --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/read_preference.ts @@ -0,0 +1,262 @@ +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, 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); + } 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 + * @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/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/common.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/common.ts new file mode 100644 index 00000000..a2ffd894 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/common.ts @@ -0,0 +1,79 @@ +import { clearTimeout } from 'timers'; + +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/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/events.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/events.ts new file mode 100644 index 00000000..c55eb095 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/monitor.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/monitor.ts new file mode 100644 index 00000000..ebb032a9 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/monitor.ts @@ -0,0 +1,595 @@ +import { clearTimeout, 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 { MongoError, MongoErrorLabel, MongoNetworkTimeoutError } from '../error'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import type { Callback } from '../utils'; +import { calculateDurationInMs, EventEmitterWithState, 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?: MongoError): 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]?: MonitorInterval; + [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, + useBigInt64: 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] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: 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] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: 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) + ); + + const error = !(err instanceof MongoError) ? new MongoError(err) : err; + error.addErrorLabel(MongoErrorLabel.ResetPool); + if (error instanceof MongoNetworkTimeoutError) { + error.addErrorLabel(MongoErrorLabel.InterruptInUseConnections); + } + + monitor.emit('resetServer', error); + 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]: 1, + ...(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; + + 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) => { + if (monitor.s.state === STATE_MONITORING) { + process.nextTick(callback); + return; + } + 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) { + 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 + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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(); + }); +} + +/** + * @internal + */ +export interface MonitorIntervalOptions { + /** The interval to execute a method on */ + heartbeatFrequencyMS: number; + /** A minimum interval that must elapse before the method is called */ + minHeartbeatFrequencyMS: number; + /** Whether the method should be called immediately when the interval is started */ + immediate: boolean; +} + +/** + * @internal + */ +export class MonitorInterval { + fn: (callback: Callback) => void; + timerId: NodeJS.Timeout | undefined; + lastExecutionEnded: number; + isExpeditedCallToFnScheduled = false; + stopped = false; + isExecutionInProgress = false; + hasExecutedOnce = false; + + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; + + constructor(fn: (callback: Callback) => void, options: Partial = {}) { + this.fn = fn; + this.lastExecutionEnded = -Infinity; + + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1000; + this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500; + + if (options.immediate) { + this._executeAndReschedule(); + } else { + this._reschedule(undefined); + } + } + + wake() { + const currentTime = now(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + + // TODO(NODE-4674): Add error handling and logging to the monitor + if (timeSinceLastCall < 0) { + return this._executeAndReschedule(); + } + + if (this.isExecutionInProgress) { + return; + } + + // debounce multiple calls to wake within the `minInterval` + if (this.isExpeditedCallToFnScheduled) { + return; + } + + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeSinceLastCall < this.minHeartbeatFrequencyMS) { + this.isExpeditedCallToFnScheduled = true; + this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall); + return; + } + + this._executeAndReschedule(); + } + + stop() { + this.stopped = true; + if (this.timerId) { + clearTimeout(this.timerId); + this.timerId = undefined; + } + + this.lastExecutionEnded = -Infinity; + this.isExpeditedCallToFnScheduled = false; + } + + toString() { + return JSON.stringify(this); + } + + toJSON() { + const currentTime = now(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + return { + timerId: this.timerId != null ? 'set' : 'cleared', + lastCallTime: this.lastExecutionEnded, + isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled, + stopped: this.stopped, + heartbeatFrequencyMS: this.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS, + currentTime, + timeSinceLastCall + }; + } + + private _reschedule(ms?: number) { + if (this.stopped) return; + if (this.timerId) { + clearTimeout(this.timerId); + } + + this.timerId = setTimeout(this._executeAndReschedule, ms || this.heartbeatFrequencyMS); + } + + private _executeAndReschedule = () => { + if (this.stopped) return; + if (this.timerId) { + clearTimeout(this.timerId); + } + + this.isExpeditedCallToFnScheduled = false; + this.isExecutionInProgress = true; + + this.fn(() => { + this.lastExecutionEnded = now(); + this.isExecutionInProgress = false; + this._reschedule(this.heartbeatFrequencyMS); + }); + }; +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server.ts new file mode 100644 index 00000000..4ed6c1cb --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server.ts @@ -0,0 +1,563 @@ +import type { Document } from '../bson'; +import { CommandOptions, Connection, DestroyOptions } from '../cmap/connection'; +import { + ConnectionPool, + ConnectionPoolEvents, + ConnectionPoolOptions +} from '../cmap/connection_pool'; +import { PoolClearedError } from '../cmap/errors'; +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 { + AnyError, + isNetworkErrorBeforeHandshake, + isNodeShuttingDownError, + isSDAMUnrecoverableError, + MongoError, + MongoErrorLabel, + MongoInvalidArgumentError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoRuntimeError, + MongoServerClosedError, + MongoServerError, + MongoUnexpectedServerResponseError, + needsRetryableWriteLabel +} from '../error'; +import type { ServerApi } from '../mongo_client'; +import { TypedEventEmitter } from '../mongo_types'; +import type { GetMoreOptions } from '../operations/get_more'; +import type { ClientSession } from '../sessions'; +import { isTransactionCommand } from '../transactions'; +import { + Callback, + 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'); + +/** @internal */ +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; + /** 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, + state: STATE_CLOSED, + topology, + pool: new ConnectionPool(this, 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('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 = { force: false }; + } + 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; + } + + 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; + if (!err) { + return cb(new MongoRuntimeError('Failed to create connection without error')); + } + if (!(err instanceof PoolClearedError)) { + this.handleError(err); + } + return cb(err); + } + + conn.command( + ns, + cmd, + finalOptions, + makeOperationHandler(this, conn, cmd, finalOptions, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + }) + ); + }, + callback + ); + } + + /** + * Handle SDAM error + * @internal + */ + handleError(error: AnyError, connection?: Connection) { + if (!(error instanceof MongoError)) { + return; + } + + const isStaleError = + error.connectionGeneration && error.connectionGeneration < this.s.pool.generation; + if (isStaleError) { + return; + } + + const isNetworkNonTimeoutError = + error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError); + const isNetworkTimeoutBeforeHandshakeError = isNetworkErrorBeforeHandshake(error); + const isAuthHandshakeError = error.hasErrorLabel(MongoErrorLabel.HandshakeError); + if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + if (!this.loadBalanced) { + error.addErrorLabel(MongoErrorLabel.ResetPool); + markServerUnknown(this, error); + } else if (connection) { + this.s.pool.clear({ serviceId: connection.serviceId }); + } + } else { + if (isSDAMUnrecoverableError(error)) { + if (shouldHandleStateChangeError(this, error)) { + const shouldClearPool = maxWireVersion(this) <= 7 || isNodeShuttingDownError(error); + if (this.loadBalanced && connection && shouldClearPool) { + this.s.pool.clear({ serviceId: connection.serviceId }); + } + + if (!this.loadBalanced) { + if (shouldClearPool) { + error.addErrorLabel(MongoErrorLabel.ResetPool); + } + markServerUnknown(this, error); + process.nextTick(() => this.requestCheck()); + } + } + } + } + } +} + +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?: MongoServerError) { + // 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 }) + ); +} + +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) { + // We should not swallow an error if it is present. + if (error == null && result != null) { + return callback(undefined, result); + } + + if (options != null && 'noResponse' in options && options.noResponse === true) { + return callback(undefined, null); + } + + 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); + } + } else { + if ( + (isRetryableWritesEnabled(server.s.topology) || isTransactionCommand(cmd)) && + needsRetryableWriteLabel(error, maxWireVersion(server)) && + !inActiveTransaction(session, cmd) + ) { + error.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + } + + if ( + session && + session.isPinned && + error.hasErrorLabel(MongoErrorLabel.TransientTransactionError) + ) { + session.unpin({ force: true }); + } + + server.handleError(error, connection); + + return callback(error); + }; +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server_description.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server_description.ts new file mode 100644 index 00000000..ab5da450 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server_description.ts @@ -0,0 +1,262 @@ +import { Document, Long, ObjectId } from '../bson'; +import { MongoError, MongoRuntimeError, MongoServerError } from '../error'; +import { arrayStrictEqual, compareObjectId, 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?: MongoServerError; + + /** The round trip time to ping this server (in ms) */ + roundTripTime?: number; + + /** 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 { + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error: MongoError | null; + topologyVersion: TopologyVersion | null; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me: string | null; + primary: string | null; + setName: string | null; + setVersion: number | null; + electionId: ObjectId | null; + logicalSessionTimeoutMinutes: number | null; + + // 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 (address == null || address === '') { + throw new MongoRuntimeError('ServerDescription must be provided with a non-empty address'); + } + + this.address = + typeof address === 'string' + ? HostAddress.fromString(address).toString() // Use HostAddress to normalize + : address.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; + this.error = options.error ?? null; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this.topologyVersion = this.error?.topologyVersion ?? hello?.topologyVersion ?? null; + this.setName = hello?.setName ?? null; + this.setVersion = hello?.setVersion ?? null; + this.electionId = hello?.electionId ?? null; + this.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes ?? null; + this.primary = hello?.primary ?? null; + this.me = hello?.me?.toLowerCase() ?? null; + this.$clusterTime = hello?.$clusterTime ?? null; + } + + get hostAddress(): HostAddress { + return HostAddress.fromString(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 | null): boolean { + // Despite using the comparator that would determine a nullish topologyVersion as greater than + // for equality we should only always perform direct equality comparison + const topologyVersionsEqual = + this.topologyVersion === other?.topologyVersion || + compareTopologyVersion(this.topologyVersion, other?.topologyVersion) === 0; + + const electionIdsEqual = + this.electionId != null && other?.electionId != null + ? compareObjectId(this.electionId, other.electionId) === 0 + : 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. + * + * 1. If the response topologyVersion is unset or the ServerDescription's + * topologyVersion is null, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is not equal to the + * ServerDescription's, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is equal to the + * ServerDescription's, the client MUST use the counter field to determine + * which topologyVersion is more recent. + * + * ```ts + * currentTv < newTv === -1 + * currentTv === newTv === 0 + * currentTv > newTv === 1 + * ``` + */ +export function compareTopologyVersion( + currentTv?: TopologyVersion | null, + newTv?: TopologyVersion | null +): 0 | -1 | 1 { + if (currentTv == null || newTv == null) { + return -1; + } + + if (!currentTv.processId.equals(newTv.processId)) { + return -1; + } + + // TODO(NODE-2674): Preserve int64 sent from MongoDB + const currentCounter = Long.isLong(currentTv.counter) + ? currentTv.counter + : Long.fromNumber(currentTv.counter); + const newCounter = Long.isLong(newTv.counter) ? newTv.counter : Long.fromNumber(newTv.counter); + + return currentCounter.compare(newCounter); +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server_selection.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/server_selection.ts new file mode 100644 index 00000000..c7c2b563 --- /dev/null +++ b/1_ActivityWatchProducer/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; + +/** @internal */ +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/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/srv_polling.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/srv_polling.ts new file mode 100644 index 00000000..253f3a74 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/srv_polling.ts @@ -0,0 +1,157 @@ +import * as dns from 'dns'; +import { clearTimeout, setTimeout } from 'timers'; + +import { MongoRuntimeError } from '../error'; +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 { + 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; + 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.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; + } + } + + // TODO(NODE-4994): implement new logging logic for SrvPoller failures + schedule(): void { + if (this._timeout) { + clearTimeout(this._timeout); + } + + this._timeout = setTimeout(() => { + this._poll().catch(() => null); + }, this.intervalMS); + } + + success(srvRecords: dns.SrvRecord[]): void { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + + failure(): void { + this.haMode = true; + this.schedule(); + } + + async _poll(): Promise { + const generation = this.generation; + let srvRecords; + + try { + srvRecords = await dns.promises.resolveSrv(this.srvAddress); + } catch (dnsError) { + this.failure(); + return; + } + + if (generation !== this.generation) { + return; + } + + const finalAddresses: dns.SrvRecord[] = []; + for (const record of srvRecords) { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } + } + + if (!finalAddresses.length) { + this.failure(); + return; + } + + this.success(finalAddresses); + } +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/topology.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/topology.ts new file mode 100644 index 00000000..3b447a6f --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/topology.ts @@ -0,0 +1,1011 @@ +import { clearTimeout, setTimeout } from 'timers'; +import { promisify } from 'util'; + +import type { BSONSerializeOptions, Document } 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, + MongoError, + MongoErrorLabel, + 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, + EventEmitterWithState, + HostAddress, + List, + 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; +} + +/** @internal */ +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]: List; + /** @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; + + selectServerAsync: ( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions + ) => Promise; + + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor(seeds: string | string[] | HostAddress | HostAddress[], options: TopologyOptions) { + super(); + + this.selectServerAsync = promisify( + ( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions, + callback: (e: Error, r: Server) => void + ) => this.selectServer(selector, options, callback as any) + ); + + // 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 List(); + 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(callback: Callback): void; + connect(options: ConnectOptions, callback: Callback): void; + connect(options?: ConnectOptions | Callback, 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): void; + close(options: CloseOptions, callback: Callback): void; + close(options?: CloseOptions, callback?: Callback): void { + options = options ?? { force: false }; + + 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, { force: !!options?.force }); + }); + + 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; + } + + // 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 | null { + 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 ?? { force: false }; + 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; + if ( + incomingServerDescription.error instanceof MongoError && + incomingServerDescription.error.hasErrorLabel(MongoErrorLabel.ResetPool) + ) { + const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel( + MongoErrorLabel.InterruptInUseConnections + ); + + server.s.pool.clear({ interruptInUseConnections }); + } else if (incomingServerDescription.error == null) { + const newTopologyType = topology.s.description.type; + const shouldMarkPoolReady = + incomingServerDescription.isDataBearing || + (incomingServerDescription.type !== ServerType.Unknown && + newTopologyType === TopologyType.Single); + if (shouldMarkPoolReady) { + server.s.pool.ready(); + } + } + } + } + + // 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: List, 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 { + const descriptions = 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/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/topology_description.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/topology_description.ts new file mode 100644 index 00000000..d35a9ad6 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/sdam/topology_description.ts @@ -0,0 +1,511 @@ +import type { ObjectId } from '../bson'; +import * as WIRE_CONSTANTS from '../cmap/wire_protocol/constants'; +import { MongoRuntimeError, MongoServerError } from '../error'; +import { compareObjectId, 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 | null; + maxSetVersion: number | null; + maxElectionId: ObjectId | null; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes: number | null; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion: number; + + /** + * Create a TopologyDescription + */ + constructor( + topologyType: TopologyType, + serverDescriptions: Map | null = null, + setName: string | null = null, + maxSetVersion: number | null = null, + maxElectionId: ObjectId | null = null, + commonWireVersion: number | null = null, + options: TopologyDescriptionOptions | null = null + ) { + 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; + this.setName = setName ?? null; + this.maxElectionId = maxElectionId ?? null; + this.maxSetVersion = maxSetVersion ?? null; + this.commonWireVersion = commonWireVersion ?? 0; + + // 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 = null; + 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 = null; + 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; + + 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); + } + } + + if ( + typeof serverDescription.setName === 'string' && + typeof setName === 'string' && + serverDescription.setName !== setName + ) { + if (topologyType === TopologyType.Single) { + // "Single" Topology with setName mismatch is direct connection usage, mark unknown do not remove + serverDescription = new ServerDescription(address); + } else { + serverDescriptions.delete(address); + } + } + + // 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(): MongoServerError | null { + const descriptionsWithError = Array.from(this.servers.values()).filter( + (sd: ServerDescription) => sd.error + ); + + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; + } + + return null; + } + + /** + * 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; + } +} + +function updateRsFromPrimary( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName: string | null = null, + maxSetVersion: number | null = null, + maxElectionId: ObjectId | null = null +): [TopologyType, string | null, number | null, ObjectId | null] { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + if (serverDescription.maxWireVersion >= 17) { + const electionIdComparison = compareObjectId(maxElectionId, serverDescription.electionId); + const maxElectionIdIsEqual = electionIdComparison === 0; + const maxElectionIdIsLess = electionIdComparison === -1; + const maxSetVersionIsLessOrEqual = + (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1); + + if (maxElectionIdIsLess || (maxElectionIdIsEqual && maxSetVersionIsLessOrEqual)) { + // The reported electionId was greater + // or the electionId was equal and reported setVersion was greater + // Always update both values, they are a tuple + maxElectionId = serverDescription.electionId; + maxSetVersion = serverDescription.setVersion; + } else { + // Stale primary + // replace serverDescription with a default ServerDescription of type "Unknown" + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } else { + 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 | null = null +): 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 | null = null +): [TopologyType, string | null] { + 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/1_ActivityWatchProducer/node_modules/mongodb/src/sessions.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sessions.ts new file mode 100644 index 00000000..3f76044d --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/sessions.ts @@ -0,0 +1,1044 @@ +import { promisify } from 'util'; + +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 { ReadConcernLevel } from './read_concern'; +import { ReadPreference } from './read_preference'; +import { _advanceClusterTime, ClusterTime, TopologyType } from './sdam/common'; +import { isTransactionCommand, Transaction, TransactionOptions, TxnState } from './transactions'; +import { + ByteUtils, + calculateDurationInMs, + Callback, + commandSupportsReadConcern, + isPromiseLike, + List, + maxWireVersion, + 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; + + const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true; + this.supports = { + // if we can enable causal consistency, do so by default + causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue + }; + + 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 + */ + async endSession(options?: EndSessionOptions): Promise { + try { + if (this.inTransaction()) { + await this.abortTransaction(); + } + if (!this.hasEnded) { + 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); + } + } catch { + // spec indicates that we should ignore all errors for `endSessions` + } finally { + maybeClearPinnedConnection(this, { force: true, ...options }); + } + } + + /** + * 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 !== 'bigint' && + 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 ByteUtils.equals(this.id.id.buffer, 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 supported in 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. + */ + async commitTransaction(): Promise { + return endTransactionAsync(this, 'commitTransaction'); + } + + /** + * Aborts the currently active transaction in this session. + */ + async abortTransaction(): Promise { + return endTransactionAsync(this, 'abortTransaction'); + } + + /** + * 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 + */ + async 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({ serviceId: 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 { + 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); + } + ); +} + +const endTransactionAsync = promisify( + endTransaction as ( + session: ClientSession, + commandName: 'abortTransaction' | 'commitTransaction', + callback: (error: Error, result: Document) => void + ) => void +); + +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: List; + + constructor(client: MongoClient) { + if (client == null) { + throw new MongoRuntimeError('ServerSessionPool requires a MongoClient'); + } + + this.client = client; + this.sessions = new List(); + } + + /** + * 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; + } + + this.sessions.prune(session => session.hasTimedOut(sessionTimeoutMinutes)); + + 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; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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/1_ActivityWatchProducer/node_modules/mongodb/src/sort.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/sort.ts new file mode 100644 index 00000000..6b766b54 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/src/transactions.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/transactions.ts new file mode 100644 index 00000000..bff2df19 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/transactions.ts @@ -0,0 +1,188 @@ +import type { Document } from './bson'; +import { MongoRuntimeError, MongoTransactionError } from './error'; +import type { CommandOperationOptions } from './operations/command'; +import { ReadConcern, ReadConcernLike } from './read_concern'; +import type { ReadPreferenceLike } from './read_preference'; +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?: ReadPreferenceLike; + /** 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/1_ActivityWatchProducer/node_modules/mongodb/src/utils.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/utils.ts new file mode 100644 index 00000000..db076acf --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/src/utils.ts @@ -0,0 +1,1353 @@ +import * as crypto from 'crypto'; +import type { SrvRecord } from 'dns'; +import * as os from 'os'; +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 { Hint, OperationOptions } from './operations/operation'; +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 type AnyOptions = Document; + +export const ByteUtils = { + toLocalBufferType(this: void, buffer: Buffer | Uint8Array): Buffer { + return Buffer.isBuffer(buffer) + ? buffer + : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + }, + + equals(this: void, seqA: Uint8Array, seqB: Uint8Array) { + return ByteUtils.toLocalBufferType(seqA).equals(seqB); + }, + + compare(this: void, seqA: Uint8Array, seqB: Uint8Array) { + return ByteUtils.toLocalBufferType(seqA).compare(seqB); + }, + + toBase64(this: void, uint8array: Uint8Array) { + return ByteUtils.toLocalBufferType(uint8array).toString('base64'); + } +}; + +/** + * 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; +} + +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 resolution type of the possible promise + * @param value - An object that could be a promise + * @returns true if the provided value is a Promise + */ +export function isPromiseLike(value?: PromiseLike | void): value is Promise { + return !!value && typeof value.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'); +} + +/** @internal */ +export function ns(ns: string): MongoDBNamespace { + return MongoDBNamespace.fromString(ns); +} + +/** @public */ +export class MongoDBNamespace { + db: string; + collection: string | undefined; + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db: string, collection?: string) { + this.db = db; + this.collection = collection === '' ? undefined : 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 (typeof namespace !== 'string' || namespace === '') { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + + const [db, ...collectionParts] = namespace.split('.'); + const collection = collectionParts.join('.'); + return new MongoDBNamespace(db, collection === '' ? undefined : collection); + } +} + +/** @internal */ +export function* makeCounter(seed = 0): Generator { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} + +/** + * Helper for handling legacy callback support. + */ +export function maybeCallback(promiseFn: () => Promise, callback: null): Promise; +export function maybeCallback( + promiseFn: () => Promise, + callback?: Callback +): Promise | void; +export function maybeCallback( + promiseFn: () => Promise, + callback?: Callback | null +): Promise | void { + const promise = promiseFn(); + if (callback == null) { + return promise; + } + + promise.then( + result => callback(undefined, result), + error => callback(error) + ); + return; +} + +/** @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 available 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; +} + +/** + * 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 | null, rhs?: AnyError | null): 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; +} + +/** @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; +} + +type ListNode = { + value: T; + next: ListNode | HeadNode; + prev: ListNode | HeadNode; +}; + +type HeadNode = { + value: null; + next: ListNode; + prev: ListNode; +}; + +/** + * When a list is empty the head is a reference with pointers to itself + * So this type represents that self referential state + */ +type EmptyNode = { + value: null; + next: EmptyNode; + prev: EmptyNode; +}; + +/** + * A sequential list of items in a circularly linked list + * @remarks + * The head node is special, it is always defined and has a value of null. + * It is never "included" in the list, in that, it is not returned by pop/shift or yielded by the iterator. + * The circular linkage and always defined head node are to reduce checks for null next/prev references to zero. + * New nodes are declared as object literals with keys always in the same order: next, prev, value. + * @internal + */ +export class List { + private readonly head: HeadNode | EmptyNode; + private count: number; + + get length() { + return this.count; + } + + get [Symbol.toStringTag]() { + return 'List' as const; + } + + constructor() { + this.count = 0; + + // this is carefully crafted: + // declaring a complete and consistently key ordered + // object is beneficial to the runtime optimizations + this.head = { + next: null, + prev: null, + value: null + } as unknown as EmptyNode; + this.head.next = this.head; + this.head.prev = this.head; + } + + toArray() { + return Array.from(this); + } + + toString() { + return `head <=> ${this.toArray().join(' <=> ')} <=> head`; + } + + *[Symbol.iterator](): Generator { + for (const node of this.nodes()) { + yield node.value; + } + } + + private *nodes(): Generator, void, void> { + let ptr: HeadNode | ListNode | EmptyNode = this.head.next; + while (ptr !== this.head) { + // Save next before yielding so that we make removing within iteration safe + const { next } = ptr as ListNode; + yield ptr as ListNode; + ptr = next; + } + } + + /** Insert at end of list */ + push(value: T) { + this.count += 1; + const newNode: ListNode = { + next: this.head as HeadNode, + prev: this.head.prev as ListNode, + value + }; + this.head.prev.next = newNode; + this.head.prev = newNode; + } + + /** Inserts every item inside an iterable instead of the iterable itself */ + pushMany(iterable: Iterable) { + for (const value of iterable) { + this.push(value); + } + } + + /** Insert at front of list */ + unshift(value: T) { + this.count += 1; + const newNode: ListNode = { + next: this.head.next as ListNode, + prev: this.head as HeadNode, + value + }; + this.head.next.prev = newNode; + this.head.next = newNode; + } + + private remove(node: ListNode | EmptyNode): T | null { + if (node === this.head || this.length === 0) { + return null; + } + + this.count -= 1; + + const prevNode = node.prev; + const nextNode = node.next; + prevNode.next = nextNode; + nextNode.prev = prevNode; + + return node.value; + } + + /** Removes the first node at the front of the list */ + shift(): T | null { + return this.remove(this.head.next); + } + + /** Removes the last node at the end of the list */ + pop(): T | null { + return this.remove(this.head.prev); + } + + /** Iterates through the list and removes nodes where filter returns true */ + prune(filter: (value: T) => boolean) { + for (const node of this.nodes()) { + if (filter(node.value)) { + this.remove(node); + } + } + } + + clear() { + this.count = 0; + this.head.next = this.head as EmptyNode; + this.head.prev = this.head as EmptyNode; + } + + /** Returns the first item in the list, does not remove */ + first(): T | null { + // If the list is empty, value will be the head's null + return this.head.next.value; + } + + /** Returns the last item in the list, does not remove */ + last(): T | null { + // If the list is empty, value will be the head's null + return this.head.prev.value; + } +} + +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +export class BufferPool { + private buffers: List; + private totalByteLength: number; + + constructor() { + this.buffers = new List(); + this.totalByteLength = 0; + } + + get length(): number { + return this.totalByteLength; + } + + /** Adds a buffer to the internal buffer pool list */ + append(buffer: Buffer): void { + this.buffers.push(buffer); + this.totalByteLength += buffer.length; + } + + /** + * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes, + * otherwise return null. Size can be negative, caller should error check. + */ + getInt32(): number | null { + if (this.totalByteLength < 4) { + return null; + } + const firstBuffer = this.buffers.first(); + if (firstBuffer != null && firstBuffer.byteLength >= 4) { + return firstBuffer.readInt32LE(0); + } + + // Unlikely case: an int32 is split across buffers. + // Use read and put the returned buffer back on top + const top4Bytes = this.read(4); + const value = top4Bytes.readInt32LE(0); + + // Put it back. + this.totalByteLength += 4; + this.buffers.unshift(top4Bytes); + + return value; + } + + /** Reads the requested number of bytes, optionally consuming them */ + read(size: number): Buffer { + if (typeof size !== 'number' || size < 0) { + throw new MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + + // oversized request returns empty buffer + if (size > this.totalByteLength) { + return Buffer.alloc(0); + } + + // We know we have enough, we just don't know how it is spread across chunks + // TODO(NODE-4732): alloc API should change based on raw option + const result = Buffer.allocUnsafe(size); + + for (let bytesRead = 0; bytesRead < size; ) { + const buffer = this.buffers.shift(); + if (buffer == null) { + break; + } + const bytesRemaining = size - bytesRead; + const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); + const bytes = buffer.subarray(0, bytesReadable); + + result.set(bytes, bytesRead); + + bytesRead += bytesReadable; + this.totalByteLength -= bytesReadable; + if (bytesReadable < buffer.byteLength) { + this.buffers.unshift(buffer.subarray(bytesReadable)); + } + } + + return result; + } +} + +/** @public */ +export class HostAddress { + host: string | undefined = undefined; + port: number | undefined = undefined; + socketPath: string | undefined = undefined; + isIPv6 = false; + + constructor(hostString: string) { + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + + if (escapedHost.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(escapedHost); + return; + } + + const urlString = `iLoveJS://${escapedHost}`; + let url; + try { + url = new URL(urlString); + } catch (urlError) { + const runtimeError = new MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); + runtimeError.cause = urlError; + throw runtimeError; + } + + const hostname = url.hostname; + const port = url.port; + + 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'); + } + Object.freeze(this); + } + + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new HostAddress('${this.toString()}')`; + } + + toString(): string { + if (typeof this.host === 'string') { + if (this.isIPv6) { + 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 + * ```ts + * 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; +} + +/** + * 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(NODE-4936): read concern eligibility for commands 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. */ +export function getMongoDBClientEncryption(): { + extension: (mdb: unknown) => { + AutoEncrypter: any; + ClientEncryption: any; + }; +} | null { + let mongodbClientEncryption = null; + + // 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 + ) { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require(process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE); + } catch { + // ignore + } + } else { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require('mongodb-client-encryption'); + } catch { + // ignore + } + } + + return mongodbClientEncryption; +} + +/** + * Compare objectIds. `null` is always less + * - `+1 = oid1 is greater than oid2` + * - `-1 = oid1 is less than oid2` + * - `+0 = oid1 is equal oid2` + */ +export function compareObjectId(oid1?: ObjectId | null, oid2?: ObjectId | null): 0 | 1 | -1 { + if (oid1 == null && oid2 == null) { + return 0; + } + + if (oid1 == null) { + return -1; + } + + if (oid2 == null) { + return 1; + } + + return ByteUtils.compare(oid1.id, oid2.id); +} + +export function parseInteger(value: unknown): number | null { + if (typeof value === 'number') return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + + return Number.isNaN(parsedValue) ? null : parsedValue; +} + +export function parseUnsignedInteger(value: unknown): number | null { + const parsedInt = parseInteger(value); + + return parsedInt != null && parsedInt >= 0 ? parsedInt : null; +} diff --git a/1_ActivityWatchProducer/node_modules/mongodb/src/write_concern.ts b/1_ActivityWatchProducer/node_modules/mongodb/src/write_concern.ts new file mode 100644 index 00000000..ebc77ebf --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/mongodb/tsconfig.json b/1_ActivityWatchProducer/node_modules/mongodb/tsconfig.json new file mode 100644 index 00000000..55dd558a --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/mongodb/tsconfig.json @@ -0,0 +1,46 @@ +{ + "compilerOptions": { + "allowJs": false, + "checkJs": false, + "strict": true, + "alwaysStrict": true, + "target": "ES2020", + "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/1_ActivityWatchProducer/node_modules/punycode/LICENSE-MIT.txt b/1_ActivityWatchProducer/node_modules/punycode/LICENSE-MIT.txt new file mode 100644 index 00000000..a41e0a7e --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/punycode/README.md b/1_ActivityWatchProducer/node_modules/punycode/README.md new file mode 100644 index 00000000..72b632cd --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/punycode/README.md @@ -0,0 +1,126 @@ +# Punycode.js [![punycode on npm](https://img.shields.io/npm/v/punycode)](https://www.npmjs.com/package/emoji-test-regex-pattern) [![](https://data.jsdelivr.com/v1/package/npm/punycode/badge)](https://www.jsdelivr.com/package/npm/punycode) + +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). + +This project provides a CommonJS module that uses ES2015+ features and JavaScript module, which work in modern Node.js versions and browsers. For the old Punycode.js version that offers the same functionality in a UMD build with support for older pre-ES2015 runtimes, including Rhino, Ringo, and Narwhal, see [v1.4.1](https://github.com/mathiasbynens/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/): + +> ⚠️ Note that userland modules don't hide core modules. +> For example, `require('punycode')` still imports the deprecated core module even if you executed `npm install punycode`. +> Use `require('punycode/')` to import userland modules rather than core modules. + +```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/1_ActivityWatchProducer/node_modules/punycode/package.json b/1_ActivityWatchProducer/node_modules/punycode/package.json new file mode 100644 index 00000000..9d0790b2 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/punycode/package.json @@ -0,0 +1,58 @@ +{ + "name": "punycode", + "version": "2.3.0", + "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/mathiasbynens/punycode.js.git" + }, + "bugs": "https://github.com/mathiasbynens/punycode.js/issues", + "files": [ + "LICENSE-MIT.txt", + "punycode.js", + "punycode.es6.js" + ], + "scripts": { + "test": "mocha tests", + "build": "node scripts/prepublish.js" + }, + "devDependencies": { + "codecov": "^1.0.1", + "istanbul": "^0.4.1", + "mocha": "^10.2.0" + }, + "jspm": { + "map": { + "./punycode.js": { + "node": "@node/punycode" + } + } + } +} diff --git a/1_ActivityWatchProducer/node_modules/punycode/punycode.es6.js b/1_ActivityWatchProducer/node_modules/punycode/punycode.es6.js new file mode 100644 index 00000000..244e1bfb --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/punycode/punycode.es6.js @@ -0,0 +1,444 @@ +'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-\x7F]/; // Note: U+007F DEL is excluded too. +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, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(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 {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.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] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).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 = codePoints => String.fromCodePoint(...codePoints); + +/** + * 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 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + 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`. + const 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) { + error('invalid-input'); + } + if (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. + const 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)); + } + } + + const 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/1_ActivityWatchProducer/node_modules/punycode/punycode.js b/1_ActivityWatchProducer/node_modules/punycode/punycode.js new file mode 100644 index 00000000..752b98a9 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/punycode/punycode.js @@ -0,0 +1,443 @@ +'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-\x7F]/; // Note: U+007F DEL is excluded too. +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, callback) { + const result = []; + let length = array.length; + while (length--) { + result[length] = callback(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 {String} A new string of characters returned by the callback + * function. + */ +function mapDomain(domain, callback) { + const parts = domain.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] + '@'; + domain = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + domain = domain.replace(regexSeparators, '\x2E'); + const labels = domain.split('.'); + const encoded = map(labels, callback).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 = codePoints => String.fromCodePoint(...codePoints); + +/** + * 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 && codePoint < 0x3A) { + return 26 + (codePoint - 0x30); + } + if (codePoint >= 0x41 && codePoint < 0x5B) { + return codePoint - 0x41; + } + if (codePoint >= 0x61 && codePoint < 0x7B) { + 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`. + const 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) { + error('invalid-input'); + } + if (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. + const 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)); + } + } + + const 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/1_ActivityWatchProducer/node_modules/saslprep/.editorconfig b/1_ActivityWatchProducer/node_modules/saslprep/.editorconfig new file mode 100644 index 00000000..d1d8a417 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/.gitattributes b/1_ActivityWatchProducer/node_modules/saslprep/.gitattributes new file mode 100644 index 00000000..3ba45360 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/saslprep/.gitattributes @@ -0,0 +1 @@ +*.mem binary diff --git a/1_ActivityWatchProducer/node_modules/saslprep/.travis.yml b/1_ActivityWatchProducer/node_modules/saslprep/.travis.yml new file mode 100644 index 00000000..0bca8265 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/saslprep/.travis.yml @@ -0,0 +1,10 @@ +sudo: false +language: node_js +node_js: + - "6" + - "8" + - "10" + - "12" + +before_install: +- npm install -g npm@6 diff --git a/1_ActivityWatchProducer/node_modules/saslprep/CHANGELOG.md b/1_ActivityWatchProducer/node_modules/saslprep/CHANGELOG.md new file mode 100644 index 00000000..77980787 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/LICENSE b/1_ActivityWatchProducer/node_modules/saslprep/LICENSE new file mode 100644 index 00000000..481c7a50 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/code-points.mem b/1_ActivityWatchProducer/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-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YBg{{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/1_ActivityWatchProducer/node_modules/saslprep/lib/code-points.js b/1_ActivityWatchProducer/node_modules/saslprep/lib/code-points.js new file mode 100644 index 00000000..222182c8 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/lib/memory-code-points.js b/1_ActivityWatchProducer/node_modules/saslprep/lib/memory-code-points.js new file mode 100644 index 00000000..cb0289c8 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/lib/util.js b/1_ActivityWatchProducer/node_modules/saslprep/lib/util.js new file mode 100644 index 00000000..506bdc99 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/package.json b/1_ActivityWatchProducer/node_modules/saslprep/package.json new file mode 100644 index 00000000..23c35627 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/readme.md b/1_ActivityWatchProducer/node_modules/saslprep/readme.md new file mode 100644 index 00000000..8ff3d70d --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/test/index.js b/1_ActivityWatchProducer/node_modules/saslprep/test/index.js new file mode 100644 index 00000000..80c71af5 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/saslprep/test/util.js b/1_ActivityWatchProducer/node_modules/saslprep/test/util.js new file mode 100644 index 00000000..355db3f8 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/socks/build/client/socksclient.js b/1_ActivityWatchProducer/node_modules/socks/build/client/socksclient.js index 05da4baa..c3439169 100644 --- a/1_ActivityWatchProducer/node_modules/socks/build/client/socksclient.js +++ b/1_ActivityWatchProducer/node_modules/socks/build/client/socksclient.js @@ -104,12 +104,12 @@ class SocksClient extends events_1.EventEmitter { return reject(err); } } - let sock; // Shuffle proxies if (options.randomizeChain) { (0, util_1.shuffleArray)(options.proxies); } try { + let sock; 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. @@ -125,12 +125,10 @@ class SocksClient extends events_1.EventEmitter { 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. + existing_socket: sock, }); // If sock is undefined, assign it here. - if (!sock) { - sock = result.socket; - } + sock = sock || result.socket; } if (typeof callback === 'function') { callback(null, { socket: sock }); diff --git a/1_ActivityWatchProducer/node_modules/socks/build/client/socksclient.js.map b/1_ActivityWatchProducer/node_modules/socks/build/client/socksclient.js.map index b39f3add..f01f317e 100644 --- a/1_ActivityWatchProducer/node_modules/socks/build/client/socksclient.js.map +++ b/1_ActivityWatchProducer/node_modules/socks/build/client/socksclient.js.map @@ -1 +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,OA07BN;AAh6BlB,MAAM,WAAY,SAAQ,qBAAY;IAgBpC,YAAY,OAA2B;QACrC,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,OAAO,qBACP,OAAO,CACX,CAAC;QAEF,8BAA8B;QAC9B,IAAA,oCAA0B,EAAC,OAAO,CAAC,CAAC;QAEpC,gBAAgB;QAChB,IAAI,CAAC,QAAQ,CAAC,4BAAgB,CAAC,OAAO,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,gBAAgB,CACrB,OAA2B,EAC3B,QAGS;QAET,OAAO,IAAI,OAAO,CAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAClE,8BAA8B;YAC9B,IAAI;gBACF,IAAA,oCAA0B,EAAC,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;aAClD;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;oBAClC,QAAQ,CAAC,GAAG,CAAC,CAAC;oBACd,8DAA8D;oBAC9D,OAAO,OAAO,CAAC,GAAU,CAAC,CAAC,CAAC,oDAAoD;iBACjF;qBAAM;oBACL,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;iBACpB;aACF;YAED,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;YACxC,MAAM,CAAC,IAAI,CAAC,aAAa,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AAU,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 +{"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;AAw7B5D,iGAx7BM,uBAAgB,OAw7BN;AA95BlB,MAAM,WAAY,SAAQ,qBAAY;IAgBpC,YAAY,OAA2B;QACrC,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,OAAO,qBACP,OAAO,CACX,CAAC;QAEF,8BAA8B;QAC9B,IAAA,oCAA0B,EAAC,OAAO,CAAC,CAAC;QAEpC,gBAAgB;QAChB,IAAI,CAAC,QAAQ,CAAC,4BAAgB,CAAC,OAAO,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,gBAAgB,CACrB,OAA2B,EAC3B,QAGS;QAET,OAAO,IAAI,OAAO,CAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAClE,8BAA8B;YAC9B,IAAI;gBACF,IAAA,oCAA0B,EAAC,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;aAClD;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,OAAO,QAAQ,KAAK,UAA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AC;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/1_ActivityWatchProducer/node_modules/socks/package.json b/1_ActivityWatchProducer/node_modules/socks/package.json index ac0b6d39..0f5054b9 100644 --- a/1_ActivityWatchProducer/node_modules/socks/package.json +++ b/1_ActivityWatchProducer/node_modules/socks/package.json @@ -1,7 +1,7 @@ { "name": "socks", "private": false, - "version": "2.7.0", + "version": "2.7.1", "description": "Fully featured SOCKS proxy client supporting SOCKSv4, SOCKSv4a, and SOCKSv5. Includes Bind and Associate functionality.", "main": "build/index.js", "typings": "typings/index.d.ts", diff --git a/1_ActivityWatchProducer/node_modules/sparse-bitfield/.npmignore b/1_ActivityWatchProducer/node_modules/sparse-bitfield/.npmignore new file mode 100644 index 00000000..3c3629e6 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/sparse-bitfield/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/1_ActivityWatchProducer/node_modules/sparse-bitfield/.travis.yml b/1_ActivityWatchProducer/node_modules/sparse-bitfield/.travis.yml new file mode 100644 index 00000000..c0428217 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/sparse-bitfield/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - '4.0' + - '5.0' diff --git a/1_ActivityWatchProducer/node_modules/sparse-bitfield/LICENSE b/1_ActivityWatchProducer/node_modules/sparse-bitfield/LICENSE new file mode 100644 index 00000000..bae9da7b --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/sparse-bitfield/README.md b/1_ActivityWatchProducer/node_modules/sparse-bitfield/README.md new file mode 100644 index 00000000..7b6b8f9e --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/sparse-bitfield/index.js b/1_ActivityWatchProducer/node_modules/sparse-bitfield/index.js new file mode 100644 index 00000000..ff458c97 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/sparse-bitfield/package.json b/1_ActivityWatchProducer/node_modules/sparse-bitfield/package.json new file mode 100644 index 00000000..092a23f6 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/sparse-bitfield/test.js b/1_ActivityWatchProducer/node_modules/sparse-bitfield/test.js new file mode 100644 index 00000000..ae42ef46 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/tr46/LICENSE.md b/1_ActivityWatchProducer/node_modules/tr46/LICENSE.md new file mode 100644 index 00000000..62c0de28 --- /dev/null +++ b/1_ActivityWatchProducer/node_modules/tr46/LICENSE.md @@ -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/1_ActivityWatchProducer/node_modules/tr46/README.md b/1_ActivityWatchProducer/node_modules/tr46/README.md new file mode 100644 index 00000000..1df7915b --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/tr46/index.js b/1_ActivityWatchProducer/node_modules/tr46/index.js new file mode 100644 index 00000000..7ce05327 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/tr46/lib/mappingTable.json b/1_ActivityWatchProducer/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 00000000..3d71a5ef --- /dev/null +++ b/1_ActivityWatchProducer/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,1,"Ꭳ"],[43892,1,"Ꭴ"],[43893,1,"Ꭵ"],[43894,1,"Ꭶ"],[43895,1,"Ꭷ"],[43896,1,"Ꭸ"],[43897,1,"Ꭹ"],[43898,1,"Ꭺ"],[43899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Ꮿ"],[[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/1_ActivityWatchProducer/node_modules/tr46/lib/regexes.js b/1_ActivityWatchProducer/node_modules/tr46/lib/regexes.js new file mode 100644 index 00000000..4dd8051e --- /dev/null +++ b/1_ActivityWatchProducer/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\u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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{1BC9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-\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-\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BFA\u0C00-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3C-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C5D\u0C60-\u0C63\u0C66-\u0C6F\u0C77-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDD\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D81-\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\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\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/1_ActivityWatchProducer/node_modules/tr46/lib/statusMapping.js b/1_ActivityWatchProducer/node_modules/tr46/lib/statusMapping.js new file mode 100644 index 00000000..cfed6d6a --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/tr46/package.json b/1_ActivityWatchProducer/node_modules/tr46/package.json new file mode 100644 index 00000000..8e79ba6c --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/webidl-conversions/LICENSE.md b/1_ActivityWatchProducer/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 00000000..d4a994f5 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/webidl-conversions/README.md b/1_ActivityWatchProducer/node_modules/webidl-conversions/README.md new file mode 100644 index 00000000..16cc3931 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/webidl-conversions/lib/index.js b/1_ActivityWatchProducer/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 00000000..0229347c --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/webidl-conversions/package.json b/1_ActivityWatchProducer/node_modules/webidl-conversions/package.json new file mode 100644 index 00000000..20747bb4 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/LICENSE.txt b/1_ActivityWatchProducer/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 00000000..8e8c25c3 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/README.md b/1_ActivityWatchProducer/node_modules/whatwg-url/README.md new file mode 100644 index 00000000..4d089006 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/index.js b/1_ActivityWatchProducer/node_modules/whatwg-url/index.js new file mode 100644 index 00000000..c470e48e --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/Function.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/Function.js new file mode 100644 index 00000000..ea8712fd --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/URL-impl.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 00000000..db3a0aea --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/URL.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 00000000..d62ac3e7 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/URLSearchParams-impl.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/URLSearchParams-impl.js new file mode 100644 index 00000000..ef8d604e --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/URLSearchParams.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/URLSearchParams.js new file mode 100644 index 00000000..a7c24eff --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/VoidFunction.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/VoidFunction.js new file mode 100644 index 00000000..9a00672a --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/encoding.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/encoding.js new file mode 100644 index 00000000..cb66b8f1 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/infra.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/infra.js new file mode 100644 index 00000000..4a984a3b --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/percent-encoding.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/percent-encoding.js new file mode 100644 index 00000000..f8308673 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/url-state-machine.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 00000000..d9ecae2e --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/urlencoded.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/urlencoded.js new file mode 100644 index 00000000..e7230637 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/lib/utils.js b/1_ActivityWatchProducer/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 00000000..3af17706 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/package.json b/1_ActivityWatchProducer/node_modules/whatwg-url/package.json new file mode 100644 index 00000000..9cb209f9 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/node_modules/whatwg-url/webidl2js-wrapper.js b/1_ActivityWatchProducer/node_modules/whatwg-url/webidl2js-wrapper.js new file mode 100644 index 00000000..b731ace5 --- /dev/null +++ b/1_ActivityWatchProducer/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/1_ActivityWatchProducer/package-lock.json b/1_ActivityWatchProducer/package-lock.json index bd46f9dd..3644cf89 100644 --- a/1_ActivityWatchProducer/package-lock.json +++ b/1_ActivityWatchProducer/package-lock.json @@ -10,7 +10,8 @@ "license": "MIT", "dependencies": { "express": "^4.18.1", - "keycloak-js": "^19.0.3" + "keycloak-js": "^19.0.3", + "mongodb": "^5.1.0" }, "devDependencies": { "electron-rebuild": "^3.2.9" @@ -139,8 +140,7 @@ "node_modules/@types/node": { "version": "18.7.13", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.13.tgz", - "integrity": "sha512-46yIhxSe5xEaJZXWdIBP7GU4HDTG8/eo0qd9atdiL+lFpA03y8KS+lkTN834TWJj5767GbWv4n/P6efyTFt1Dw==", - "dev": true + "integrity": "sha512-46yIhxSe5xEaJZXWdIBP7GU4HDTG8/eo0qd9atdiL+lFpA03y8KS+lkTN834TWJj5767GbWv4n/P6efyTFt1Dw==" }, "node_modules/@types/responselike": { "version": "1.0.0", @@ -151,6 +151,20 @@ "@types/node": "*" } }, + "node_modules/@types/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-xTE1E+YF4aWPJJeUzaZI5DRntlkY3+BCVJi0axFptnjGmAoWxkyREIh/XMrfxVLejwQxMCfDXdICo0VLxThrog==" + }, + "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/abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -357,6 +371,14 @@ "concat-map": "0.0.1" } }, + "node_modules/bson": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/bson/-/bson-5.0.1.tgz", + "integrity": "sha512-y09gBGusgHtinMon/GVbv1J6FrXhnr/+6hqLlSmEFzkz6PodqF6TxjyvfvY3AfO+oG1mgUtbC86xSbOlwvM62Q==", + "engines": { + "node": ">=14.20.1" + } + }, "node_modules/buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -1325,8 +1347,7 @@ "node_modules/ip": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", - "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==", - "dev": true + "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==" }, "node_modules/ipaddr.js": { "version": "1.9.1", @@ -1507,6 +1528,12 @@ "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", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", @@ -1682,6 +1709,47 @@ "node": ">=10" } }, + "node_modules/mongodb": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.1.0.tgz", + "integrity": "sha512-qgKb7y+EI90y4weY3z5+lIgm8wmexbonz0GalHkSElQXVKtRuwqXuhXKccyvIjXCJVy9qPV82zsinY0W1FBnJw==", + "dependencies": { + "bson": "^5.0.1", + "mongodb-connection-string-url": "^2.6.0", + "socks": "^2.7.1" + }, + "engines": { + "node": ">=14.20.1" + }, + "optionalDependencies": { + "saslprep": "^1.0.3" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.201.0", + "mongodb-client-encryption": "^2.3.0", + "snappy": "^7.2.2" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + }, + "snappy": { + "optional": true + } + } + }, + "node_modules/mongodb-connection-string-url": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", + "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + "dependencies": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^11.0.0" + } + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -1962,6 +2030,14 @@ "once": "^1.3.1" } }, + "node_modules/punycode": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", + "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==", + "engines": { + "node": ">=6" + } + }, "node_modules/qs": { "version": "6.10.3", "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.3.tgz", @@ -2123,6 +2199,18 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "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/semver": { "version": "7.3.7", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", @@ -2268,17 +2356,15 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "dev": true, "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==", - "dev": true, + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", + "integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", "dependencies": { "ip": "^2.0.0", "smart-buffer": "^4.2.0" @@ -2302,6 +2388,15 @@ "node": ">= 10" } }, + "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/ssri": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/ssri/-/ssri-9.0.1.tgz", @@ -2394,6 +2489,17 @@ "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/type-is": { "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", @@ -2478,6 +2584,26 @@ "defaults": "^1.0.3" } }, + "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/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -2661,8 +2787,7 @@ "@types/node": { "version": "18.7.13", "resolved": "https://registry.npmjs.org/@types/node/-/node-18.7.13.tgz", - "integrity": "sha512-46yIhxSe5xEaJZXWdIBP7GU4HDTG8/eo0qd9atdiL+lFpA03y8KS+lkTN834TWJj5767GbWv4n/P6efyTFt1Dw==", - "dev": true + "integrity": "sha512-46yIhxSe5xEaJZXWdIBP7GU4HDTG8/eo0qd9atdiL+lFpA03y8KS+lkTN834TWJj5767GbWv4n/P6efyTFt1Dw==" }, "@types/responselike": { "version": "1.0.0", @@ -2673,6 +2798,20 @@ "@types/node": "*" } }, + "@types/webidl-conversions": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + "integrity": "sha512-xTE1E+YF4aWPJJeUzaZI5DRntlkY3+BCVJi0axFptnjGmAoWxkyREIh/XMrfxVLejwQxMCfDXdICo0VLxThrog==" + }, + "@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": "*" + } + }, "abbrev": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", @@ -2833,6 +2972,11 @@ "concat-map": "0.0.1" } }, + "bson": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/bson/-/bson-5.0.1.tgz", + "integrity": "sha512-y09gBGusgHtinMon/GVbv1J6FrXhnr/+6hqLlSmEFzkz6PodqF6TxjyvfvY3AfO+oG1mgUtbC86xSbOlwvM62Q==" + }, "buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -3576,8 +3720,7 @@ "ip": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", - "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==", - "dev": true + "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==" }, "ipaddr.js": { "version": "1.9.1", @@ -3716,6 +3859,12 @@ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==" }, + "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", "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", @@ -3838,6 +3987,26 @@ "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", "dev": true }, + "mongodb": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.1.0.tgz", + "integrity": "sha512-qgKb7y+EI90y4weY3z5+lIgm8wmexbonz0GalHkSElQXVKtRuwqXuhXKccyvIjXCJVy9qPV82zsinY0W1FBnJw==", + "requires": { + "bson": "^5.0.1", + "mongodb-connection-string-url": "^2.6.0", + "saslprep": "^1.0.3", + "socks": "^2.7.1" + } + }, + "mongodb-connection-string-url": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", + "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + "requires": { + "@types/whatwg-url": "^8.2.1", + "whatwg-url": "^11.0.0" + } + }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -4044,6 +4213,11 @@ "once": "^1.3.1" } }, + "punycode": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz", + "integrity": "sha512-rRV+zQD8tVFys26lAGR9WUuS4iUAngJScM+ZRSKtvl5tKeZ2t5bvdNFdNHBW9FWR4guGHlgmsZ1G7BSm2wTbuA==" + }, "qs": { "version": "6.10.3", "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.3.tgz", @@ -4151,6 +4325,15 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "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" + } + }, "semver": { "version": "7.3.7", "resolved": "https://registry.npmjs.org/semver/-/semver-7.3.7.tgz", @@ -4274,14 +4457,12 @@ "smart-buffer": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", - "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", - "dev": true + "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==", - "dev": true, + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", + "integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", "requires": { "ip": "^2.0.0", "smart-buffer": "^4.2.0" @@ -4298,6 +4479,15 @@ "socks": "^2.6.2" } }, + "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" + } + }, "ssri": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/ssri/-/ssri-9.0.1.tgz", @@ -4369,6 +4559,14 @@ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==" }, + "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" + } + }, "type-is": { "version": "1.6.18", "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", @@ -4432,6 +4630,20 @@ "defaults": "^1.0.3" } }, + "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" + } + }, "which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/1_ActivityWatchProducer/package.json b/1_ActivityWatchProducer/package.json index 506a5024..6577d76a 100644 --- a/1_ActivityWatchProducer/package.json +++ b/1_ActivityWatchProducer/package.json @@ -16,6 +16,7 @@ }, "dependencies": { "express": "^4.18.1", - "keycloak-js": "^19.0.3" + "keycloak-js": "^19.0.3", + "mongodb": "^5.1.0" } } diff --git a/2_PAC/Apps/OpAdapter.js b/2_PAC/Apps/OpAdapter.js index cf0fdbb3..148292a1 100644 --- a/2_PAC/Apps/OpAdapter.js +++ b/2_PAC/Apps/OpAdapter.js @@ -18,12 +18,20 @@ class OpAdapter extends PacFactory{ super(jsap_file); //LOCALHOST - this.opClient=new OpClient({ + /*this.opClient=new OpClient({ host:"localhost", port:889, clientId:"n3d2NUpnrMU5HenPac3lRh5nE38AZAViekVOIDbnzGk", clientSecret:"xS2Ao-MPUmkLP3cT1Jyzhj4fgjLugSOiTxrGzLayAQc", apiKey:"37fdc215964b5f21fc99fde4e59a83d1c1c363eb2b818db2ff9a2af65e7f2d12" + });*/ + //REMOTE + this.opClient=new OpClient({ + host:"dld.arces.unibo.it",//"localhost",// + port:8078,//889,// + clientId:"pIuaMa7WY4xwkkVNobDjQpp_OSjzsUrMXEKnjCVkWQA", + clientSecret:"nNFyLa7MRSJ2Pnq9ju8_f3Lg4FxRW4Gs1EdFgfIAHr4", + apiKey:"bcc95e391fc9f7eee77aa7cb3bbc8cd126108d6a6623c944a72d56f09e3bd633" }); //PORTAINER /*this.opClient=new OpClient({ @@ -61,6 +69,7 @@ class OpAdapter extends PacFactory{ async update_tasks(){ var string_messages=await this.opClient.get_tasks("My2sec"); console.log("MAO") + throw new Error("MAO") //console.log(string_messages) for(var i in string_messages){ var msg=string_messages[i]; diff --git a/2_PAC/gregnet_modules/PacFactory/MongoDbClient.js b/2_PAC/gregnet_modules/PacFactory/MongoDbClient.js new file mode 100644 index 00000000..1f56d149 --- /dev/null +++ b/2_PAC/gregnet_modules/PacFactory/MongoDbClient.js @@ -0,0 +1,65 @@ +const { MongoClient } = require('mongodb') + + +class MongoDbClient{ + constructor(uri,database,collection){ + this.uri=uri; + this.database=database; + this.collection=collection; //one user has one collection, the name is the usergraph + } + + async insertFile(file){ + let client; + try{ + client = new MongoClient(this.uri); + const database = client.db(this.database); + const collection = database.collection(this.collection); + const result = await collection.insertOne(file); + //console.log(file); + return result; + }catch(e){ + console.log(e); + }finally{ + await client.close(); + } + } + + async getFile(query,options){ + let client; + try{ + client = new MongoClient(this.uri); + const database = client.db(this.database); + const collection = database.collection(this.collection); + if(!options) options={}; + const file = await collection.findOne(query, options); + //console.log(file); + return file; + }catch(e){ + console.log(e); + }finally{ + await client.close(); + } + } + + + +} + + +const config={ + user:"root", + password:"Gregnet-99", + url:"localhost", + port:"27017", + database:"local", + collection:"startup_log" +} + + +var uri="mongodb://root:Gregnet-99@localhost:27017/" +var database="local" +var collection="startup_log" +var client=new MongoDbClient(uri,database,collection); +var file=client.getFile({ + _id:"1aa11f35b6bf-1676558141161" +}); \ No newline at end of file diff --git a/2_PAC/gregnet_modules/PacFactory/OpenProjectClient.js b/2_PAC/gregnet_modules/PacFactory/OpenProjectClient.js index 92ac4219..66ae32fc 100644 --- a/2_PAC/gregnet_modules/PacFactory/OpenProjectClient.js +++ b/2_PAC/gregnet_modules/PacFactory/OpenProjectClient.js @@ -86,6 +86,12 @@ class OpenProjectClient { async get_tasks(whitelisted_projects){ + + var res=await this.get_auth_resource("/api/v3/work_packages"); + res=JSON.parse(res); + console.log(res) + throw new Error("MAUS") + console.log("Getting Work Packages ids..."); const work_packages_json = await this.em.getMany(WP); const work_packages_ids= this.get_work_packages_ids(work_packages_json); @@ -122,6 +128,10 @@ class OpenProjectClient { async get_tasks_old(whitelisted_projects){ console.log(1,"Getting Work Packages ids..."); + + + + const work_packages_json = await this.em.getMany(WP); const work_packages_ids= this.get_work_packages_ids(work_packages_json); diff --git a/2_PAC/gregnet_modules/PacFactory/SupersetClient.js b/2_PAC/gregnet_modules/PacFactory/SupersetClient.js new file mode 100644 index 00000000..9fe8ca70 --- /dev/null +++ b/2_PAC/gregnet_modules/PacFactory/SupersetClient.js @@ -0,0 +1,35 @@ +class SupersetClient{ + constructor(host,port){ + this.hostname=host; + this.port=port; + } + + getGuestToken(){ + + } + getToken(){ + const http = require('http'); + const options = { + hostname: this.host,//"openproject",//'host.docker.internal', + port: this.port,//80,//889, + path: "/api/v1/security/login", + method: 'POST', + headers: { + "Content-Type": 'application/json' + } + } + const req = http.request(options, res => { + let data = ''; + console.log('Status: ', res.statusCode); + //console.log('Headers: ', JSON.stringify(res.headers)); + res.setEncoding('utf8'); + res.on('data', chunk => {data += chunk;}); + res.on('end', () => {/*console.log('Body: ', JSON.parse(data))*/}); + }).on('error', e => { + console.error(e); + }); + + req.write(JSON.stringify(update)); + req.end(); + } +} \ No newline at end of file diff --git a/2_PAC/node_modules/.package-lock.json b/2_PAC/node_modules/.package-lock.json index 7244423b..7e961553 100644 --- a/2_PAC/node_modules/.package-lock.json +++ b/2_PAC/node_modules/.package-lock.json @@ -1,1661 +1,3628 @@ { - "name": "PacFactory", + + "name": "2_PAC", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@arces-wot/sepa-js": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/@arces-wot/sepa-js/-/sepa-js-0.12.1.tgz", + "integrity": "sha512-lvilgudP7hrfqHB9+uxY34tNeUO7f8sCs7D19xjCpqHVAdbBpWz4hHUt+8H7+wTDGV2XaJCPaex6SbRnQUzbgw==", + "dependencies": { + "axios": "^0.19.0", + "deepmerge": "^4.2.2", + "isomorphic-ws": "^4.0.0", + "ws": "^6.0.0" + } + }, + "node_modules/@servie/events": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@servie/events/-/events-1.0.0.tgz", + "integrity": "sha512-sBSO19KzdrJCM3gdx6eIxV8M9Gxfgg6iDQmH5TIAGaUu+X9VDdsINXJOnoiZ1Kx3TrHdH4bt5UVglkjsEGBcvw==" - }, + + }, + + "node_modules/@types/node": { + + "version": "18.13.0", + + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.13.0.tgz", + + "integrity": "sha512-gC3TazRzGoOnoKAhUx+Q0t8S9Tzs74z7m0ipwGpSqQrleP14hKxP4/JUeEQcD3W1/aIpnWl8pHowI7WokuZpXg==" + + }, + "node_modules/@types/tough-cookie": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-2.3.8.tgz", + "integrity": "sha512-7axfYN8SW9pWg78NgenHasSproWQee5rzyPVLC9HpaQSDgNArsnKJD88EaMfi4Pl48AyciO3agYCFqpHS1gLpg==" - }, + + }, + + "node_modules/@types/webidl-conversions": { + + "version": "7.0.0", + + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + + "integrity": "sha512-xTE1E+YF4aWPJJeUzaZI5DRntlkY3+BCVJi0axFptnjGmAoWxkyREIh/XMrfxVLejwQxMCfDXdICo0VLxThrog==" + + }, + + "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/101": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/101/-/101-1.6.3.tgz", + "integrity": "sha512-4dmQ45yY0Dx24Qxp+zAsNLlMF6tteCyfVzgbulvSyC7tCyd3V8sW76sS0tHq8NpcbXfWTKasfyfzU1Kd86oKzw==", + "dependencies": { + "clone": "^1.0.2", + "deep-eql": "^0.1.3", + "keypather": "^1.10.2" + } + }, + "node_modules/101/node_modules/keypather": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/keypather/-/keypather-1.10.2.tgz", + "integrity": "sha512-hgomDZ+POrsgpkE7qQuSI2ffyfVLJdDLxk8spzWeR33ovNssz6jCWDOIBLEPyI8SAWcQ5njl1ignlqgMrZsGpA==", + "dependencies": { + "101": "^1.0.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/assert-err": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assert-err/-/assert-err-1.1.0.tgz", + "integrity": "sha512-dEOsK5ngosvrne66QiI3D3nsvTesIMhiiH0tYC5sISAFFzvZza0PFxWWanNcoBX90McFTRsebVkR0ApXxtkGqA==", + "dependencies": { + "escape-string-regexp": "^1.0.5", + "object-assign": "^4.1.0" + } + }, + "node_modules/assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/async-limiter": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz", + "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==", + "engines": { + "node": "*" + } + }, + "node_modules/aws4": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.12.0.tgz", + "integrity": "sha512-NmWvPnx0F1SfrQbYwOi7OeaNGokp9XhzNioJ/CSBs8Qa4vxug81mhJEAVZwxXuBmYB5KDRfMq/F3RR0BIU7sWg==" + }, + "node_modules/axios": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz", + "integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==", + "deprecated": "Critical security vulnerability fixed in v0.21.1. For more information, see https://github.com/axios/axios/pull/3410", + "dependencies": { + "follow-redirects": "1.5.10" + } + }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, + "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.20.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", + "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + + } + + }, + + "node_modules/bson": { + + "version": "5.0.0", + + "resolved": "https://registry.npmjs.org/bson/-/bson-5.0.0.tgz", + + "integrity": "sha512-EL2KpZdyhshyyptj6pnQfnFKPoncD9KwZYvgmj/FXQiOUU1HWTHWmBOP4TZXU3YzStcI5qgpIl68YnMo16s26A==", + + "engines": { + + "node": ">=14.20.1" + } + }, + "node_modules/byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/byte-length/-/byte-length-1.0.2.tgz", + "integrity": "sha512-ovBpjmsgd/teRmgcPh23d4gJvxDoXtAzEL9xTfMU8Yc2kqCDb7L9jAG0XHl1nzuGl+h3ebCIF1i62UFyA9V/2Q==" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==" + }, + "node_modules/client-oauth2": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/client-oauth2/-/client-oauth2-4.3.3.tgz", + "integrity": "sha512-k8AvUYJon0vv75ufoVo4nALYb/qwFFicO3I0+39C6xEdflqVtr+f9cy+0ZxAduoVSTfhP5DX2tY2XICAd5hy6Q==", + "dependencies": { + "popsicle": "^12.0.5", + "safe-buffer": "^5.2.0" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, + "node_modules/cross-fetch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", + "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", + "dependencies": { + "node-fetch": "2.6.7" + } + }, + "node_modules/cross-fetch/node_modules/node-fetch": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==", + "dependencies": { + "assert-plus": "^1.0.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/deep-eql": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-0.1.3.tgz", + "integrity": "sha512-6sEotTRGBFiNcqVoeHwnfopbSpi5NbH1VWJmYCVkmxMmaVTT0bUTrNaGyBwhgP4MZL012W/mkzIn3Da+iDYweg==", + "dependencies": { + "type-detect": "0.1.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.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": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==", + "dependencies": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.18.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", + "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.1", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.5.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "node_modules/extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==", + "engines": [ + "node >=0.6.0" + ] + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/follow-redirects": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", + "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", + "dependencies": { + "debug": "=3.1.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/follow-redirects/node_modules/debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==", + "engines": { + "node": "*" + } + }, + "node_modules/form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/get-intrinsic": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.3.tgz", + "integrity": "sha512-QJVz1Tj7MS099PevUG5jvnt9tSkXN8K14dxQlikJuPt4uD9hHAHjLyLBiLR5zELelBdD9QNRAXZzsJx0WaDL9A==", + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==", + "dependencies": { + "assert-plus": "^1.0.0" + } + }, + "node_modules/har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==", + "engines": { + "node": ">=4" + } + }, + "node_modules/har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "deprecated": "this library is no longer supported", + "dependencies": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==", + "dependencies": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + }, + "engines": { + "node": ">=0.8", + "npm": ">=1.3.7" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + + }, + + "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/ip-regex": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", + "integrity": "sha512-58yWmlHpp7VYfcdTwMTvwMmqx/Elfxjd9RXTDyMsbL7lLWmhMylLEqiYVLKuLzOZqVgiWXD9MfR62Vv89VRxkw==", + "engines": { + "node": ">=4" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==" + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==" + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + }, + "node_modules/iso8601-duration": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/iso8601-duration/-/iso8601-duration-1.3.0.tgz", + "integrity": "sha512-K4CiUBzo3YeWk76FuET/dQPH03WE04R94feo5TSKQCXpoXQt9E4yx2CnY737QZnSAI3PI4WlKo/zfqizGx52QQ==" + }, + "node_modules/isomorphic-ws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-4.0.1.tgz", + "integrity": "sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w==", + "peerDependencies": { + "ws": "*" + } + }, + "node_modules/isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==" + }, + "node_modules/jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==" + }, + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==" + }, + "node_modules/jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", + "dependencies": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/keypather": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/keypather/-/keypather-3.1.0.tgz", + "integrity": "sha512-DsxfrBVXlQihWmefW/lNvVgtzFoSoDd67mCsop7a+tK9h7ybpBF5YRUXg192GBmOc3gn4IEv3AV69HElXYuCLA==", + "dependencies": { + "101": "^1.6.2", + "debug": "^3.1.0", + "escape-string-regexp": "^1.0.5", + "shallow-clone": "^3.0.0", + "string-reduce": "^1.0.0" + } + }, + "node_modules/keypather/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/keypather/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" + }, + "node_modules/make-error-cause": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/make-error-cause/-/make-error-cause-2.3.0.tgz", + "integrity": "sha512-etgt+n4LlOkGSJbBTV9VROHA5R7ekIPS4vfh+bCAoJgRrJWdqJCBbpS3osRJ/HrT7R68MzMiY3L3sDJ/Fd8aBg==", + "dependencies": { + "make-error": "^1.3.5" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "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", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + + "node_modules/mongodb": { + + "version": "5.0.1", + + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.0.1.tgz", + + "integrity": "sha512-KpjtY+NWFmcic6UDYEdfn768ZTuKyv7CRaui7ZSd6q/0/o1AURMC7KygTUwB1Cl8V10Pe5NiP+Y2eBMCDs/ygQ==", + + "dependencies": { + + "bson": "^5.0.0", + + "mongodb-connection-string-url": "^2.6.0", + + "socks": "^2.7.1" + + }, + + "engines": { + + "node": ">=14.20.1" + + }, + + "optionalDependencies": { + + "saslprep": "^1.0.3" + + }, + + "peerDependencies": { + + "@aws-sdk/credential-providers": "^3.201.0", + + "mongodb-client-encryption": "^2.3.0", + + "snappy": "^7.2.2" + + }, + + "peerDependenciesMeta": { + + "@aws-sdk/credential-providers": { + + "optional": true + + }, + + "mongodb-client-encryption": { + + "optional": true + + }, + + "snappy": { + + "optional": true + + } + + } + + }, + + "node_modules/mongodb-connection-string-url": { + + "version": "2.6.0", + + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", + + "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + + "dependencies": { + + "@types/whatwg-url": "^8.2.1", + + "whatwg-url": "^11.0.0" + + } + + }, + + "node_modules/mongodb-connection-string-url/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/mongodb-connection-string-url/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/mongodb-connection-string-url/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/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "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/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/mysql2": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-2.3.3.tgz", + "integrity": "sha512-wxJUev6LgMSgACDkb/InIFxDprRa6T95+VEoR+xPvtngtccNH2dGjEB/fVZ8yg1gWv1510c9CvXuJHi5zUm0ZA==", + "dependencies": { + "denque": "^2.0.1", + "generate-function": "^2.3.1", + "iconv-lite": "^0.6.3", + "long": "^4.0.0", + "lru-cache": "^6.0.0", + "named-placeholders": "^1.1.2", + "seq-queue": "^0.0.5", + "sqlstring": "^2.3.2" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/mysql2/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/mysql2/node_modules/sqlstring": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz", + "integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.2.tgz", + "integrity": "sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA==", + "dependencies": { + "lru-cache": "^4.1.3" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/named-placeholders/node_modules/lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dependencies": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "node_modules/named-placeholders/node_modules/yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha512-ncTzHV7NvsQZkYe1DW7cbDLm0YpzHmZF5r/iyP3ZnQtMiJ+pjzisCiMNI+Sj+xQF5pXhSHxSB3uDbsBTzY/c2A==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.0.tgz", + "integrity": "sha512-BKwRP/O0UvoMKp7GNdwPlObhYGB5DQqwhEDQlNKuoqwVYSxkSZCSbHjnFFmUEtwSKRPU4kNK8PbDYYitwaE3QA==", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "engines": { + "node": "*" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.2.tgz", + "integrity": "sha512-z+cPxW0QGUp0mcqcsgQyLVRDoXFQbXOwBaqyF7VIgI4TWNQsDHrBpUQslRmIfAoYWdYzs6UlKJtB2XJpTaNSpQ==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/op-client": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/op-client/-/op-client-1.4.2.tgz", + "integrity": "sha512-IgOMyXLHzqVvQM6YZ0qpP7d3UXO2kQPukZAMEh/2b3iC73XNcSMFo9TTXSWpJYYZaBhKvkLhDI39UdJj9+Z/Xg==", + "dependencies": { + "client-oauth2": "^4.3.3", + "cross-fetch": "^3.0.5", + "iso8601-duration": "^1.2.0", + "keypather": "^3.1.0", + "reflect-metadata": "^0.1.10" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + }, + "node_modules/performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==" + }, + "node_modules/popsicle": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/popsicle/-/popsicle-12.1.0.tgz", + "integrity": "sha512-muNC/cIrWhfR6HqqhHazkxjob3eyECBe8uZYSQ/N5vixNAgssacVleerXnE8Are5fspR0a+d2qWaBR1g7RYlmw==", + "dependencies": { + "popsicle-content-encoding": "^1.0.0", + "popsicle-cookie-jar": "^1.0.0", + "popsicle-redirects": "^1.1.0", + "popsicle-transport-http": "^1.0.8", + "popsicle-transport-xhr": "^2.0.0", + "popsicle-user-agent": "^1.0.0", + "servie": "^4.3.3", + "throwback": "^4.1.0" + } + }, + "node_modules/popsicle-content-encoding": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-content-encoding/-/popsicle-content-encoding-1.0.0.tgz", + "integrity": "sha512-4Df+vTfM8wCCJVTzPujiI6eOl3SiWQkcZg0AMrOkD1enMXsF3glIkFUZGvour1Sj7jOWCsNSEhBxpbbhclHhzw==", + "peerDependencies": { + "servie": "^4.0.0" + } + }, + "node_modules/popsicle-cookie-jar": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-cookie-jar/-/popsicle-cookie-jar-1.0.0.tgz", + "integrity": "sha512-vrlOGvNVELko0+J8NpGC5lHWDGrk8LQJq9nwAMIVEVBfN1Lib3BLxAaLRGDTuUnvl45j5N9dT2H85PULz6IjjQ==", + "dependencies": { + "@types/tough-cookie": "^2.3.5", + "tough-cookie": "^3.0.1" + }, + "peerDependencies": { + "servie": "^4.0.0" + } + }, + "node_modules/popsicle-redirects": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/popsicle-redirects/-/popsicle-redirects-1.1.1.tgz", + "integrity": "sha512-mC2HrKjdTAWDalOjGxlXw9j6Qxrz/Yd2ui6bPxpi2IQDYWpF4gUAMxbA8EpSWJhLi0PuWKDwTHHPrUPGutAoIA==", + "peerDependencies": { + "servie": "^4.1.0" + } + }, + "node_modules/popsicle-transport-http": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/popsicle-transport-http/-/popsicle-transport-http-1.2.1.tgz", + "integrity": "sha512-i5r3IGHkGiBDm1oPFvOfEeSGWR0lQJcsdTqwvvDjXqcTHYJJi4iSi3ecXIttDiTBoBtRAFAE9nF91fspQr63FQ==", + "dependencies": { + "make-error-cause": "^2.2.0" + }, + "peerDependencies": { + "servie": "^4.2.0" + } + }, + "node_modules/popsicle-transport-xhr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/popsicle-transport-xhr/-/popsicle-transport-xhr-2.0.0.tgz", + "integrity": "sha512-5Sbud4Widngf1dodJE5cjEYXkzEUIl8CzyYRYR57t6vpy9a9KPGQX6KBKdPjmBZlR5A06pOBXuJnVr23l27rtA==", + "peerDependencies": { + "servie": "^4.2.0" + } + }, + "node_modules/popsicle-user-agent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-user-agent/-/popsicle-user-agent-1.0.0.tgz", + "integrity": "sha512-epKaq3TTfTzXcxBxjpoKYMcTTcAX8Rykus6QZu77XNhJuRHSRxMd+JJrbX/3PFI0opFGSN0BabbAYCbGxbu0mA==", + "peerDependencies": { + "servie": "^4.0.0" + } + }, + "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/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha512-b/YwNhb8lk1Zz2+bXXpS/LK9OisiZZ1SNsSLxN1x2OXVEhW2Ckr/7mWE5vrC1ZTiJlD9g19jWszTmJsB+oEpFQ==" + }, + "node_modules/psl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", + "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==" + }, + "node_modules/punycode": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.2.0.tgz", + "integrity": "sha512-LN6QV1IJ9ZhxWTNdktaPClrNfp8xdSAYS0Zk2ddX7XsXZAxckMHPCBcHRo0cTcEIgYPRiGEkmji3Idkh2yFtYw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "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/readable-stream/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/reflect-metadata": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", + "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==" + }, + "node_modules/request": { + "version": "2.88.2", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", + "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142", + "dependencies": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/request/node_modules/qs": { + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/request/node_modules/tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dependencies": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "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/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + + "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.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/seq-queue": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", + "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==" + }, + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/servie": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/servie/-/servie-4.3.3.tgz", + "integrity": "sha512-b0IrY3b1gVMsWvJppCf19g1p3JSnS0hQi6xu4Hi40CIhf0Lx8pQHcvBL+xunShpmOiQzg1NOia812NAWdSaShw==", + "dependencies": { + "@servie/events": "^1.0.0", + "byte-length": "^1.0.2", + "ts-expect": "^1.1.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/shallow-clone": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" - } - }, + + } + + }, + + "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.1", + + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", + + "integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", + + "dependencies": { + + "ip": "^2.0.0", + + "smart-buffer": "^4.2.0" + + }, + + "engines": { + + "node": ">= 10.13.0", + + "npm": ">= 3.0.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/sshpk": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz", + "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", + "dependencies": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + }, + "bin": { + "sshpk-conv": "bin/sshpk-conv", + "sshpk-sign": "bin/sshpk-sign", + "sshpk-verify": "bin/sshpk-verify" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "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/string_decoder/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/string-reduce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string-reduce/-/string-reduce-1.0.0.tgz", + "integrity": "sha512-Sc7/l7xG8TvJrC1+LNowFgAyW0jerj73NHPJo66ijTQCbveJ2TRHoq+mACTLzlFTO7V30ESzb23qTU6wB0VNCQ==", + "dependencies": { + "assert-err": "^1.1.0" + } + }, + "node_modules/throwback": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/throwback/-/throwback-4.1.0.tgz", + "integrity": "sha512-dLFe8bU8SeH0xeqeKL7BNo8XoPC/o91nz9/ooeplZPiso+DZukhoyZcSz9TFnUNScm+cA9qjU1m1853M6sPOng==" + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tough-cookie": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-3.0.1.tgz", + "integrity": "sha512-yQyJ0u4pZsv9D4clxO69OEjLWYw+jbgspjTue4lTQZLfV0c5l1VmK2y1JK8E9ahdpltPOaAThPcp5nKPUgSnsg==", + "dependencies": { + "ip-regex": "^2.1.0", + "psl": "^1.1.28", + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/ts-expect": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/ts-expect/-/ts-expect-1.3.0.tgz", + "integrity": "sha512-e4g0EJtAjk64xgnFPD6kTBUtpnMVzDrMb12N1YZV0VvSlhnVT3SGxiYTLdGy8Q5cYHOIC/FAHmZ10eGrAguicQ==" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==" + }, + "node_modules/type-detect": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-0.1.1.tgz", + "integrity": "sha512-5rqszGVwYgBoDkIm2oUtvkfZMQ0vk29iDMU0W2qCa3rG0vPDNczCMT4hV/bLBgLg8k8ri6+u3Zbt+S/14eMzlA==", + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", + "bin": { + "uuid": "bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==", + "engines": [ + "node >=0.6.0" + ], + "dependencies": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "node_modules/verror/node_modules/core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" + }, + "node_modules/web-streams-polyfill": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/ws": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-6.2.2.tgz", + "integrity": "sha512-zmhltoSR8u1cnDsD43TX59mzoMZsLKqUweyYBAIvTngR3shc0W6aOZylZmq/7hqyVxPdi+5Ud2QInblgyE72fw==", + "dependencies": { + "async-limiter": "~1.0.0" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + } + } + } + diff --git a/2_PAC/node_modules/@types/node/LICENSE b/2_PAC/node_modules/@types/node/LICENSE new file mode 100644 index 00000000..9e841e7a --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/README.md b/2_PAC/node_modules/@types/node/README.md new file mode 100644 index 00000000..ae3cd63b --- /dev/null +++ b/2_PAC/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: Tue, 07 Feb 2023 08:32:36 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), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky). diff --git a/2_PAC/node_modules/@types/node/assert.d.ts b/2_PAC/node_modules/@types/node/assert.d.ts new file mode 100644 index 00000000..e8595e63 --- /dev/null +++ b/2_PAC/node_modules/@types/node/assert.d.ts @@ -0,0 +1,961 @@ +/** + * 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; + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: this, arguments: [1, 2, 3 ] }]); + * ``` + * + * @since v18.8.0, v16.18.0 + * @params fn + * @returns An Array with the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * 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[]; + /** + * Reset calls of the call tracker. + * If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * tracker.getCalls(callsfunc).length === 1; + * + * tracker.reset(callsfunc); + * tracker.getCalls(callsfunc).length === 0; + * ``` + * + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * 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 CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + 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/2_PAC/node_modules/@types/node/assert/strict.d.ts b/2_PAC/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 00000000..b4319b97 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/async_hooks.d.ts b/2_PAC/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 00000000..96908bed --- /dev/null +++ b/2_PAC/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,513 @@ +/** + * 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; + } + interface AsyncLocalStorageOptions { + /** + * Optional callback invoked before a store is propagated to a new async resource. + * Returning `true` allows propagation, returning `false` avoids it. Default is to propagate always. + * @param type The type of async event. + * @param store The current store. + * @since v18.13.0 + */ + onPropagate?: ((type: string, store: T) => boolean) | undefined; + } + /** + * 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 { + constructor(options?: AsyncLocalStorageOptions); + + /** + * 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/2_PAC/node_modules/@types/node/buffer.d.ts b/2_PAC/node_modules/@types/node/buffer.d.ts new file mode 100644 index 00000000..5ec326d0 --- /dev/null +++ b/2_PAC/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2258 @@ +/** + * `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'; + import { ReadableStream as WebReadableStream } from 'node:stream/web'; + 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 (WHATWG) `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + + import { Blob as NodeBlob } from 'buffer'; + // This conditional type will be the existing global Blob in a browser, or + // the copy below in a Node environment. + type __Blob = typeof globalThis extends { onmessage: any, Blob: infer T } + ? T : NodeBlob; + 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; + + interface Blob extends __Blob {} + /** + * `Blob` class is a global reference for `require('node:buffer').Blob` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { + onmessage: any; + Blob: infer T; + } + ? T + : typeof NodeBlob; + } +} +declare module 'node:buffer' { + export * from 'buffer'; +} diff --git a/2_PAC/node_modules/@types/node/child_process.d.ts b/2_PAC/node_modules/@types/node/child_process.d.ts new file mode 100644 index 00000000..c537d6d6 --- /dev/null +++ b/2_PAC/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 false + */ + 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/2_PAC/node_modules/@types/node/cluster.d.ts b/2_PAC/node_modules/@types/node/cluster.d.ts new file mode 100644 index 00000000..37dbc574 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/console.d.ts b/2_PAC/node_modules/@types/node/console.d.ts new file mode 100644 index 00000000..16c9137a --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/constants.d.ts b/2_PAC/node_modules/@types/node/constants.d.ts new file mode 100644 index 00000000..208020dc --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/crypto.d.ts b/2_PAC/node_modules/@types/node/crypto.d.ts new file mode 100644 index 00000000..20d960cd --- /dev/null +++ b/2_PAC/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; + } + /** + * 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): DiffieHellman; + function createDiffieHellman(prime: ArrayBuffer | NodeJS.ArrayBufferView, generator?: number | ArrayBuffer | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: ArrayBuffer | NodeJS.ArrayBufferView, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator?: number | ArrayBuffer | 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 2^48. `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(encoding?: null, format?: ECDHKeyFormat): 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' | 'jwk'; + 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' | 'default' | '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 when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * 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: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise; + deriveBits(algorithm: AlgorithmIdentifier | 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/2_PAC/node_modules/@types/node/dgram.d.ts b/2_PAC/node_modules/@types/node/dgram.d.ts new file mode 100644 index 00000000..247328d2 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/diagnostics_channel.d.ts b/2_PAC/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 00000000..3dcaa035 --- /dev/null +++ b/2_PAC/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 | symbol): 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 | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => 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 | symbol; + /** + * 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 | symbol); + /** + * 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/2_PAC/node_modules/@types/node/dns.d.ts b/2_PAC/node_modules/@types/node/dns.d.ts new file mode 100644 index 00000000..305367b8 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/dns/promises.d.ts b/2_PAC/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 00000000..77cd807b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/dom-events.d.ts b/2_PAC/node_modules/@types/node/dom-events.d.ts new file mode 100644 index 00000000..b9c1c3aa --- /dev/null +++ b/2_PAC/node_modules/@types/node/dom-events.d.ts @@ -0,0 +1,126 @@ +export {}; // Don't export anything! + +//// DOM-like Events +// NB: The Event / EventTarget / EventListener implementations below were copied +// from lib.dom.d.ts, then edited to reflect Node's documentation at +// https://nodejs.org/api/events.html#class-eventtarget. +// Please read that link to understand important implementation differences. + +// This conditional type will be the existing global Event in a browser, or +// the copy below in a Node environment. +type __Event = typeof globalThis extends { onmessage: any, Event: any } +? {} +: { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?] + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; +}; + +// See comment above explaining conditional type +type __EventTarget = typeof globalThis extends { onmessage: any, EventTarget: any } +? {} +: { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; +}; + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +import {} from 'events'; // Make this an ambient declaration +declare global { + /** An event which takes place in the DOM. */ + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any, Event: infer T } + ? T + : { + prototype: __Event; + new (type: string, eventInitDict?: EventInit): __Event; + }; + + /** + * EventTarget is a DOM interface implemented by objects that can + * receive events and may have listeners for them. + */ + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any, EventTarget: infer T } + ? T + : { + prototype: __EventTarget; + new (): __EventTarget; + }; +} diff --git a/2_PAC/node_modules/@types/node/domain.d.ts b/2_PAC/node_modules/@types/node/domain.d.ts new file mode 100644 index 00000000..fafe68a5 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/events.d.ts b/2_PAC/node_modules/@types/node/events.d.ts new file mode 100644 index 00000000..4633df19 --- /dev/null +++ b/2_PAC/node_modules/@types/node/events.d.ts @@ -0,0 +1,678 @@ +/** + * 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' { + // NOTE: This class is in the docs but is **not actually exported** by Node. + // If https://github.com/nodejs/node/issues/39903 gets resolved and Node + // actually starts exporting the class, uncomment below. + + // import { EventListener, EventListenerObject } from '__dom-events'; + // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ + // interface NodeEventTarget extends EventTarget { + // /** + // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. + // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. + // */ + // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ + // eventNames(): string[]; + // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ + // listenerCount(type: string): number; + // /** Node.js-specific alias for `eventTarget.removeListener()`. */ + // off(type: string, listener: EventListener | EventListenerObject): this; + // /** Node.js-specific alias for `eventTarget.addListener()`. */ + // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ + // once(type: string, listener: EventListener | EventListenerObject): this; + // /** + // * Node.js-specific extension to the `EventTarget` class. + // * If `type` is specified, removes all registered listeners for `type`, + // * otherwise removes all registered listeners. + // */ + // removeAllListeners(type: string): this; + // /** + // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. + // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. + // */ + // removeListener(type: string, listener: EventListener | EventListenerObject): this; + // } + + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + // Any EventTarget with a Node-style `once` function + interface _NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + // Any EventTarget with a DOM-style `addEventListener` + 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<_DOMEventTarget | NodeJS.EventEmitter>): 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/2_PAC/node_modules/@types/node/fs.d.ts b/2_PAC/node_modules/@types/node/fs.d.ts new file mode 100644 index 00000000..75c53fb0 --- /dev/null +++ b/2_PAC/node_modules/@types/node/fs.d.ts @@ -0,0 +1,3872 @@ +/** + * 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, 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; + } + /** + * 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; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: 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; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): 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?: CopySyncOptions): void; +} +declare module 'node:fs' { + export * from 'fs'; +} diff --git a/2_PAC/node_modules/@types/node/fs/promises.d.ts b/2_PAC/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 00000000..aca2fd51 --- /dev/null +++ b/2_PAC/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1138 @@ +/** + * 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 { + BigIntStats, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatOptions, + Stats, + TimeLike, + WatchEventType, + WatchOptions, + WriteStream, + WriteVResult, + } from 'node:fs'; + import { Interface as ReadlineInterface } from 'node:readline'; + + 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; + /** + * Convenience method to create a `readline` interface and stream over the file. For example: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * + * @since v18.11.0 + * @param options See `filehandle.createReadStream()` for the options. + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @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: TimeLike, mtime: TimeLike): 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; + } + + const constants: typeof fsConstants; + + /** + * 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: TimeLike, mtime: TimeLike): 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: TimeLike, mtime: TimeLike): 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/2_PAC/node_modules/@types/node/globals.d.ts b/2_PAC/node_modules/@types/node/globals.d.ts new file mode 100644 index 00000000..80fd4cf3 --- /dev/null +++ b/2_PAC/node_modules/@types/node/globals.d.ts @@ -0,0 +1,300 @@ +// 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 extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; +} + +declare var AbortController: typeof globalThis extends {onmessage: any; AbortController: infer T} + ? T + : { + prototype: AbortController; + new(): AbortController; + }; + +declare var AbortSignal: typeof globalThis extends {onmessage: any; AbortSignal: infer T} + ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; +//#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 ReadonlyArray 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/2_PAC/node_modules/@types/node/globals.global.d.ts b/2_PAC/node_modules/@types/node/globals.global.d.ts new file mode 100644 index 00000000..ef1198c0 --- /dev/null +++ b/2_PAC/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/2_PAC/node_modules/@types/node/http.d.ts b/2_PAC/node_modules/@types/node/http.d.ts new file mode 100644 index 00000000..e14de6cf --- /dev/null +++ b/2_PAC/node_modules/@types/node/http.d.ts @@ -0,0 +1,1651 @@ +/** + * 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'; + import { LookupOptions } from 'node:dns'; + // 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 { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: + | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | undefined; + hints?: LookupOptions['hints']; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * 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. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: 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; + /** + * 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 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > 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: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: 'request', listener: RequestListener): this; + addListener( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: 'checkExpectation', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; + emit(event: 'connect', req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit( + event: 'request', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'upgrade', req: InstanceType, 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: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: InstanceType, 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: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: 'request', listener: RequestListener): this; + once( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener( + event: 'upgrade', + listener: (req: InstanceType, 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: Request; + 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: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an 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 an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * Example: + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics' + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks + * }, earlyHintsCallback); + * ``` + * + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, 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 an 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< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >( + 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; + + /** + * Performs the low-level validations on the provided name that are done when `res.setHeader(name, value)` is called. + * Passing illegal value as name will result in a TypeError being thrown, identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * @param name Header name + * @since v14.3.0 + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided value that are done when `res.setHeader(name, value)` is called. + * Passing illegal value as value will result in a TypeError being thrown. + * - Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * - Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * @param name Header name + * @param value Header value + * @since v14.3.0 + */ + function validateHeaderValue(name: string, value: string): void; + + /** + * Set the maximum number of idle HTTP parsers. Default: 1000. + * @param count + * @since v18.8.0, v16.18.0 + */ + function setMaxIdleHTTPParsers(count: number): void; + + 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/2_PAC/node_modules/@types/node/http2.d.ts b/2_PAC/node_modules/@types/node/http2.d.ts new file mode 100644 index 00000000..0e368260 --- /dev/null +++ b/2_PAC/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2134 @@ +/** + * 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, callback?: (err: Error | null, settings: Settings, duration: number) => void): 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 status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * Example: + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics' + * }); + * ``` + * + * @since v18.11.0 + * @param hints An object containing the values of headers + */ + writeEarlyHints(hints: Record): 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/2_PAC/node_modules/@types/node/https.d.ts b/2_PAC/node_modules/@types/node/https.d.ts new file mode 100644 index 00000000..bda367d7 --- /dev/null +++ b/2_PAC/node_modules/@types/node/https.d.ts @@ -0,0 +1,542 @@ +/** + * 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< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = http.RequestOptions & + tls.SecureContextOptions & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; + 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< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > 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: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: 'checkExpectation', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'clientError', err: Error, socket: Duplex): boolean; + emit(event: 'connect', req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: 'request', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'upgrade', req: InstanceType, 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: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: InstanceType, 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: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: InstanceType, 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: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener( + event: 'upgrade', + listener: (req: InstanceType, 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< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + 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/2_PAC/node_modules/@types/node/index.d.ts b/2_PAC/node_modules/@types/node/index.d.ts new file mode 100644 index 00000000..f184a18f --- /dev/null +++ b/2_PAC/node_modules/@types/node/index.d.ts @@ -0,0 +1,134 @@ +// Type definitions for non-npm package Node.js 18.13 +// 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 +// Dmitry Semigradsky +// 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 4.9+. + +// 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/2_PAC/node_modules/@types/node/inspector.d.ts b/2_PAC/node_modules/@types/node/inspector.d.ts new file mode 100644 index 00000000..eba0b55d --- /dev/null +++ b/2_PAC/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2741 @@ +// eslint-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/2_PAC/node_modules/@types/node/module.d.ts b/2_PAC/node_modules/@types/node/module.d.ts new file mode 100644 index 00000000..5a60a5fa --- /dev/null +++ b/2_PAC/node_modules/@types/node/module.d.ts @@ -0,0 +1,115 @@ +/** + * @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 isBuiltin(moduleName: string): boolean; + 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/2_PAC/node_modules/@types/node/net.d.ts b/2_PAC/node_modules/@types/node/net.d.ts new file mode 100644 index 00000000..056407c8 --- /dev/null +++ b/2_PAC/node_modules/@types/node/net.d.ts @@ -0,0 +1,877 @@ +/** + * > 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; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | 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; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet + * and destroy this TCP socket once it is connected. Otherwise, it will call + * `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. If this is not a TCP socket + * (for example, a pipe), calling this method will immediately throw + * an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0 + * @return The socket itself. + */ + resetAndDestroy(): 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; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0 + */ + readonly localFamily?: string; + /** + * 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. ready + * 9. 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; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * 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 + * 5. drop + */ + 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: 'drop', listener: (data?: DropArgument) => 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; + emit(event: 'drop', data?: DropArgument): 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: 'drop', listener: (data?: DropArgument) => 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: 'drop', listener: (data?: DropArgument) => 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: 'drop', listener: (data?: DropArgument) => 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: 'drop', listener: (data?: DropArgument) => 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); + /** + * @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/2_PAC/node_modules/@types/node/os.d.ts b/2_PAC/node_modules/@types/node/os.d.ts new file mode 100644 index 00000000..3c555992 --- /dev/null +++ b/2_PAC/node_modules/@types/node/os.d.ts @@ -0,0 +1,466 @@ +/** + * 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'; + scopeid?: undefined; + } + 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 machine type as a string, such as arm, aarch64, mips, mips64, ppc64, ppc64le, s390, s390x, i386, i686, x86_64. + * + * On POSIX systems, the machine type 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 v18.9.0 + */ + function machine(): string; + /** + * 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/2_PAC/node_modules/@types/node/package.json b/2_PAC/node_modules/@types/node/package.json new file mode 100644 index 00000000..4339ed35 --- /dev/null +++ b/2_PAC/node_modules/@types/node/package.json @@ -0,0 +1,237 @@ +{ + "name": "@types/node", + "version": "18.13.0", + "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" + }, + { + "name": "Dmitry Semigradsky", + "url": "https://github.com/Semigradsky", + "githubUsername": "Semigradsky" + } + ], + "main": "", + "types": "index.d.ts", + "typesVersions": { + "<=4.8": { + "*": [ + "ts4.8/*" + ] + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "6c5087993475c3d03552602e518e6747e3493f7e7dec65e81e1f206b013ad890", + "typeScriptVersion": "4.2" +} \ No newline at end of file diff --git a/2_PAC/node_modules/@types/node/path.d.ts b/2_PAC/node_modules/@types/node/path.d.ts new file mode 100644 index 00000000..1d33f792 --- /dev/null +++ b/2_PAC/node_modules/@types/node/path.d.ts @@ -0,0 +1,191 @@ +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 path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + 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 paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * 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. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: 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 path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: 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 path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: '\\' | '/'; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ';' | ':'; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: 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/2_PAC/node_modules/@types/node/perf_hooks.d.ts b/2_PAC/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 00000000..5c0b228e --- /dev/null +++ b/2_PAC/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,625 @@ +/** + * 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. + toJSON(): any; + } + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: 'mark'; + } + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: 'measure'; + } + /** + * _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; + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only the named measure. + * @param name + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.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`. + * @param name + * @param type + * @since v16.7.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`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * 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 + * @return The PerformanceMark entry that was created + */ + mark(name?: string, options?: MarkOptions): PerformanceMark; + /** + * 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 + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * 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; + + import { performance as _performance } from 'perf_hooks'; + global { + /** + * `performance` is a global reference for `require('perf_hooks').performance` + * https://nodejs.org/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } + ? T + : typeof _performance; + } +} +declare module 'node:perf_hooks' { + export * from 'perf_hooks'; +} diff --git a/2_PAC/node_modules/@types/node/process.d.ts b/2_PAC/node_modules/@types/node/process.d.ts new file mode 100644 index 00000000..12148f91 --- /dev/null +++ b/2_PAC/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 that 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/2_PAC/node_modules/@types/node/punycode.d.ts b/2_PAC/node_modules/@types/node/punycode.d.ts new file mode 100644 index 00000000..87ebbb90 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/querystring.d.ts b/2_PAC/node_modules/@types/node/querystring.d.ts new file mode 100644 index 00000000..e1185478 --- /dev/null +++ b/2_PAC/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'); + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical + * or when compatibility with browser code is desirable. + * @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/2_PAC/node_modules/@types/node/readline.d.ts b/2_PAC/node_modules/@types/node/readline.d.ts new file mode 100644 index 00000000..6ab64acb --- /dev/null +++ b/2_PAC/node_modules/@types/node/readline.d.ts @@ -0,0 +1,653 @@ +/** + * 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'; + import * as promises from 'node:readline/promises'; + + export { promises }; + export 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 + */ + export 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; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; + export type CompleterResult = [string[], string]; + export 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 + */ + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + export 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 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export 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`. + */ + export 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`. + */ + export 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`. + */ + export 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`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module 'node:readline' { + export * from 'readline'; +} diff --git a/2_PAC/node_modules/@types/node/readline/promises.d.ts b/2_PAC/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 00000000..8f9f06f0 --- /dev/null +++ b/2_PAC/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,143 @@ +/** + * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. + * + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) + * @since v17.0.0 + */ +declare module 'readline/promises' { + import { Interface as _Interface, ReadLineOptions, Completer, AsyncCompleter, Direction } from 'node:readline'; + import { Abortable } from 'node:events'; + + class Interface extends _Interface { + /** + * 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 readlinePromises.Interface was created with output set to null or undefined the query is not written. + * + * If the question is called after rl.close(), it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an AbortSignal to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * @since v17.0.0 + * @param query A statement or query to write to output, prepended to the prompt. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + + class Readline { + /** + * @param stream A TTY stream. + */ + constructor(stream: NodeJS.WritableStream, options?: { autoCommit?: boolean }); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an action that clears current line of the associated `stream` in a specified direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an action that clears the associated `stream` from the current position of the cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an action that moves the cursor relative to its current position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless autoCommit: true was passed to the constructor. + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. + */ + rollback(): this; + } + + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readlinePromises.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). + * + * ## Use of the `completer` function + * + * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: + * + * - An Array with matching entries for the completion. + * - The substring that was used for the matching. + * + * For instance: `[[substr1, substr2, ...], originalsubstring]`. + * + * ```js + * function completer(line) { + * const completions = '.help .error .exit .quit .q'.split(' '); + * const hits = completions.filter((c) => c.startsWith(line)); + * // Show all completions if none found + * return [hits.length ? hits : completions, line]; + * } + * ``` + * + * The `completer` function can also returns a `Promise`, or be asynchronous: + * + * ```js + * async function completer(linePartial) { + * await someAsyncWork(); + * return [['123'], linePartial]; + * } + * ``` + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module 'node:readline/promises' { + export * from 'readline/promises'; +} diff --git a/2_PAC/node_modules/@types/node/repl.d.ts b/2_PAC/node_modules/@types/node/repl.d.ts new file mode 100644 index 00000000..be42ccc4 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/stream.d.ts b/2_PAC/node_modules/@types/node/stream.d.ts new file mode 100644 index 00000000..711fd9ca --- /dev/null +++ b/2_PAC/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1340 @@ +/** + * 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 { Blob as NodeBlob } from "node:buffer"; + 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 v8.0.0 + */ + destroyed: boolean; + /** + * Is true after 'close' has been emitted. + * @since v18.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 v18.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 | NodeBlob | 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/2_PAC/node_modules/@types/node/stream/consumers.d.ts b/2_PAC/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 00000000..1ebf12e1 --- /dev/null +++ b/2_PAC/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module 'stream/consumers' { + import { Blob as NodeBlob } from "node:buffer"; + 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/2_PAC/node_modules/@types/node/stream/promises.d.ts b/2_PAC/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 00000000..b427073d --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/stream/web.d.ts b/2_PAC/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 00000000..f9ef0570 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/string_decoder.d.ts b/2_PAC/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 00000000..a5858041 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/test.d.ts b/2_PAC/node_modules/@types/node/test.d.ts new file mode 100644 index 00000000..58b8c453 --- /dev/null +++ b/2_PAC/node_modules/@types/node/test.d.ts @@ -0,0 +1,455 @@ +/** + * The `node:test` module provides a standalone testing module. + * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/test.js) + */ +declare module 'node:test' { + /** + * Programmatically start the test runner. + * @since v18.9.0 + * @param options Configuration options for running tests. + * @returns A {@link TapStream} that emits events about the test execution. + */ + function run(options?: RunOptions): TapStream; + + /** + * 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; + namespace describe { + // Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function skip(name?: string, fn?: SuiteFn): void; + function skip(options?: TestOptions, fn?: SuiteFn): void; + function skip(fn?: SuiteFn): void; + + // Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function todo(name?: string, fn?: SuiteFn): void; + function todo(options?: TestOptions, fn?: SuiteFn): void; + function todo(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; + namespace it { + // Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + function skip(name?: string, options?: TestOptions, fn?: ItFn): void; + function skip(name?: string, fn?: ItFn): void; + function skip(options?: TestOptions, fn?: ItFn): void; + function skip(fn?: ItFn): void; + + // Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. + function todo(name?: string, options?: TestOptions, fn?: ItFn): void; + function todo(name?: string, fn?: ItFn): void; + function todo(options?: TestOptions, fn?: ItFn): void; + function todo(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; + + interface RunOptions { + /** + * If a number is provided, then that many files would run in parallel. + * If truthy, it would run (number of cpu cores - 1) files in parallel. + * If falsy, it would only run one file at a time. + * If unspecified, subtests inherit this value from their parent. + * @default true + */ + concurrency?: number | boolean | undefined; + + /** + * An array containing the list of files to run. + * If unspecified, the test runner execution model will be used. + */ + files?: readonly string[] | undefined; + + /** + * Allows aborting an in-progress test execution. + * @default undefined + */ + signal?: AbortSignal | undefined; + + /** + * A number of milliseconds the test will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + } + + /** + * A successful call of the `run()` method will return a new `TapStream` object, + * streaming a [TAP](https://testanything.org/) output. + * `TapStream` will emit events in the order of the tests' definitions. + * @since v18.9.0 + */ + interface TapStream extends NodeJS.ReadableStream { + addListener(event: 'test:diagnostic', listener: (message: string) => void): this; + addListener(event: 'test:fail', listener: (data: TestFail) => void): this; + addListener(event: 'test:pass', listener: (data: TestPass) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: 'test:diagnostic', message: string): boolean; + emit(event: 'test:fail', data: TestFail): boolean; + emit(event: 'test:pass', data: TestPass): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'test:diagnostic', listener: (message: string) => void): this; + on(event: 'test:fail', listener: (data: TestFail) => void): this; + on(event: 'test:pass', listener: (data: TestPass) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: 'test:diagnostic', listener: (message: string) => void): this; + once(event: 'test:fail', listener: (data: TestFail) => void): this; + once(event: 'test:pass', listener: (data: TestPass) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'test:diagnostic', listener: (message: string) => void): this; + prependListener(event: 'test:fail', listener: (data: TestFail) => void): this; + prependListener(event: 'test:pass', listener: (data: TestPass) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'test:diagnostic', listener: (message: string) => void): this; + prependOnceListener(event: 'test:fail', listener: (data: TestFail) => void): this; + prependOnceListener(event: 'test:pass', listener: (data: TestPass) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + + interface TestFail { + /** + * The test duration. + */ + duration: number; + + /** + * The failure casing test to fail. + */ + error: Error; + + /** + * The test name. + */ + name: string; + + /** + * The ordinal number of the test. + */ + testNumber: number; + + /** + * Present if `context.todo` is called. + */ + todo?: string; + + /** + * Present if `context.skip` is called. + */ + skip?: string; + } + + interface TestPass { + /** + * The test duration. + */ + duration: number; + + /** + * The test name. + */ + name: string; + + /** + * The ordinal number of the test. + */ + testNumber: number; + + /** + * Present if `context.todo` is called. + */ + todo?: string; + + /** + * Present if `context.skip` is called. + */ + skip?: string; + } + + /** + * 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 create a hook running before each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach: typeof beforeEach; + + /** + * This function is used to create a hook that runs after the current test finishes. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach: typeof afterEach; + + /** + * 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; + + /** + * The name of the test. + * @since v18.8.0 + */ + readonly name: string; + + /** + * 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; + + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0 + */ + readonly signal: AbortSignal; + + /** + * 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 { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + + /** + * 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 | undefined; + + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + + /** + * 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 | undefined; + + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + + /** + * 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 | undefined; + } + + /** + * This function is used to create a hook running before running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function before(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function after(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running before each subtest of the current suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + + /** + * The hook function. If the hook uses callbacks, the callback function is passed as the + * second argument. + */ + type HookFn = (done: (result?: any) => void) => any; + + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + + export { test as default, run, test, describe, it, before, after, beforeEach, afterEach }; +} diff --git a/2_PAC/node_modules/@types/node/timers.d.ts b/2_PAC/node_modules/@types/node/timers.d.ts new file mode 100644 index 00000000..b26f3ced --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/timers/promises.d.ts b/2_PAC/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 00000000..c1450684 --- /dev/null +++ b/2_PAC/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,93 @@ +/** + * 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; + + interface Scheduler { + /** + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported. + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: TimerOptions) => Promise; + /** + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + + const scheduler: Scheduler; +} +declare module 'node:timers/promises' { + export * from 'timers/promises'; +} diff --git a/2_PAC/node_modules/@types/node/tls.d.ts b/2_PAC/node_modules/@types/node/tls.d.ts new file mode 100644 index 00000000..2c55eb93 --- /dev/null +++ b/2_PAC/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1107 @@ +/** + * 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 { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve,if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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/2_PAC/node_modules/@types/node/trace_events.d.ts b/2_PAC/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 00000000..d47aa931 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/@types/node/ts4.8/assert.d.ts b/2_PAC/node_modules/@types/node/ts4.8/assert.d.ts new file mode 100644 index 00000000..e8595e63 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/assert.d.ts @@ -0,0 +1,961 @@ +/** + * 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; + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: this, arguments: [1, 2, 3 ] }]); + * ``` + * + * @since v18.8.0, v16.18.0 + * @params fn + * @returns An Array with the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * 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[]; + /** + * Reset calls of the call tracker. + * If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * tracker.getCalls(callsfunc).length === 1; + * + * tracker.reset(callsfunc); + * tracker.getCalls(callsfunc).length === 0; + * ``` + * + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * 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 CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + 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/2_PAC/node_modules/@types/node/ts4.8/assert/strict.d.ts b/2_PAC/node_modules/@types/node/ts4.8/assert/strict.d.ts new file mode 100644 index 00000000..b4319b97 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/async_hooks.d.ts b/2_PAC/node_modules/@types/node/ts4.8/async_hooks.d.ts new file mode 100644 index 00000000..96908bed --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/async_hooks.d.ts @@ -0,0 +1,513 @@ +/** + * 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; + } + interface AsyncLocalStorageOptions { + /** + * Optional callback invoked before a store is propagated to a new async resource. + * Returning `true` allows propagation, returning `false` avoids it. Default is to propagate always. + * @param type The type of async event. + * @param store The current store. + * @since v18.13.0 + */ + onPropagate?: ((type: string, store: T) => boolean) | undefined; + } + /** + * 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 { + constructor(options?: AsyncLocalStorageOptions); + + /** + * 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/2_PAC/node_modules/@types/node/ts4.8/buffer.d.ts b/2_PAC/node_modules/@types/node/ts4.8/buffer.d.ts new file mode 100644 index 00000000..ea859cd2 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/buffer.d.ts @@ -0,0 +1,2259 @@ +/** + * `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'; + import { ReadableStream as WebReadableStream } from 'node:stream/web'; + 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 (WHATWG) `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + + import { Blob as NodeBlob } from 'buffer'; + // This conditional type will be the existing global Blob in a browser, or + // the copy below in a Node environment. + type __Blob = typeof globalThis extends { onmessage: any, Blob: any } + ? {} : NodeBlob; + + 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; + + interface Blob extends __Blob {} + /** + * `Blob` class is a global reference for `require('node:buffer').Blob` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { + onmessage: any; + Blob: infer T; + } + ? T + : typeof NodeBlob; + } +} +declare module 'node:buffer' { + export * from 'buffer'; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/child_process.d.ts b/2_PAC/node_modules/@types/node/ts4.8/child_process.d.ts new file mode 100644 index 00000000..c537d6d6 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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 false + */ + 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/2_PAC/node_modules/@types/node/ts4.8/cluster.d.ts b/2_PAC/node_modules/@types/node/ts4.8/cluster.d.ts new file mode 100644 index 00000000..37dbc574 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/console.d.ts b/2_PAC/node_modules/@types/node/ts4.8/console.d.ts new file mode 100644 index 00000000..16c9137a --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/constants.d.ts b/2_PAC/node_modules/@types/node/ts4.8/constants.d.ts new file mode 100644 index 00000000..208020dc --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/crypto.d.ts b/2_PAC/node_modules/@types/node/ts4.8/crypto.d.ts new file mode 100644 index 00000000..20d960cd --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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; + } + /** + * 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): DiffieHellman; + function createDiffieHellman(prime: ArrayBuffer | NodeJS.ArrayBufferView, generator?: number | ArrayBuffer | NodeJS.ArrayBufferView): DiffieHellman; + function createDiffieHellman(prime: ArrayBuffer | NodeJS.ArrayBufferView, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman; + function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator?: number | ArrayBuffer | 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 2^48. `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(encoding?: null, format?: ECDHKeyFormat): 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' | 'jwk'; + 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' | 'default' | '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 when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * 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: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise; + deriveBits(algorithm: AlgorithmIdentifier | 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/2_PAC/node_modules/@types/node/ts4.8/dgram.d.ts b/2_PAC/node_modules/@types/node/ts4.8/dgram.d.ts new file mode 100644 index 00000000..247328d2 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts b/2_PAC/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts new file mode 100644 index 00000000..3dcaa035 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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 | symbol): 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 | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => 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 | symbol; + /** + * 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 | symbol); + /** + * 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/2_PAC/node_modules/@types/node/ts4.8/dns.d.ts b/2_PAC/node_modules/@types/node/ts4.8/dns.d.ts new file mode 100644 index 00000000..305367b8 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/dns/promises.d.ts b/2_PAC/node_modules/@types/node/ts4.8/dns/promises.d.ts new file mode 100644 index 00000000..77cd807b --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/dom-events.d.ts b/2_PAC/node_modules/@types/node/ts4.8/dom-events.d.ts new file mode 100644 index 00000000..b9c1c3aa --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/dom-events.d.ts @@ -0,0 +1,126 @@ +export {}; // Don't export anything! + +//// DOM-like Events +// NB: The Event / EventTarget / EventListener implementations below were copied +// from lib.dom.d.ts, then edited to reflect Node's documentation at +// https://nodejs.org/api/events.html#class-eventtarget. +// Please read that link to understand important implementation differences. + +// This conditional type will be the existing global Event in a browser, or +// the copy below in a Node environment. +type __Event = typeof globalThis extends { onmessage: any, Event: any } +? {} +: { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?] + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; +}; + +// See comment above explaining conditional type +type __EventTarget = typeof globalThis extends { onmessage: any, EventTarget: any } +? {} +: { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; +}; + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +import {} from 'events'; // Make this an ambient declaration +declare global { + /** An event which takes place in the DOM. */ + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any, Event: infer T } + ? T + : { + prototype: __Event; + new (type: string, eventInitDict?: EventInit): __Event; + }; + + /** + * EventTarget is a DOM interface implemented by objects that can + * receive events and may have listeners for them. + */ + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any, EventTarget: infer T } + ? T + : { + prototype: __EventTarget; + new (): __EventTarget; + }; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/domain.d.ts b/2_PAC/node_modules/@types/node/ts4.8/domain.d.ts new file mode 100644 index 00000000..fafe68a5 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/events.d.ts b/2_PAC/node_modules/@types/node/ts4.8/events.d.ts new file mode 100644 index 00000000..4633df19 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/events.d.ts @@ -0,0 +1,678 @@ +/** + * 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' { + // NOTE: This class is in the docs but is **not actually exported** by Node. + // If https://github.com/nodejs/node/issues/39903 gets resolved and Node + // actually starts exporting the class, uncomment below. + + // import { EventListener, EventListenerObject } from '__dom-events'; + // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ + // interface NodeEventTarget extends EventTarget { + // /** + // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. + // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. + // */ + // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ + // eventNames(): string[]; + // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ + // listenerCount(type: string): number; + // /** Node.js-specific alias for `eventTarget.removeListener()`. */ + // off(type: string, listener: EventListener | EventListenerObject): this; + // /** Node.js-specific alias for `eventTarget.addListener()`. */ + // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ + // once(type: string, listener: EventListener | EventListenerObject): this; + // /** + // * Node.js-specific extension to the `EventTarget` class. + // * If `type` is specified, removes all registered listeners for `type`, + // * otherwise removes all registered listeners. + // */ + // removeAllListeners(type: string): this; + // /** + // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. + // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. + // */ + // removeListener(type: string, listener: EventListener | EventListenerObject): this; + // } + + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + // Any EventTarget with a Node-style `once` function + interface _NodeEventTarget { + once(eventName: string | symbol, listener: (...args: any[]) => void): this; + } + // Any EventTarget with a DOM-style `addEventListener` + 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<_DOMEventTarget | NodeJS.EventEmitter>): 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/2_PAC/node_modules/@types/node/ts4.8/fs.d.ts b/2_PAC/node_modules/@types/node/ts4.8/fs.d.ts new file mode 100644 index 00000000..75c53fb0 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/fs.d.ts @@ -0,0 +1,3872 @@ +/** + * 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, 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; + } + /** + * 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; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: 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; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): 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?: CopySyncOptions): void; +} +declare module 'node:fs' { + export * from 'fs'; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/fs/promises.d.ts b/2_PAC/node_modules/@types/node/ts4.8/fs/promises.d.ts new file mode 100644 index 00000000..aca2fd51 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/fs/promises.d.ts @@ -0,0 +1,1138 @@ +/** + * 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 { + BigIntStats, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatOptions, + Stats, + TimeLike, + WatchEventType, + WatchOptions, + WriteStream, + WriteVResult, + } from 'node:fs'; + import { Interface as ReadlineInterface } from 'node:readline'; + + 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; + /** + * Convenience method to create a `readline` interface and stream over the file. For example: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * + * @since v18.11.0 + * @param options See `filehandle.createReadStream()` for the options. + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @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: TimeLike, mtime: TimeLike): 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; + } + + const constants: typeof fsConstants; + + /** + * 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: TimeLike, mtime: TimeLike): 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: TimeLike, mtime: TimeLike): 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/2_PAC/node_modules/@types/node/ts4.8/globals.d.ts b/2_PAC/node_modules/@types/node/ts4.8/globals.d.ts new file mode 100644 index 00000000..f401d95a --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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 extends EventTarget { + /** + * 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/2_PAC/node_modules/@types/node/ts4.8/globals.global.d.ts b/2_PAC/node_modules/@types/node/ts4.8/globals.global.d.ts new file mode 100644 index 00000000..ef1198c0 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/2_PAC/node_modules/@types/node/ts4.8/http.d.ts b/2_PAC/node_modules/@types/node/ts4.8/http.d.ts new file mode 100644 index 00000000..e14de6cf --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/http.d.ts @@ -0,0 +1,1651 @@ +/** + * 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'; + import { LookupOptions } from 'node:dns'; + // 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 { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: + | ((options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | undefined; + hints?: LookupOptions['hints']; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * 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. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: 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; + /** + * 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 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > 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: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: 'request', listener: RequestListener): this; + addListener( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: 'checkExpectation', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'clientError', err: Error, socket: stream.Duplex): boolean; + emit(event: 'connect', req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit( + event: 'request', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'upgrade', req: InstanceType, 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: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: 'request', listener: RequestListener): this; + on(event: 'upgrade', listener: (req: InstanceType, 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: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: 'request', listener: RequestListener): this; + once( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: 'request', listener: RequestListener): this; + prependListener( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: 'request', listener: RequestListener): this; + prependOnceListener( + event: 'upgrade', + listener: (req: InstanceType, 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: Request; + 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: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an 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 an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * Example: + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics' + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks + * }, earlyHintsCallback); + * ``` + * + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, 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 an 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< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >( + 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; + + /** + * Performs the low-level validations on the provided name that are done when `res.setHeader(name, value)` is called. + * Passing illegal value as name will result in a TypeError being thrown, identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * @param name Header name + * @since v14.3.0 + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided value that are done when `res.setHeader(name, value)` is called. + * Passing illegal value as value will result in a TypeError being thrown. + * - Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * - Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * @param name Header name + * @param value Header value + * @since v14.3.0 + */ + function validateHeaderValue(name: string, value: string): void; + + /** + * Set the maximum number of idle HTTP parsers. Default: 1000. + * @param count + * @since v18.8.0, v16.18.0 + */ + function setMaxIdleHTTPParsers(count: number): void; + + 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/2_PAC/node_modules/@types/node/ts4.8/http2.d.ts b/2_PAC/node_modules/@types/node/ts4.8/http2.d.ts new file mode 100644 index 00000000..0e368260 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/http2.d.ts @@ -0,0 +1,2134 @@ +/** + * 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, callback?: (err: Error | null, settings: Settings, duration: number) => void): 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 status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * Example: + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics' + * }); + * ``` + * + * @since v18.11.0 + * @param hints An object containing the values of headers + */ + writeEarlyHints(hints: Record): 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/2_PAC/node_modules/@types/node/ts4.8/https.d.ts b/2_PAC/node_modules/@types/node/ts4.8/https.d.ts new file mode 100644 index 00000000..bda367d7 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/https.d.ts @@ -0,0 +1,542 @@ +/** + * 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< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = http.RequestOptions & + tls.SecureContextOptions & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; + 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< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > 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: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: 'request', listener: http.RequestListener): this; + addListener( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: 'checkExpectation', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'clientError', err: Error, socket: Duplex): boolean; + emit(event: 'connect', req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: 'request', + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: 'upgrade', req: InstanceType, 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: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: 'request', listener: http.RequestListener): this; + on(event: 'upgrade', listener: (req: InstanceType, 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: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: 'request', listener: http.RequestListener): this; + once(event: 'upgrade', listener: (req: InstanceType, 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: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: 'request', listener: http.RequestListener): this; + prependListener( + event: 'upgrade', + listener: (req: InstanceType, 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: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: 'request', listener: http.RequestListener): this; + prependOnceListener( + event: 'upgrade', + listener: (req: InstanceType, 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< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + 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/2_PAC/node_modules/@types/node/ts4.8/index.d.ts b/2_PAC/node_modules/@types/node/ts4.8/index.d.ts new file mode 100644 index 00000000..7c8b38c6 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/index.d.ts @@ -0,0 +1,88 @@ +/** + * 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 4.8 and earlier. + +// 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/2_PAC/node_modules/@types/node/ts4.8/inspector.d.ts b/2_PAC/node_modules/@types/node/ts4.8/inspector.d.ts new file mode 100644 index 00000000..eba0b55d --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/inspector.d.ts @@ -0,0 +1,2741 @@ +// eslint-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/2_PAC/node_modules/@types/node/ts4.8/module.d.ts b/2_PAC/node_modules/@types/node/ts4.8/module.d.ts new file mode 100644 index 00000000..5a60a5fa --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/module.d.ts @@ -0,0 +1,115 @@ +/** + * @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 isBuiltin(moduleName: string): boolean; + 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/2_PAC/node_modules/@types/node/ts4.8/net.d.ts b/2_PAC/node_modules/@types/node/ts4.8/net.d.ts new file mode 100644 index 00000000..056407c8 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/net.d.ts @@ -0,0 +1,877 @@ +/** + * > 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; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | 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; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet + * and destroy this TCP socket once it is connected. Otherwise, it will call + * `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. If this is not a TCP socket + * (for example, a pipe), calling this method will immediately throw + * an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0 + * @return The socket itself. + */ + resetAndDestroy(): 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; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0 + */ + readonly localFamily?: string; + /** + * 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. ready + * 9. 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; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * 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 + * 5. drop + */ + 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: 'drop', listener: (data?: DropArgument) => 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; + emit(event: 'drop', data?: DropArgument): 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: 'drop', listener: (data?: DropArgument) => 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: 'drop', listener: (data?: DropArgument) => 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: 'drop', listener: (data?: DropArgument) => 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: 'drop', listener: (data?: DropArgument) => 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); + /** + * @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/2_PAC/node_modules/@types/node/ts4.8/os.d.ts b/2_PAC/node_modules/@types/node/ts4.8/os.d.ts new file mode 100644 index 00000000..3c555992 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/os.d.ts @@ -0,0 +1,466 @@ +/** + * 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'; + scopeid?: undefined; + } + 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 machine type as a string, such as arm, aarch64, mips, mips64, ppc64, ppc64le, s390, s390x, i386, i686, x86_64. + * + * On POSIX systems, the machine type 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 v18.9.0 + */ + function machine(): string; + /** + * 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/2_PAC/node_modules/@types/node/ts4.8/path.d.ts b/2_PAC/node_modules/@types/node/ts4.8/path.d.ts new file mode 100644 index 00000000..1d33f792 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/path.d.ts @@ -0,0 +1,191 @@ +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 path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + 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 paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * 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. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: 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 path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: 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 path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: '\\' | '/'; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ';' | ':'; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: 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/2_PAC/node_modules/@types/node/ts4.8/perf_hooks.d.ts b/2_PAC/node_modules/@types/node/ts4.8/perf_hooks.d.ts new file mode 100644 index 00000000..5c0b228e --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/perf_hooks.d.ts @@ -0,0 +1,625 @@ +/** + * 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. + toJSON(): any; + } + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: 'mark'; + } + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: 'measure'; + } + /** + * _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; + /** + * If name is not provided, removes all PerformanceMeasure objects from the Performance Timeline. + * If name is provided, removes only the named measure. + * @param name + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.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`. + * @param name + * @param type + * @since v16.7.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`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * 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 + * @return The PerformanceMark entry that was created + */ + mark(name?: string, options?: MarkOptions): PerformanceMark; + /** + * 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 + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * 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; + + import { performance as _performance } from 'perf_hooks'; + global { + /** + * `performance` is a global reference for `require('perf_hooks').performance` + * https://nodejs.org/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } + ? T + : typeof _performance; + } +} +declare module 'node:perf_hooks' { + export * from 'perf_hooks'; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/process.d.ts b/2_PAC/node_modules/@types/node/ts4.8/process.d.ts new file mode 100644 index 00000000..12148f91 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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 that 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/2_PAC/node_modules/@types/node/ts4.8/punycode.d.ts b/2_PAC/node_modules/@types/node/ts4.8/punycode.d.ts new file mode 100644 index 00000000..87ebbb90 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/querystring.d.ts b/2_PAC/node_modules/@types/node/ts4.8/querystring.d.ts new file mode 100644 index 00000000..e1185478 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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'); + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical + * or when compatibility with browser code is desirable. + * @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/2_PAC/node_modules/@types/node/ts4.8/readline.d.ts b/2_PAC/node_modules/@types/node/ts4.8/readline.d.ts new file mode 100644 index 00000000..6ab64acb --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/readline.d.ts @@ -0,0 +1,653 @@ +/** + * 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'; + import * as promises from 'node:readline/promises'; + + export { promises }; + export 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 + */ + export 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; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => void; + export type CompleterResult = [string[], string]; + export 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 + */ + export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + export 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 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export 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`. + */ + export 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`. + */ + export 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`. + */ + export 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`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module 'node:readline' { + export * from 'readline'; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/readline/promises.d.ts b/2_PAC/node_modules/@types/node/ts4.8/readline/promises.d.ts new file mode 100644 index 00000000..8f9f06f0 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/readline/promises.d.ts @@ -0,0 +1,143 @@ +/** + * The `readline/promise` module provides an API for reading lines of input from a Readable stream one line at a time. + * + * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/readline/promises.js) + * @since v17.0.0 + */ +declare module 'readline/promises' { + import { Interface as _Interface, ReadLineOptions, Completer, AsyncCompleter, Direction } from 'node:readline'; + import { Abortable } from 'node:events'; + + class Interface extends _Interface { + /** + * 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 readlinePromises.Interface was created with output set to null or undefined the query is not written. + * + * If the question is called after rl.close(), it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an AbortSignal to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * @since v17.0.0 + * @param query A statement or query to write to output, prepended to the prompt. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + + class Readline { + /** + * @param stream A TTY stream. + */ + constructor(stream: NodeJS.WritableStream, options?: { autoCommit?: boolean }); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an action that clears current line of the associated `stream` in a specified direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an action that clears the associated `stream` from the current position of the cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an action that moves the cursor relative to its current position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless autoCommit: true was passed to the constructor. + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback()` method clears the internal list of pending actions without sending it to the associated `stream`. + */ + rollback(): this; + } + + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout + * }); + * ``` + * + * Once the `readlinePromises.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). + * + * ## Use of the `completer` function + * + * The `completer` function takes the current line entered by the user as an argument, and returns an `Array` with 2 entries: + * + * - An Array with matching entries for the completion. + * - The substring that was used for the matching. + * + * For instance: `[[substr1, substr2, ...], originalsubstring]`. + * + * ```js + * function completer(line) { + * const completions = '.help .error .exit .quit .q'.split(' '); + * const hits = completions.filter((c) => c.startsWith(line)); + * // Show all completions if none found + * return [hits.length ? hits : completions, line]; + * } + * ``` + * + * The `completer` function can also returns a `Promise`, or be asynchronous: + * + * ```js + * async function completer(linePartial) { + * await someAsyncWork(); + * return [['123'], linePartial]; + * } + * ``` + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module 'node:readline/promises' { + export * from 'readline/promises'; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/repl.d.ts b/2_PAC/node_modules/@types/node/ts4.8/repl.d.ts new file mode 100644 index 00000000..be42ccc4 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/stream.d.ts b/2_PAC/node_modules/@types/node/ts4.8/stream.d.ts new file mode 100644 index 00000000..a0df689e --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/stream.d.ts @@ -0,0 +1,1340 @@ +/** + * 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 { Blob as NodeBlob } from "node:buffer"; + 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 | NodeBlob | 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/2_PAC/node_modules/@types/node/ts4.8/stream/consumers.d.ts b/2_PAC/node_modules/@types/node/ts4.8/stream/consumers.d.ts new file mode 100644 index 00000000..1ebf12e1 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module 'stream/consumers' { + import { Blob as NodeBlob } from "node:buffer"; + 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/2_PAC/node_modules/@types/node/ts4.8/stream/promises.d.ts b/2_PAC/node_modules/@types/node/ts4.8/stream/promises.d.ts new file mode 100644 index 00000000..b427073d --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/stream/web.d.ts b/2_PAC/node_modules/@types/node/ts4.8/stream/web.d.ts new file mode 100644 index 00000000..f9ef0570 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/string_decoder.d.ts b/2_PAC/node_modules/@types/node/ts4.8/string_decoder.d.ts new file mode 100644 index 00000000..a5858041 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/test.d.ts b/2_PAC/node_modules/@types/node/ts4.8/test.d.ts new file mode 100644 index 00000000..8e20710e --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/test.d.ts @@ -0,0 +1,446 @@ +/** + * The `node:test` module provides a standalone testing module. + * @see [source](https://github.com/nodejs/node/blob/v18.x/lib/test.js) + */ +declare module 'node:test' { + /** + * Programmatically start the test runner. + * @since v18.9.0 + * @param options Configuration options for running tests. + * @returns A {@link TapStream} that emits events about the test execution. + */ + function run(options?: RunOptions): TapStream; + + /** + * 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; + namespace describe { + // Shorthand for skipping a suite, same as `describe([name], { skip: true }[, fn])`. + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function skip(name?: string, fn?: SuiteFn): void; + function skip(options?: TestOptions, fn?: SuiteFn): void; + function skip(fn?: SuiteFn): void; + + // Shorthand for marking a suite as `TODO`, same as `describe([name], { todo: true }[, fn])`. + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): void; + function todo(name?: string, fn?: SuiteFn): void; + function todo(options?: TestOptions, fn?: SuiteFn): void; + function todo(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; + namespace it { + // Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + function skip(name?: string, options?: TestOptions, fn?: ItFn): void; + function skip(name?: string, fn?: ItFn): void; + function skip(options?: TestOptions, fn?: ItFn): void; + function skip(fn?: ItFn): void; + + // Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. + function todo(name?: string, options?: TestOptions, fn?: ItFn): void; + function todo(name?: string, fn?: ItFn): void; + function todo(options?: TestOptions, fn?: ItFn): void; + function todo(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; + + interface RunOptions { + /** + * If a number is provided, then that many files would run in parallel. + * If truthy, it would run (number of cpu cores - 1) files in parallel. + * If falsy, it would only run one file at a time. + * If unspecified, subtests inherit this value from their parent. + * @default true + */ + concurrency?: number | boolean | undefined; + + /** + * An array containing the list of files to run. + * If unspecified, the test runner execution model will be used. + */ + files?: readonly string[] | undefined; + + /** + * Allows aborting an in-progress test execution. + * @default undefined + */ + signal?: AbortSignal | undefined; + + /** + * A number of milliseconds the test will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + } + + /** + * A successful call of the `run()` method will return a new `TapStream` object, + * streaming a [TAP](https://testanything.org/) output. + * `TapStream` will emit events in the order of the tests' definitions. + * @since v18.9.0 + */ + interface TapStream extends NodeJS.ReadableStream { + addListener(event: 'test:diagnostic', listener: (message: string) => void): this; + addListener(event: 'test:fail', listener: (data: TestFail) => void): this; + addListener(event: 'test:pass', listener: (data: TestPass) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: 'test:diagnostic', message: string): boolean; + emit(event: 'test:fail', data: TestFail): boolean; + emit(event: 'test:pass', data: TestPass): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: 'test:diagnostic', listener: (message: string) => void): this; + on(event: 'test:fail', listener: (data: TestFail) => void): this; + on(event: 'test:pass', listener: (data: TestPass) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: 'test:diagnostic', listener: (message: string) => void): this; + once(event: 'test:fail', listener: (data: TestFail) => void): this; + once(event: 'test:pass', listener: (data: TestPass) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: 'test:diagnostic', listener: (message: string) => void): this; + prependListener(event: 'test:fail', listener: (data: TestFail) => void): this; + prependListener(event: 'test:pass', listener: (data: TestPass) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: 'test:diagnostic', listener: (message: string) => void): this; + prependOnceListener(event: 'test:fail', listener: (data: TestFail) => void): this; + prependOnceListener(event: 'test:pass', listener: (data: TestPass) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + + interface TestFail { + /** + * The test duration. + */ + duration: number; + + /** + * The failure casing test to fail. + */ + error: Error; + + /** + * The test name. + */ + name: string; + + /** + * The ordinal number of the test. + */ + testNumber: number; + + /** + * Present if `context.todo` is called. + */ + todo?: string; + + /** + * Present if `context.skip` is called. + */ + skip?: string; + } + + interface TestPass { + /** + * The test duration. + */ + duration: number; + + /** + * The test name. + */ + name: string; + + /** + * The ordinal number of the test. + */ + testNumber: number; + + /** + * Present if `context.todo` is called. + */ + todo?: string; + + /** + * Present if `context.skip` is called. + */ + skip?: string; + } + + /** + * 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 create a hook running before each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach: typeof beforeEach; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach: typeof afterEach; + + /** + * 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; + + /** + * The name of the test. + * @since v18.8.0 + */ + readonly name: string; + + /** + * 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; + + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0 + */ + readonly signal: AbortSignal; + + /** + * 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 { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + + /** + * 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 | undefined; + + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + + /** + * 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 | undefined; + + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + + /** + * 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 | undefined; + } + + /** + * This function is used to create a hook running before running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function before(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after running a suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function after(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running before each subtest of the current suite. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + + /** + * The hook function. If the hook uses callbacks, the callback function is passed as the + * second argument. + */ + type HookFn = (done: (result?: any) => void) => any; + + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + + export { test as default, run, test, describe, it, before, after, beforeEach, afterEach }; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/timers.d.ts b/2_PAC/node_modules/@types/node/ts4.8/timers.d.ts new file mode 100644 index 00000000..b26f3ced --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/timers/promises.d.ts b/2_PAC/node_modules/@types/node/ts4.8/timers/promises.d.ts new file mode 100644 index 00000000..c1450684 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/timers/promises.d.ts @@ -0,0 +1,93 @@ +/** + * 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; + + interface Scheduler { + /** + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.wait(delay, options) is roughly equivalent to calling timersPromises.setTimeout(delay, undefined, options) except that the ref option is not supported. + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: TimerOptions) => Promise; + /** + * An experimental API defined by the Scheduling APIs draft specification being developed as a standard Web Platform API. + * Calling timersPromises.scheduler.yield() is equivalent to calling timersPromises.setImmediate() with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + + const scheduler: Scheduler; +} +declare module 'node:timers/promises' { + export * from 'timers/promises'; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/tls.d.ts b/2_PAC/node_modules/@types/node/ts4.8/tls.d.ts new file mode 100644 index 00000000..2c55eb93 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/tls.d.ts @@ -0,0 +1,1107 @@ +/** + * 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 { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve,if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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: () => 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 | null, sessionData: Buffer | null) => 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/2_PAC/node_modules/@types/node/ts4.8/trace_events.d.ts b/2_PAC/node_modules/@types/node/ts4.8/trace_events.d.ts new file mode 100644 index 00000000..d47aa931 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/tty.d.ts b/2_PAC/node_modules/@types/node/ts4.8/tty.d.ts new file mode 100644 index 00000000..6473f8db --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/url.d.ts b/2_PAC/node_modules/@types/node/ts4.8/url.d.ts new file mode 100644 index 00000000..e172acbf --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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 as NodeBlob } 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: NodeBlob): 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 T; + } + ? T + : 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 T; + } + ? T + : typeof _URLSearchParams; + } +} +declare module 'node:url' { + export * from 'url'; +} diff --git a/2_PAC/node_modules/@types/node/ts4.8/util.d.ts b/2_PAC/node_modules/@types/node/ts4.8/util.d.ts new file mode 100644 index 00000000..bb1100e7 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/util.d.ts @@ -0,0 +1,2011 @@ +/** + * 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.x/lib/util.js) + */ +declare module 'util' { + import * as types from 'node:util/types'; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + 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; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + 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; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * 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; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = 'special' | 'number' | 'bigint' | 'boolean' | 'undefined' | 'null' | 'string' | 'symbol' | 'date' | 'regexp' | 'module'; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + 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; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given {AbortSignal} as transferable so that it can be used with + * `structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * 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 fn 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 }; + + //// TextEncoder/Decoder + /** + * 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; + } + + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from 'util'; + global { + /** + * `TextDecoder` class is a global reference for `require('util').TextDecoder` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } + ? TextDecoder + : typeof _TextDecoder; + + /** + * `TextEncoder` class is a global reference for `require('util').TextEncoder` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } + ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a high-level API for command-line argument parsing. Takes a + * specification for the expected arguments and returns a structured object + * with the parsed values and positionals. + * + * `config` provides arguments for parsing and configures the parser. It + * supports the following properties: + * + * - `args` The array of argument strings. **Default:** `process.argv` with + * `execPath` and `filename` removed. + * - `options` Arguments known to the parser. Keys of `options` are the long + * names of options and values are objects accepting the following properties: + * + * - `type` Type of argument, which must be either `boolean` (for options + * which do not take values) or `string` (for options which do). + * - `multiple` Whether this option can be provided multiple + * times. If `true`, all values will be collected in an array. If + * `false`, values for the option are last-wins. **Default:** `false`. + * - `short` A single character alias for the option. + * - `default` The default option value when it is not set by args. It + * must be of the same type as the `type` property. When `multiple` + * is `true`, it must be an array. + * + * - `strict`: Whether an error should be thrown when unknown arguments + * are encountered, or when arguments are passed that do not match the + * `type` configured in `options`. **Default:** `true`. + * - `allowPositionals`: Whether this command accepts positional arguments. + * **Default:** `false` if `strict` is `true`, otherwise `true`. + * - `tokens`: Whether tokens {boolean} Return the parsed tokens. This is useful + * for extending the built-in behavior, from adding additional checks through + * to reprocessing the tokens in different ways. + * **Default:** `false`. + * + * @returns The parsed command line arguments: + * + * - `values` A mapping of parsed option names with their string + * or boolean values. + * - `positionals` Positional arguments. + * - `tokens` Detailed parse information (only if `tokens` was specified). + * + */ + export function parseArgs(config?: T): ParsedResults; + + interface ParseArgsOptionConfig { + /** + * Type of argument. + */ + type: 'string' | 'boolean'; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The default option value when it is not set by args. + * It must be of the same type as the the `type` property. + * When `multiple` is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + + interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionConfig; + } + + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true + ? IfTrue + : T extends false + ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false + ? IfFalse + : T extends true + ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T['strict'], + O['type'] extends 'string' ? string : O['type'] extends 'boolean' ? boolean : string | boolean, + string | boolean + >; + + type ParsedValues = + & IfDefaultsTrue + & (T['options'] extends ParseArgsOptionsConfig + ? { + -readonly [LongOption in keyof T['options']]: IfDefaultsFalse< + T['options'][LongOption]['multiple'], + undefined | Array>, + undefined | ExtractOptionValue + >; + } + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T['strict'], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionConfig, + > = O['type'] extends 'string' + ? { + kind: 'option'; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O['type'] extends 'boolean' + ? { + kind: 'option'; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T['options'] = keyof T['options'], + > = K extends unknown + ? T['options'] extends ParseArgsOptionsConfig + ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T['strict'], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: 'option-terminator'; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T['tokens'], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: 'option'; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: 'option'; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: 'positional'; index: number; value: string } + | { kind: 'option-terminator'; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T + ? { + values: { [longOption: string]: undefined | string | boolean | Array }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * @since v18.13.0 + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + */ + type: string; + + /** + * Gets and sets the subtype portion of the MIME. + */ + subtype: string; + + /** + * Gets the essence of the MIME. + * + * Use `mime.type` or `mime.subtype` to alter the MIME. + */ + readonly essence: string; + + /** + * Gets the `MIMEParams` object representing the parameters of the MIME. + */ + readonly params: MIMEParams; + + /** + * Returns the serialized MIME. + * + * Because of the need for standard compliance, this method + * does not allow users to customize the serialization process of the MIME. + */ + toString(): string; + } + + /** + * @since v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + entries(): IterableIterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. + * If there are no such pairs, `null` is returned. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + */ + keys(): IterableIterator; + /** + * Sets the value in the `MIMEParams` 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`. + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } +} +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/2_PAC/node_modules/@types/node/ts4.8/v8.d.ts b/2_PAC/node_modules/@types/node/ts4.8/v8.d.ts new file mode 100644 index 00000000..6685dc25 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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/2_PAC/node_modules/@types/node/ts4.8/vm.d.ts b/2_PAC/node_modules/@types/node/ts4.8/vm.d.ts new file mode 100644 index 00000000..c96513a5 --- /dev/null +++ b/2_PAC/node_modules/@types/node/ts4.8/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 ` +``` + +## Installation + +```sh +npm install bson +``` + +## Documentation + +### Objects + +
+
EJSON : object
+
+
+ +### Functions + +
+
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.

+
+
+ + + +### EJSON + +* [EJSON](#EJSON) + + * [.parse(text, [options])](#EJSON.parse) + + * [.stringify(value, [replacer], [space], [options])](#EJSON.stringify) + + * [.serialize(bson, [options])](#EJSON.serialize) + + * [.deserialize(ejson, [options])](#EJSON.deserialize) + + + + +#### *EJSON*.parse(text, [options]) + +| 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) | + +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)); +``` + + +#### *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) }; + +// prints '{"int32":{"$numberInt":"10"}}' +console.log(EJSON.stringify(doc, { relaxed: false })); + +// 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.useBigInt64] | Object | false | when deserializing a Long will return a BigInt. | +| [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. + +## Error Handling + +It is our recommendation to use `BSONError.isBSONError()` checks on errors and to avoid relying on parsing `error.message` and `error.name` strings in your code. We guarantee `BSONError.isBSONError()` 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. + +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 `BSONError.isBSONError()` will always be able to accurately capture the errors that our BSON library throws. + +Hypothetical example: A collection in our Db has an issue with UTF-8 data: + +```ts +let documentCount = 0; +const cursor = collection.find({}, { utf8Validation: true }); +try { + for await (const doc of cursor) documentCount += 1; +} catch (error) { + if (BSONError.isBSONError(error)) { + console.log(`Found the troublemaker UTF-8!: ${documentCount} ${error.message}`); + return documentCount; + } + throw error; +} +``` + +## React Native + +BSON requires that `TextEncoder`, `TextDecoder`, `atob`, `btoa`, and `crypto.getRandomValues` are available globally. These are present in most Javascript runtimes but require polyfilling in React Native. Polyfills for the missing functionality can be installed with the following command: +```sh +npm install --save react-native-get-random-values text-encoding-polyfill base-64 +``` + +The following snippet should be placed at the top of the entrypoint (by default this is the root `index.js` file) for React Native projects using the BSON library. These lines must be placed for any code that imports `BSON`. + +```typescript +// Required Polyfills For ReactNative +import {encode, decode} from 'base-64'; +if (global.btoa == null) { + global.btoa = encode; +} +if (global.atob == null) { + global.atob = decode; +} +import 'text-encoding-polyfill'; +import 'react-native-get-random-values'; +``` + +Finally, import the `BSON` library like so: + +```typescript +import { BSON, EJSON } from 'bson'; +``` + +This will cause React Native to import the `node_modules/bson/lib/bson.cjs` bundle (see the `"react-native"` setting we have in the `"exports"` section of our [package.json](./package.json).) + +### Technical Note about React Native module import + +The `"exports"` definition in our `package.json` will result in BSON's CommonJS bundle being imported in a React Native project instead of the ES module bundle. Importing the CommonJS bundle is necessary because BSON's ES module bundle of BSON uses top-level await, which is not supported syntax in [React Native's runtime hermes](https://hermesengine.dev/). + +## 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/2_PAC/node_modules/bson/bson.d.ts b/2_PAC/node_modules/bson/bson.d.ts new file mode 100644 index 00000000..fcf9ec38 --- /dev/null +++ b/2_PAC/node_modules/bson/bson.d.ts @@ -0,0 +1,1204 @@ +/** + * A class representation of the BSON Binary type. + * @public + * @category BSONType + */ +export declare class Binary extends BSONValue { + get _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: Uint8Array; + 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 | 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(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): 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 | number[]; + +declare namespace BSON { + export { + setInternalBufferSize, + serialize, + serializeWithBufferAndIndex, + deserialize, + calculateObjectSize, + deserializeStream, + UUIDExtended, + BinaryExtended, + BinaryExtendedLegacy, + BinarySequence, + CodeExtended, + DBRefLike, + Decimal128Extended, + DoubleExtended, + EJSONOptions, + Int32Extended, + LongExtended, + MaxKeyExtended, + MinKeyExtended, + ObjectIdExtended, + ObjectIdLike, + BSONRegExpExtended, + BSONRegExpExtendedLegacy, + BSONSymbolExtended, + LongWithoutOverrides, + TimestampExtended, + TimestampOverrides, + LongWithoutOverridesClass, + SerializeOptions, + DeserializeOptions, + Code, + BSONSymbol, + DBRef, + Binary, + ObjectId, + UUID, + Long, + Timestamp, + Double, + Int32, + MinKey, + MaxKey, + BSONRegExp, + Decimal128, + BSONValue, + BSONError, + BSONVersionError, + BSONType, + EJSON, + Document, + CalculateObjectSizeOptions + } +} +export { BSON } + +/** + * @public + * `BSONError` objects are thrown when runtime errors occur. + */ +export declare class BSONError extends Error { + /* Excluded from this release type: bsonError */ + get name(): string; + constructor(message: string); + /** + * @public + * + * All errors thrown from the BSON library inherit from `BSONError`. + * This method can assist with determining if an error originates from the BSON library + * even if it does not pass an `instanceof` check against this class' constructor. + * + * @param value - any javascript value that needs type checking + */ + static isBSONError(value: unknown): value is BSONError; +} + +/** + * A class representation of the BSON RegExp type. + * @public + * @category BSONType + */ +export declare class BSONRegExp extends BSONValue { + get _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 */ + inspect(): string; +} + +/** @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 extends BSONValue { + get _bsontype(): 'BSONSymbol'; + value: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string); + /** Access the wrapped string value. */ + valueOf(): string; + toString(): string; + inspect(): string; + toJSON(): string; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ +} + +/** @public */ +export declare interface BSONSymbolExtended { + $symbol: string; +} + +/** @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 abstract class BSONValue { + /** @public */ + abstract get _bsontype(): string; + /** @public */ + abstract inspect(): string; + /* Excluded from this release type: toExtendedJSON */ +} + +/** @public */ +export declare class BSONVersionError extends BSONError { + get name(): 'BSONVersionError'; + constructor(); +} + +/** + * 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 extends BSONValue { + get _bsontype(): 'Code'; + code: string; + scope: Document | null; + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document | null); + toJSON(): { + code: string; + scope?: Document; + }; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface CodeExtended { + $code: string; + $scope?: Document; +} + +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +export declare class DBRef extends BSONValue { + get _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 extends BSONValue { + get _bsontype(): 'Decimal128'; + readonly bytes: Uint8Array; + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Uint8Array | 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: Uint8Array, options?: DeserializeOptions): Document; + +/** @public */ +export declare interface DeserializeOptions { + /** when deserializing a Long will return as a BigInt. */ + useBigInt64?: 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: Uint8Array | 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 extends BSONValue { + get _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; +} + +/** @public */ +export declare const EJSON: { + parse: typeof parse; + stringify: typeof stringify; + serialize: typeof EJSONserialize; + deserialize: typeof EJSONdeserialize; +}; + +/** + * 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 + */ +declare function EJSONdeserialize(ejson: Document, options?: EJSONOptions): any; + +/** @public */ +export declare type EJSONOptions = { + /** 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; + /** Enable native bigint support */ + useBigInt64?: boolean; +}; + +/** + * 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 + */ +declare function EJSONserialize(value: any, options?: EJSONOptions): Document; + +/** + * A class representation of a BSON Int32 type. + * @public + * @category BSONType + */ +export declare class Int32 extends BSONValue { + get _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; + +/** + * 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 extends BSONValue { + get _bsontype(): 'Long'; + /** An indicator used to reliably determine if an object is a Long or not. */ + get __isLong__(): boolean; + /** + * 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 | bigint; + inspect(): string; +} + +/** @public */ +export declare interface LongExtended { + $numberLong: string; +} + +/** @public */ +export declare type LongWithoutOverrides = new (low: unknown, high?: number | boolean, unsigned?: boolean) => { + [P in Exclude]: Long[P]; +}; + +/** @public */ +export declare const LongWithoutOverridesClass: LongWithoutOverrides; + +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +export declare class MaxKey extends BSONValue { + get _bsontype(): 'MaxKey'; + /* 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 extends BSONValue { + get _bsontype(): 'MinKey'; + /* 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 + */ +export declare class ObjectId extends BSONValue { + get _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 | Uint8Array); + /** + * The ObjectId bytes + * @readonly + */ + get id(): Uint8Array; + set id(value: Uint8Array); + /** 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): Uint8Array; + /** + * Converts the id into a 24 character hex string for printing, unless encoding is provided. + * @param encoding - hex or base64 + */ + toString(encoding?: 'hex' | 'base64'): 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 | Uint8Array): boolean; + /* Excluded from this release type: toExtendedJSON */ + /* Excluded from this release type: fromExtendedJSON */ + inspect(): string; +} + +/** @public */ +export declare interface ObjectIdExtended { + $oid: string; +} + +/** @public */ +export declare interface ObjectIdLike { + id: string | Uint8Array; + __id?: string; + toHexString(): string; +} + +/** + * 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)); + * ``` + */ +declare function parse(text: string, options?: EJSONOptions): any; + +/** + * 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): Uint8Array; + +/** @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: Uint8Array, 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; + +/** + * 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)); + * ``` + */ +declare function stringify(value: any, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSONOptions, space?: string | number, options?: EJSONOptions): string; + +/** + * @public + * @category BSONType + * */ +export declare class Timestamp extends LongWithoutOverridesClass { + get _bsontype(): 'Timestamp'; + static readonly MAX_VALUE: Long; + /** + * @param int - A 64-bit bigint representing the Timestamp. + */ + constructor(int: bigint); + /** + * @param long - 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; + }); + 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 extends Binary { + static cacheHexString: boolean; + /* 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 | Uint8Array | UUID); + /** + * The UUID bytes + * @readonly + */ + get id(): Uint8Array; + set id(value: Uint8Array); + /** + * 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?: 'hex' | 'base64'): 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 | Uint8Array | UUID): boolean; + /** + * Creates a Binary instance from the current UUID. + */ + toBinary(): Binary; + /** + * Generates a populated buffer containing a v4 uuid + */ + static generate(): Uint8Array; + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Uint8Array | 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/2_PAC/node_modules/bson/etc/prepare.js b/2_PAC/node_modules/bson/etc/prepare.js new file mode 100644 index 00000000..91e6f3a9 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/bson/lib/bson.bundle.js b/2_PAC/node_modules/bson/lib/bson.bundle.js new file mode 100644 index 00000000..127da523 --- /dev/null +++ b/2_PAC/node_modules/bson/lib/bson.bundle.js @@ -0,0 +1,4072 @@ +var BSON = (function (exports) { +'use strict'; + +const BSON_MAJOR_VERSION = 5; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +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 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message) { + super(message); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); + } +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = (() => { + try { + return require('node:crypto').randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + fromUTF8(text) { + return Buffer.from(text, 'utf8'); + }, + toUTF8(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + fromUTF8(text) { + return new TextEncoder().encode(text); + }, + toUTF8(uint8array) { + return new TextDecoder('utf8', { fatal: false }).decode(uint8array); + }, + utf8ByteLength(input) { + return webByteUtils.fromUTF8(input).byteLength; + }, + encodeUTF8Into(buffer, source, byteOffset) { + const bytes = webByteUtils.fromUTF8(source); + buffer.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; +class BSONDataView extends DataView { + static fromUint8Array(input) { + return new DataView(input.buffer, input.byteOffset, input.byteLength); + } +} + +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; +const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); +const uuidHexStringToBuffer = (hexString) => { + if (!uuidValidateString(hexString)) { + throw new BSONError('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 ByteUtils.fromHex(sanitizedHexString); +}; +function bufferToUuidHexString(buffer, includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(buffer.subarray(0, 4)), + ByteUtils.toHex(buffer.subarray(4, 6)), + ByteUtils.toHex(buffer.subarray(6, 8)), + ByteUtils.toHex(buffer.subarray(8, 10)), + ByteUtils.toHex(buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(buffer); +} + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + this.buffer = ByteUtils.fromISO88591(buffer); + } + else if (Array.isArray(buffer)) { + this.buffer = ByteUtils.fromNumberArray(buffer); + } + else { + this.buffer = ByteUtils.toLocalBufferType(buffer); + } + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let 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 BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + const bytes = ByteUtils.fromISO88591(sequence); + this.buffer.set(bytes, offset); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value(asRaw) { + asRaw = !!asRaw; + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer); + return ByteUtils.toUTF8(this.buffer); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + 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() { + 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.`); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + 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 = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +class UUID extends Binary { + constructor(input) { + let bytes; + let hexStr; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + hexStr = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = uuidHexStringToBuffer(input); + } + else { + throw new BSONError('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).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + this.__id = hexStr; + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + toHexString(includeDashes = true) { + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + const uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + if (input.byteLength !== UUID_BYTE_LENGTH) { + return false; + } + return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; + } + return false; + } + static createFromHexString(hexString) { + const buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new UUID("${this.toHexString()}")`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const codeJson = this.toJSON(); + return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let 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; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + 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}"` : ''})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(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 { +} +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; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + 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; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + 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; + } + } + static fromNumber(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); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + 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; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(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); + } + static fromBytesBE(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); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + 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); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + 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; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + 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) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + 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 { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + 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); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(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; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + 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)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + 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 (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + 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); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(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); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(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); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + 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); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + 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 + ]; + } + toBytesBE() { + 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 + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + 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); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + 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; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +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; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + 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++) { + _rem = _rem.shiftLeft(32); + _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 }; +} +function multiply64x2(left, right) { + 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 { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + 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, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + let isNegative = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let firstDigit = 0; + let lastDigit = 0; + let exponent = 0; + let i = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + 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; + 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 BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + 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; + } + } + } + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit - firstDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + 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; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + 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)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + 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; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocate(16); + index = 0; + 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; + 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; + 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; + 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 new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + 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; + } + const exponent = biased_exponent - EXPONENT_BIAS; + 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; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + 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++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + 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() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Decimal128("${this.toString()}")`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const eJSON = this.toExtendedJSON(); + return `new Double(${eJSON.$numberDouble})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Int32(${this.valueOf()})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MinKey()'; + } +} + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +const kId = Symbol('id'); +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this[kId] = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 12) { + const bytes = ByteUtils.fromUTF8(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes'); + } + } + else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this[kId]; + } + set id(value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocate(12); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + 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]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); + } + 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 ByteUtils.equals(ByteUtils.fromUTF8(otherId), 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; + } + getTimestamp() { + const timestamp = new Date(); + const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + static createFromTime(time) { + const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new ObjectId("${this.toHexString()}")`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + 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 (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + 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)}`); + } + 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) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + 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 BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + inspect() { + return `new BSONSymbol("${this.value}")`; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + if (low.t < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (low.i < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (low.t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (low.i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(low.i.valueOf(), low.t.valueOf(), true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +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; +function validateUtf8(bytes, start, end) { + 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; +} + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + 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})`); + } + 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"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + const utf8KeysSet = new Set(); + 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]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i)); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === 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 === BSON_DATA_OID) { + const oid = ByteUtils.allocate(12); + oid.set(buffer.subarray(index, index + 12)); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(dataview.getFloat64(index, true)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = dataview.getFloat64(index, true); + index = index + 8; + } + else if (elementType === 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 === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === 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'); + 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 === 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; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, 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 === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); + 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); + if (useBigInt64) { + value = dataview.getBigInt64(0, true); + } + else 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 === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocate(16); + bytes.set(buffer.subarray(index, index + 16), 0); + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + 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 = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = value.toUUID(); + } + } + } + else { + const _buffer = ByteUtils.allocate(binarySize); + 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'); + } + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + 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 === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === 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 === BSON_DATA_TIMESTAMP) { + const i = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + const t = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + value = new Timestamp({ i, t }); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === 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); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + 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); + index = index + stringSize; + const _index = index; + const objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + 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'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); + index = index + stringSize; + const oidBuffer = ByteUtils.allocate(12); + oidBuffer.set(buffer.subarray(index, index + 12), 0); + const oid = new ObjectId(oidBuffer); + index = index + 12; + 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; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +function getValidatedString(buffer, start, end, shouldValidateUtf8) { + const value = ByteUtils.toUTF8(buffer.subarray(start, end)); + 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; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + 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; + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); +const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); +const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + if (type === BSON_DATA_INT) { + NUMBER_SPACE.setInt32(0, value, true); + } + else { + NUMBER_SPACE.setFloat64(0, value, true); + } + const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + buffer.set(bytes, index); + index += bytes.byteLength; + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setBigInt64(0, value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (isUint8Array(value.id)) { + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + return index + 12; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + buffer.set(value, index); + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + 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) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setFloat64(0, value.value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + 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; + buffer[index++] = value.sub_type; + 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; + } + buffer.set(data, index); + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $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, true, path); + const size = endIndex - startIndex; + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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 (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (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 (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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 === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +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 +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + 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; + 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; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + 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 BSONError('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(), 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))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + 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) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(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) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(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 (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + 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); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + 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, ejsonOptions); + }); +} +function stringify(value, 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; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, 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; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocate(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, 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; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + 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); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ +__proto__: null, +Code: Code, +BSONSymbol: BSONSymbol, +DBRef: DBRef, +Binary: Binary, +ObjectId: ObjectId, +UUID: UUID, +Long: Long, +Timestamp: Timestamp, +Double: Double, +Int32: Int32, +MinKey: MinKey, +MaxKey: MaxKey, +BSONRegExp: BSONRegExp, +Decimal128: Decimal128, +setInternalBufferSize: setInternalBufferSize, +serialize: serialize, +serializeWithBufferAndIndex: serializeWithBufferAndIndex, +deserialize: deserialize, +calculateObjectSize: calculateObjectSize, +deserializeStream: deserializeStream, +BSONValue: BSONValue, +BSONError: BSONError, +BSONVersionError: BSONVersionError, +BSONType: BSONType, +EJSON: EJSON +}); + +exports.BSON = bson; +exports.BSONError = BSONError; +exports.BSONRegExp = BSONRegExp; +exports.BSONSymbol = BSONSymbol; +exports.BSONType = BSONType; +exports.BSONValue = BSONValue; +exports.BSONVersionError = BSONVersionError; +exports.Binary = Binary; +exports.Code = Code; +exports.DBRef = DBRef; +exports.Decimal128 = Decimal128; +exports.Double = Double; +exports.EJSON = EJSON; +exports.Int32 = Int32; +exports.Long = Long; +exports.MaxKey = MaxKey; +exports.MinKey = MinKey; +exports.ObjectId = ObjectId; +exports.Timestamp = Timestamp; +exports.UUID = UUID; +exports.calculateObjectSize = calculateObjectSize; +exports.deserialize = deserialize; +exports.deserializeStream = deserializeStream; +exports.serialize = serialize; +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +exports.setInternalBufferSize = setInternalBufferSize; + +return exports; + +})({}); +//# sourceMappingURL=bson.bundle.js.map diff --git a/2_PAC/node_modules/bson/lib/bson.bundle.js.map b/2_PAC/node_modules/bson/lib/bson.bundle.js.map new file mode 100644 index 00000000..2d56f218 --- /dev/null +++ b/2_PAC/node_modules/bson/lib/bson.bundle.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.bundle.js","sources":["../src/constants.ts","../src/error.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/uuid_utils.ts","../src/parser/utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":";;;AACO,MAAM,kBAAkB,GAAG,CAAU,CAAC;AAGtC,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC,MAAM,cAAc,GAAG,CAAC,UAAU,CAAC;AAEnC,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAE3C,MAAM,cAAc,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAMxC,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAMnC,MAAM,UAAU,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAGpC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,eAAe,GAAG,CAAC,CAAC;AAG1B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,mBA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G,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAErD,IAAI,KAAK,GAAG,UAAU,CAAC;IAEvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;AAE1C,QAAA,MAAM,IAAI,GACR,UAAU,CAAC,KAAK,CAAC;aAChB,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;aAC3B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;aAC5B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAEhC,QAAA,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;AAE9B,QAAA,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAEhF,QAAA,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AACtB,KAAA;AAGD,IAAA,OAAO,KAAK,CAAC;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/2_PAC/node_modules/bson/lib/bson.cjs b/2_PAC/node_modules/bson/lib/bson.cjs new file mode 100644 index 00000000..5813029c --- /dev/null +++ b/2_PAC/node_modules/bson/lib/bson.cjs @@ -0,0 +1,4067 @@ +'use strict'; + +const BSON_MAJOR_VERSION = 5; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +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 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message) { + super(message); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); + } +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = (() => { + try { + return require('node:crypto').randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + fromUTF8(text) { + return Buffer.from(text, 'utf8'); + }, + toUTF8(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + fromUTF8(text) { + return new TextEncoder().encode(text); + }, + toUTF8(uint8array) { + return new TextDecoder('utf8', { fatal: false }).decode(uint8array); + }, + utf8ByteLength(input) { + return webByteUtils.fromUTF8(input).byteLength; + }, + encodeUTF8Into(buffer, source, byteOffset) { + const bytes = webByteUtils.fromUTF8(source); + buffer.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; +class BSONDataView extends DataView { + static fromUint8Array(input) { + return new DataView(input.buffer, input.byteOffset, input.byteLength); + } +} + +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; +const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); +const uuidHexStringToBuffer = (hexString) => { + if (!uuidValidateString(hexString)) { + throw new BSONError('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 ByteUtils.fromHex(sanitizedHexString); +}; +function bufferToUuidHexString(buffer, includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(buffer.subarray(0, 4)), + ByteUtils.toHex(buffer.subarray(4, 6)), + ByteUtils.toHex(buffer.subarray(6, 8)), + ByteUtils.toHex(buffer.subarray(8, 10)), + ByteUtils.toHex(buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(buffer); +} + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + this.buffer = ByteUtils.fromISO88591(buffer); + } + else if (Array.isArray(buffer)) { + this.buffer = ByteUtils.fromNumberArray(buffer); + } + else { + this.buffer = ByteUtils.toLocalBufferType(buffer); + } + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let 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 BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + const bytes = ByteUtils.fromISO88591(sequence); + this.buffer.set(bytes, offset); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value(asRaw) { + asRaw = !!asRaw; + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer); + return ByteUtils.toUTF8(this.buffer); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + 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() { + 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.`); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + 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 = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +class UUID extends Binary { + constructor(input) { + let bytes; + let hexStr; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + hexStr = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = uuidHexStringToBuffer(input); + } + else { + throw new BSONError('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).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + this.__id = hexStr; + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + toHexString(includeDashes = true) { + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + const uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + if (input.byteLength !== UUID_BYTE_LENGTH) { + return false; + } + return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; + } + return false; + } + static createFromHexString(hexString) { + const buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new UUID("${this.toHexString()}")`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const codeJson = this.toJSON(); + return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let 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; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + 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}"` : ''})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(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 { +} +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; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + 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; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + 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; + } + } + static fromNumber(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); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + 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; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(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); + } + static fromBytesBE(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); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + 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); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + 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; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + 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) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + 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 { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + 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); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(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; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + 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)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + 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 (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + 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); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(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); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(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); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + 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); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + 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 + ]; + } + toBytesBE() { + 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 + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + 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); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + 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; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +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; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + 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++) { + _rem = _rem.shiftLeft(32); + _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 }; +} +function multiply64x2(left, right) { + 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 { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + 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, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + let isNegative = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let firstDigit = 0; + let lastDigit = 0; + let exponent = 0; + let i = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + 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; + 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 BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + 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; + } + } + } + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit - firstDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + 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; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + 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)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + 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; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocate(16); + index = 0; + 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; + 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; + 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; + 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 new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + 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; + } + const exponent = biased_exponent - EXPONENT_BIAS; + 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; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + 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++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + 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() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Decimal128("${this.toString()}")`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const eJSON = this.toExtendedJSON(); + return `new Double(${eJSON.$numberDouble})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Int32(${this.valueOf()})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MinKey()'; + } +} + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +const kId = Symbol('id'); +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this[kId] = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 12) { + const bytes = ByteUtils.fromUTF8(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes'); + } + } + else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this[kId]; + } + set id(value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocate(12); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + 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]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); + } + 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 ByteUtils.equals(ByteUtils.fromUTF8(otherId), 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; + } + getTimestamp() { + const timestamp = new Date(); + const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + static createFromTime(time) { + const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new ObjectId("${this.toHexString()}")`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + 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 (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + 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)}`); + } + 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) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + 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 BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + inspect() { + return `new BSONSymbol("${this.value}")`; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + if (low.t < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (low.i < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (low.t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (low.i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(low.i.valueOf(), low.t.valueOf(), true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +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; +function validateUtf8(bytes, start, end) { + 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; +} + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + 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})`); + } + 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"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + const utf8KeysSet = new Set(); + 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]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i)); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === 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 === BSON_DATA_OID) { + const oid = ByteUtils.allocate(12); + oid.set(buffer.subarray(index, index + 12)); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(dataview.getFloat64(index, true)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = dataview.getFloat64(index, true); + index = index + 8; + } + else if (elementType === 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 === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === 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'); + 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 === 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; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, 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 === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); + 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); + if (useBigInt64) { + value = dataview.getBigInt64(0, true); + } + else 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 === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocate(16); + bytes.set(buffer.subarray(index, index + 16), 0); + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + 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 = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = value.toUUID(); + } + } + } + else { + const _buffer = ByteUtils.allocate(binarySize); + 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'); + } + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + 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 === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === 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 === BSON_DATA_TIMESTAMP) { + const i = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + const t = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + value = new Timestamp({ i, t }); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === 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); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + 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); + index = index + stringSize; + const _index = index; + const objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + 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'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); + index = index + stringSize; + const oidBuffer = ByteUtils.allocate(12); + oidBuffer.set(buffer.subarray(index, index + 12), 0); + const oid = new ObjectId(oidBuffer); + index = index + 12; + 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; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +function getValidatedString(buffer, start, end, shouldValidateUtf8) { + const value = ByteUtils.toUTF8(buffer.subarray(start, end)); + 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; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + 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; + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); +const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); +const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + if (type === BSON_DATA_INT) { + NUMBER_SPACE.setInt32(0, value, true); + } + else { + NUMBER_SPACE.setFloat64(0, value, true); + } + const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + buffer.set(bytes, index); + index += bytes.byteLength; + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setBigInt64(0, value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (isUint8Array(value.id)) { + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + return index + 12; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + buffer.set(value, index); + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + 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) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setFloat64(0, value.value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + 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; + buffer[index++] = value.sub_type; + 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; + } + buffer.set(data, index); + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $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, true, path); + const size = endIndex - startIndex; + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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 (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (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 (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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 === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +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 +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + 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; + 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; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + 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 BSONError('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(), 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))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + 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) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(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) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(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 (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + 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); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + 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, ejsonOptions); + }); +} +function stringify(value, 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; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, 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; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocate(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, 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; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + 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); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ + __proto__: null, + Code: Code, + BSONSymbol: BSONSymbol, + DBRef: DBRef, + Binary: Binary, + ObjectId: ObjectId, + UUID: UUID, + Long: Long, + Timestamp: Timestamp, + Double: Double, + Int32: Int32, + MinKey: MinKey, + MaxKey: MaxKey, + BSONRegExp: BSONRegExp, + Decimal128: Decimal128, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONValue: BSONValue, + BSONError: BSONError, + BSONVersionError: BSONVersionError, + BSONType: BSONType, + EJSON: EJSON +}); + +exports.BSON = bson; +exports.BSONError = BSONError; +exports.BSONRegExp = BSONRegExp; +exports.BSONSymbol = BSONSymbol; +exports.BSONType = BSONType; +exports.BSONValue = BSONValue; +exports.BSONVersionError = BSONVersionError; +exports.Binary = Binary; +exports.Code = Code; +exports.DBRef = DBRef; +exports.Decimal128 = Decimal128; +exports.Double = Double; +exports.EJSON = EJSON; +exports.Int32 = Int32; +exports.Long = Long; +exports.MaxKey = MaxKey; +exports.MinKey = MinKey; +exports.ObjectId = ObjectId; +exports.Timestamp = Timestamp; +exports.UUID = UUID; +exports.calculateObjectSize = calculateObjectSize; +exports.deserialize = deserialize; +exports.deserializeStream = deserializeStream; +exports.serialize = serialize; +exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex; +exports.setInternalBufferSize = setInternalBufferSize; +//# sourceMappingURL=bson.cjs.map diff --git a/2_PAC/node_modules/bson/lib/bson.cjs.map b/2_PAC/node_modules/bson/lib/bson.cjs.map new file mode 100644 index 00000000..ab648495 --- /dev/null +++ b/2_PAC/node_modules/bson/lib/bson.cjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.cjs","sources":["../src/constants.ts","../src/error.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/uuid_utils.ts","../src/parser/utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":";;AACO,MAAM,kBAAkB,GAAG,CAAU,CAAC;AAGtC,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC,MAAM,cAAc,GAAG,CAAC,UAAU,CAAC;AAEnC,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAE3C,MAAM,cAAc,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAMxC,MAAM,UAAU,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAMnC,MAAM,UAAU,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC;AAGpC,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,eAAe,GAAG,CAAC,CAAC;AAG1B,MAAM,gBAAgB,GAAG,CAAC,CAAC;AAG3B,MAAM,mBAAmB,GAAG,CAAC,CAAC;AAG9B,MAAM,aAAa,GAAG,CAAC,CAAC;AAGxB,MAAM,iBAAiB,GAAG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vB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;AAE1C,QAAA,MAAM,IAAI,GACR,UAAU,CAAC,KAAK,CAAC;aAChB,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;aAC3B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;aAC5B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAEhC,QAAA,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;AAE9B,QAAA,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAEhF,QAAA,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AACtB,KAAA;AAGD,IAAA,OAAO,KAAK,CAAC;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/2_PAC/node_modules/bson/lib/bson.mjs b/2_PAC/node_modules/bson/lib/bson.mjs new file mode 100644 index 00000000..8eb39675 --- /dev/null +++ b/2_PAC/node_modules/bson/lib/bson.mjs @@ -0,0 +1,4040 @@ +const BSON_MAJOR_VERSION = 5; +const BSON_INT32_MAX = 0x7fffffff; +const BSON_INT32_MIN = -0x80000000; +const BSON_INT64_MAX = Math.pow(2, 63) - 1; +const BSON_INT64_MIN = -Math.pow(2, 63); +const JS_INT_MAX = Math.pow(2, 53); +const JS_INT_MIN = -Math.pow(2, 53); +const BSON_DATA_NUMBER = 1; +const BSON_DATA_STRING = 2; +const BSON_DATA_OBJECT = 3; +const BSON_DATA_ARRAY = 4; +const BSON_DATA_BINARY = 5; +const BSON_DATA_UNDEFINED = 6; +const BSON_DATA_OID = 7; +const BSON_DATA_BOOLEAN = 8; +const BSON_DATA_DATE = 9; +const BSON_DATA_NULL = 10; +const BSON_DATA_REGEXP = 11; +const BSON_DATA_DBPOINTER = 12; +const BSON_DATA_CODE = 13; +const BSON_DATA_SYMBOL = 14; +const BSON_DATA_CODE_W_SCOPE = 15; +const BSON_DATA_INT = 16; +const BSON_DATA_TIMESTAMP = 17; +const BSON_DATA_LONG = 18; +const BSON_DATA_DECIMAL128 = 19; +const BSON_DATA_MIN_KEY = 0xff; +const BSON_DATA_MAX_KEY = 0x7f; +const BSON_BINARY_SUBTYPE_DEFAULT = 0; +const BSON_BINARY_SUBTYPE_UUID_NEW = 4; +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 +}); + +class BSONError extends Error { + get bsonError() { + return true; + } + get name() { + return 'BSONError'; + } + constructor(message) { + super(message); + } + static isBSONError(value) { + return (value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + 'name' in value && + 'message' in value && + 'stack' in value); + } +} +class BSONVersionError extends BSONError { + get name() { + return 'BSONVersionError'; + } + constructor() { + super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later`); + } +} + +function nodejsMathRandomBytes(byteLength) { + return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const nodejsRandomBytes = await (async () => { + try { + return (await import('node:crypto')).randomBytes; + } + catch { + return nodejsMathRandomBytes; + } +})(); +const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer) { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength); + } + const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return Buffer.from(potentialBuffer); + } + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + allocate(size) { + return Buffer.alloc(size); + }, + equals(a, b) { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + fromNumberArray(array) { + return Buffer.from(array); + }, + fromBase64(base64) { + return Buffer.from(base64, 'base64'); + }, + toBase64(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + fromISO88591(codePoints) { + return Buffer.from(codePoints, 'binary'); + }, + toISO88591(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + fromHex(hex) { + return Buffer.from(hex, 'hex'); + }, + toHex(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + fromUTF8(text) { + return Buffer.from(text, 'utf8'); + }, + toUTF8(buffer) { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); + }, + utf8ByteLength(input) { + return Buffer.byteLength(input, 'utf8'); + }, + encodeUTF8Into(buffer, source, byteOffset) { + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + randomBytes: nodejsRandomBytes +}; + +function isReactNative() { + const { navigator } = globalThis; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} +function webMathRandomBytes(byteLength) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256))); +} +const webRandomBytes = (() => { + const { crypto } = globalThis; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength) => { + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } + else { + if (isReactNative()) { + const { console } = globalThis; + console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'); + } + return webMathRandomBytes; + } +})(); +const HEX_DIGIT = /(\d|[a-f])/i; +const webByteUtils = { + toLocalBufferType(potentialUint8array) { + const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + if (stringTag === 'Uint8Array') { + return potentialUint8array; + } + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength)); + } + if (stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]') { + return new Uint8Array(potentialUint8array); + } + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + allocate(size) { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + equals(a, b) { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + fromNumberArray(array) { + return Uint8Array.from(array); + }, + fromBase64(base64) { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + toBase64(uint8array) { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + fromISO88591(codePoints) { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + toISO88591(uint8array) { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + fromHex(hex) { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + return Uint8Array.from(buffer); + }, + toHex(uint8array) { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + fromUTF8(text) { + return new TextEncoder().encode(text); + }, + toUTF8(uint8array) { + return new TextDecoder('utf8', { fatal: false }).decode(uint8array); + }, + utf8ByteLength(input) { + return webByteUtils.fromUTF8(input).byteLength; + }, + encodeUTF8Into(buffer, source, byteOffset) { + const bytes = webByteUtils.fromUTF8(source); + buffer.set(bytes, byteOffset); + return bytes.byteLength; + }, + randomBytes: webRandomBytes +}; + +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; +const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; +class BSONDataView extends DataView { + static fromUint8Array(input) { + return new DataView(input.buffer, input.byteOffset, input.byteLength); + } +} + +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; +const uuidValidateString = (str) => typeof str === 'string' && VALIDATION_REGEX.test(str); +const uuidHexStringToBuffer = (hexString) => { + if (!uuidValidateString(hexString)) { + throw new BSONError('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 ByteUtils.fromHex(sanitizedHexString); +}; +function bufferToUuidHexString(buffer, includeDashes = true) { + if (includeDashes) { + return [ + ByteUtils.toHex(buffer.subarray(0, 4)), + ByteUtils.toHex(buffer.subarray(4, 6)), + ByteUtils.toHex(buffer.subarray(6, 8)), + ByteUtils.toHex(buffer.subarray(8, 10)), + ByteUtils.toHex(buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(buffer); +} + +function isAnyArrayBuffer(value) { + return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value)); +} +function isUint8Array(value) { + return Object.prototype.toString.call(value) === '[object Uint8Array]'; +} +function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} +function isMap(d) { + return Object.prototype.toString.call(d) === '[object Map]'; +} +function isDate(d) { + return Object.prototype.toString.call(d) === '[object Date]'; +} + +class BSONValue { + get [Symbol.for('@@mdb.bson.version')]() { + return BSON_MAJOR_VERSION; + } +} + +class Binary extends BSONValue { + get _bsontype() { + return 'Binary'; + } + constructor(buffer, subType) { + super(); + if (!(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer)) { + throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array'); + } + this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT; + if (buffer == null) { + this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } + else { + if (typeof buffer === 'string') { + this.buffer = ByteUtils.fromISO88591(buffer); + } + else if (Array.isArray(buffer)) { + this.buffer = ByteUtils.fromNumberArray(buffer); + } + else { + this.buffer = ByteUtils.toLocalBufferType(buffer); + } + this.position = this.buffer.byteLength; + } + } + put(byteValue) { + if (typeof byteValue === 'string' && byteValue.length !== 1) { + throw new BSONError('only accepts single character String'); + } + else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('only accepts single character Uint8Array or Array'); + let 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 BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } + else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + this.buffer[this.position++] = decodedByte; + } + } + write(sequence, offset) { + offset = typeof offset === 'number' ? offset : this.position; + if (this.buffer.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + } + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } + else if (typeof sequence === 'string') { + const bytes = ByteUtils.fromISO88591(sequence); + this.buffer.set(bytes, offset); + this.position = + offset + sequence.length > this.position ? offset + sequence.length : this.position; + } + } + read(position, length) { + length = length && length > 0 ? length : this.position; + return this.buffer.slice(position, position + length); + } + value(asRaw) { + asRaw = !!asRaw; + if (asRaw && this.buffer.length === this.position) { + return this.buffer; + } + if (asRaw) { + return this.buffer.slice(0, this.position); + } + return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); + } + length() { + return this.position; + } + toJSON() { + return ByteUtils.toBase64(this.buffer); + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') + return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') + return ByteUtils.toUTF8(this.buffer); + return ByteUtils.toUTF8(this.buffer); + } + toExtendedJSON(options) { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + 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() { + 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.`); + } + static fromExtendedJSON(doc, options) { + options = options || {}; + let data; + 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 = ByteUtils.fromBase64(doc.$binary); + } + else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } + else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; + } +} +Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0; +Binary.BUFFER_SIZE = 256; +Binary.SUBTYPE_DEFAULT = 0; +Binary.SUBTYPE_FUNCTION = 1; +Binary.SUBTYPE_BYTE_ARRAY = 2; +Binary.SUBTYPE_UUID_OLD = 3; +Binary.SUBTYPE_UUID = 4; +Binary.SUBTYPE_MD5 = 5; +Binary.SUBTYPE_ENCRYPTED = 6; +Binary.SUBTYPE_COLUMN = 7; +Binary.SUBTYPE_USER_DEFINED = 128; +const UUID_BYTE_LENGTH = 16; +class UUID extends Binary { + constructor(input) { + let bytes; + let hexStr; + if (input == null) { + bytes = UUID.generate(); + } + else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + hexStr = input.__id; + } + else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } + else if (typeof input === 'string') { + bytes = uuidHexStringToBuffer(input); + } + else { + throw new BSONError('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).'); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + this.__id = hexStr; + } + get id() { + return this.buffer; + } + set id(value) { + this.buffer = value; + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + toHexString(includeDashes = true) { + if (UUID.cacheHexString && this.__id) { + return this.__id; + } + const uuidHexString = bufferToUuidHexString(this.id, includeDashes); + if (UUID.cacheHexString) { + this.__id = uuidHexString; + } + return uuidHexString; + } + toString(encoding) { + if (encoding === 'hex') + return ByteUtils.toHex(this.id); + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (!otherId) { + return false; + } + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + try { + return ByteUtils.equals(new UUID(otherId).id, this.id); + } + catch { + return false; + } + } + toBinary() { + return new Binary(this.id, Binary.SUBTYPE_UUID); + } + static generate() { + const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH); + bytes[6] = (bytes[6] & 0x0f) | 0x40; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + return bytes; + } + static isValid(input) { + if (!input) { + return false; + } + if (input instanceof UUID) { + return true; + } + if (typeof input === 'string') { + return uuidValidateString(input); + } + if (isUint8Array(input)) { + if (input.byteLength !== UUID_BYTE_LENGTH) { + return false; + } + return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; + } + return false; + } + static createFromHexString(hexString) { + const buffer = uuidHexStringToBuffer(hexString); + return new UUID(buffer); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new UUID("${this.toHexString()}")`; + } +} + +class Code extends BSONValue { + get _bsontype() { + return 'Code'; + } + constructor(code, scope) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + toJSON() { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + return { code: this.code }; + } + toExtendedJSON() { + if (this.scope) { + return { $code: this.code, $scope: this.scope }; + } + return { $code: this.code }; + } + static fromExtendedJSON(doc) { + return new Code(doc.$code, doc.$scope); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const codeJson = this.toJSON(); + return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`; + } +} + +function isDBRefLike(value) { + return (value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string'))); +} +class DBRef extends BSONValue { + get _bsontype() { + return 'DBRef'; + } + constructor(collection, oid, db, fields) { + super(); + const parts = collection.split('.'); + if (parts.length === 2) { + db = parts.shift(); + collection = parts.shift(); + } + this.collection = collection; + this.oid = oid; + this.db = db; + this.fields = fields || {}; + } + get namespace() { + return this.collection; + } + set namespace(value) { + this.collection = value; + } + toJSON() { + const o = Object.assign({ + $ref: this.collection, + $id: this.oid + }, this.fields); + if (this.db != null) + o.$db = this.db; + return o; + } + toExtendedJSON(options) { + options = options || {}; + let 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; + } + static fromExtendedJSON(doc) { + const copy = Object.assign({}, doc); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(doc.$ref, doc.$id, doc.$db, copy); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + 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}"` : ''})`; + } +} + +let wasm = undefined; +try { + wasm = new WebAssembly.Instance(new WebAssembly.Module(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 { +} +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; +const INT_CACHE = {}; +const UINT_CACHE = {}; +const MAX_INT64_STRING_LENGTH = 20; +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; +class Long extends BSONValue { + get _bsontype() { + return 'Long'; + } + get __isLong__() { + return true; + } + constructor(low = 0, high, unsigned) { + super(); + 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; + } + } + static fromBits(lowBits, highBits, unsigned) { + return new Long(lowBits, highBits, unsigned); + } + static fromInt(value, unsigned) { + 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; + } + } + static fromNumber(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); + } + static fromBigInt(value, unsigned) { + return Long.fromString(value.toString(), unsigned); + } + static fromString(str, unsigned, radix) { + if (str.length === 0) + throw new BSONError('empty string'); + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') + return Long.ZERO; + if (typeof unsigned === 'number') { + (radix = unsigned), (unsigned = false); + } + else { + unsigned = !!unsigned; + } + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + let p; + if ((p = str.indexOf('-')) > 0) + throw new BSONError('interior hyphen'); + else if (p === 0) { + return Long.fromString(str.substring(1), unsigned, radix).neg(); + } + 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; + } + static fromBytes(bytes, unsigned, le) { + return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned); + } + static fromBytesLE(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); + } + static fromBytesBE(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); + } + static isLong(value) { + return (value != null && + typeof value === 'object' && + '__isLong__' in value && + value.__isLong__ === true); + } + static fromValue(val, unsigned) { + if (typeof val === 'number') + return Long.fromNumber(val, unsigned); + if (typeof val === 'string') + return Long.fromString(val, unsigned); + return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned); + } + add(addend) { + if (!Long.isLong(addend)) + addend = Long.fromValue(addend); + 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); + } + and(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned); + } + compare(other) { + 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; + if (!this.unsigned) + return this.sub(other).isNegative() ? -1 : 1; + return other.high >>> 0 > this.high >>> 0 || + (other.high === this.high && other.low >>> 0 > this.low >>> 0) + ? -1 + : 1; + } + comp(other) { + return this.compare(other); + } + divide(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + if (divisor.isZero()) + throw new BSONError('division by zero'); + if (wasm) { + if (!this.unsigned && + this.high === -0x80000000 && + divisor.low === -1 && + divisor.high === -1) { + 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) { + if (this.eq(Long.MIN_VALUE)) { + if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE)) + return Long.MIN_VALUE; + else if (divisor.eq(Long.MIN_VALUE)) + return Long.ONE; + else { + 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 { + if (!divisor.unsigned) + divisor = divisor.toUnsigned(); + if (divisor.gt(this)) + return Long.UZERO; + if (divisor.gt(this.shru(1))) + return Long.UONE; + res = Long.UZERO; + } + rem = this; + while (rem.gte(divisor)) { + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); + const log2 = Math.ceil(Math.log(approx) / Math.LN2); + const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); + 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); + } + if (approxRes.isZero()) + approxRes = Long.ONE; + res = res.add(approxRes); + rem = rem.sub(approxRem); + } + return res; + } + div(divisor) { + return this.divide(divisor); + } + equals(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; + } + eq(other) { + return this.equals(other); + } + getHighBits() { + return this.high; + } + getHighBitsUnsigned() { + return this.high >>> 0; + } + getLowBits() { + return this.low; + } + getLowBitsUnsigned() { + return this.low >>> 0; + } + getNumBitsAbs() { + if (this.isNegative()) { + return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); + } + const val = this.high !== 0 ? this.high : this.low; + let bit; + for (bit = 31; bit > 0; bit--) + if ((val & (1 << bit)) !== 0) + break; + return this.high !== 0 ? bit + 33 : bit + 1; + } + greaterThan(other) { + return this.comp(other) > 0; + } + gt(other) { + return this.greaterThan(other); + } + greaterThanOrEqual(other) { + return this.comp(other) >= 0; + } + gte(other) { + return this.greaterThanOrEqual(other); + } + ge(other) { + return this.greaterThanOrEqual(other); + } + isEven() { + return (this.low & 1) === 0; + } + isNegative() { + return !this.unsigned && this.high < 0; + } + isOdd() { + return (this.low & 1) === 1; + } + isPositive() { + return this.unsigned || this.high >= 0; + } + isZero() { + return this.high === 0 && this.low === 0; + } + lessThan(other) { + return this.comp(other) < 0; + } + lt(other) { + return this.lessThan(other); + } + lessThanOrEqual(other) { + return this.comp(other) <= 0; + } + lte(other) { + return this.lessThanOrEqual(other); + } + modulo(divisor) { + if (!Long.isLong(divisor)) + divisor = Long.fromValue(divisor); + 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)); + } + mod(divisor) { + return this.modulo(divisor); + } + rem(divisor) { + return this.modulo(divisor); + } + multiply(multiplier) { + if (this.isZero()) + return Long.ZERO; + if (!Long.isLong(multiplier)) + multiplier = Long.fromValue(multiplier); + 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 (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24)) + return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned); + 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); + } + mul(multiplier) { + return this.multiply(multiplier); + } + negate() { + if (!this.unsigned && this.eq(Long.MIN_VALUE)) + return Long.MIN_VALUE; + return this.not().add(Long.ONE); + } + neg() { + return this.negate(); + } + not() { + return Long.fromBits(~this.low, ~this.high, this.unsigned); + } + notEquals(other) { + return !this.equals(other); + } + neq(other) { + return this.notEquals(other); + } + ne(other) { + return this.notEquals(other); + } + or(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned); + } + shiftLeft(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); + } + shl(numBits) { + return this.shiftLeft(numBits); + } + shiftRight(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); + } + shr(numBits) { + return this.shiftRight(numBits); + } + shiftRightUnsigned(numBits) { + 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); + } + } + shr_u(numBits) { + return this.shiftRightUnsigned(numBits); + } + shru(numBits) { + return this.shiftRightUnsigned(numBits); + } + subtract(subtrahend) { + if (!Long.isLong(subtrahend)) + subtrahend = Long.fromValue(subtrahend); + return this.add(subtrahend.neg()); + } + sub(subtrahend) { + return this.subtract(subtrahend); + } + toInt() { + return this.unsigned ? this.low >>> 0 : this.low; + } + toNumber() { + if (this.unsigned) + return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + toBigInt() { + return BigInt(this.toString()); + } + toBytes(le) { + return le ? this.toBytesLE() : this.toBytesBE(); + } + toBytesLE() { + 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 + ]; + } + toBytesBE() { + 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 + ]; + } + toSigned() { + if (!this.unsigned) + return this; + return Long.fromBits(this.low, this.high, false); + } + toString(radix) { + radix = radix || 10; + if (radix < 2 || 36 < radix) + throw new BSONError('radix'); + if (this.isZero()) + return '0'; + if (this.isNegative()) { + if (this.eq(Long.MIN_VALUE)) { + 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); + } + const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned); + let rem = this; + let result = ''; + 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; + } + } + } + toUnsigned() { + if (this.unsigned) + return this; + return Long.fromBits(this.low, this.high, true); + } + xor(other) { + if (!Long.isLong(other)) + other = Long.fromValue(other); + return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned); + } + eqz() { + return this.isZero(); + } + le(other) { + return this.lessThanOrEqual(other); + } + toExtendedJSON(options) { + if (options && options.relaxed) + return this.toNumber(); + return { $numberLong: this.toString() }; + } + static fromExtendedJSON(doc, options) { + const { useBigInt64 = false, relaxed = true } = { ...options }; + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} +Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL); +Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true); +Long.ZERO = Long.fromInt(0); +Long.UZERO = Long.fromInt(0, true); +Long.ONE = Long.fromInt(1); +Long.UONE = Long.fromInt(1, true); +Long.NEG_ONE = Long.fromInt(-1); +Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false); + +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; +const NAN_BUFFER = ByteUtils.fromNumberArray([ + 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([ + 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +].reverse()); +const EXPONENT_REGEX = /^([-+])?(\d+)?$/; +const COMBINATION_MASK = 0x1f; +const EXPONENT_MASK = 0x3fff; +const COMBINATION_INFINITY = 30; +const COMBINATION_NAN = 31; +function isDigit(value) { + return !isNaN(parseInt(value, 10)); +} +function divideu128(value) { + 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++) { + _rem = _rem.shiftLeft(32); + _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 }; +} +function multiply64x2(left, right) { + 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 { high: productHigh, low: productLow }; +} +function lessThan(left, right) { + const uhleft = left.high >>> 0; + const uhright = right.high >>> 0; + 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, message) { + throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`); +} +class Decimal128 extends BSONValue { + get _bsontype() { + return 'Decimal128'; + } + constructor(bytes) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } + else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } + else { + throw new BSONError('Decimal128 must take a Buffer or string'); + } + } + static fromString(representation) { + let isNegative = false; + let sawRadix = false; + let foundNonZero = false; + let significantDigits = 0; + let nDigitsRead = 0; + let nDigits = 0; + let radixPosition = 0; + let firstNonZero = 0; + const digits = [0]; + let nDigitsStored = 0; + let digitsInsert = 0; + let firstDigit = 0; + let lastDigit = 0; + let exponent = 0; + let i = 0; + let significandHigh = new Long(0, 0); + let significandLow = new Long(0, 0); + let biasedExponent = 0; + let index = 0; + if (representation.length >= 7000) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + const stringMatch = representation.match(PARSE_STRING_REGEXP); + const infMatch = representation.match(PARSE_INF_REGEXP); + const nanMatch = representation.match(PARSE_NAN_REGEXP); + if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) { + throw new BSONError('' + representation + ' not a valid Decimal128 string'); + } + if (stringMatch) { + const unsignedNumber = stringMatch[2]; + const e = stringMatch[4]; + const expSign = stringMatch[5]; + const expNumber = stringMatch[6]; + if (e && expNumber === undefined) + invalidErr(representation, 'missing exponent power'); + if (e && unsignedNumber === undefined) + invalidErr(representation, 'missing exponent base'); + if (e === undefined && (expSign || expNumber)) { + invalidErr(representation, 'missing e before exponent'); + } + } + if (representation[index] === '+' || representation[index] === '-') { + isNegative = representation[index++] === '-'; + } + if (!isDigit(representation[index]) && representation[index] !== '.') { + if (representation[index] === 'i' || representation[index] === 'I') { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + else if (representation[index] === 'N') { + return new Decimal128(NAN_BUFFER); + } + } + 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; + 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 BSONError('' + representation + ' not a valid Decimal128 string'); + if (representation[index] === 'e' || representation[index] === 'E') { + const match = representation.substr(++index).match(EXPONENT_REGEX); + if (!match || !match[2]) + return new Decimal128(NAN_BUFFER); + exponent = parseInt(match[0], 10); + index = index + match[0].length; + } + if (representation[index]) + return new Decimal128(NAN_BUFFER); + 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; + } + } + } + if (exponent <= radixPosition && radixPosition - exponent > 1 << 14) { + exponent = EXPONENT_MIN; + } + else { + exponent = exponent - radixPosition; + } + while (exponent > EXPONENT_MAX) { + lastDigit = lastDigit + 1; + if (lastDigit - firstDigit > MAX_DIGITS) { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + exponent = exponent - 1; + } + while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) { + if (lastDigit === 0 && significantDigits < nDigitsStored) { + exponent = EXPONENT_MIN; + significantDigits = 0; + break; + } + if (nDigitsStored < nDigits) { + nDigits = nDigits - 1; + } + else { + lastDigit = lastDigit - 1; + } + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + } + else { + const digitsString = digits.join(''); + if (digitsString.match(/^0+$/)) { + exponent = EXPONENT_MAX; + break; + } + invalidErr(representation, 'overflow'); + } + } + if (lastDigit - firstDigit + 1 < significantDigits) { + let endOfString = nDigitsRead; + if (sawRadix) { + firstNonZero = firstNonZero + 1; + endOfString = endOfString + 1; + } + 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; + if (dIdx === 0) { + if (exponent < EXPONENT_MAX) { + exponent = exponent + 1; + digits[dIdx] = 1; + } + else { + return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } + } + } + } + } + } + significandHigh = Long.fromNumber(0); + significandLow = Long.fromNumber(0); + 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)); + } + biasedExponent = exponent + EXPONENT_BIAS; + const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) }; + if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) { + 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; + if (isNegative) { + dec.high = dec.high.or(Long.fromString('9223372036854775808')); + } + const buffer = ByteUtils.allocate(16); + index = 0; + 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; + 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; + 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; + 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 new Decimal128(buffer); + } + toString() { + let biased_exponent; + let significand_digits = 0; + const significand = new Array(36); + for (let i = 0; i < significand.length; i++) + significand[i] = 0; + let index = 0; + let is_zero = false; + let significand_msb; + let significand128 = { parts: [0, 0, 0, 0] }; + let j, k; + const string = []; + index = 0; + const buffer = this.bytes; + const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + index = 0; + const dec = { + low: new Long(low, midl), + high: new Long(midh, high) + }; + if (dec.high.lessThan(Long.ZERO)) { + string.push('-'); + } + const combination = (high >> 26) & COMBINATION_MASK; + if (combination >> 3 === 3) { + 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; + } + const exponent = biased_exponent - EXPONENT_BIAS; + 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; + const result = divideu128(significand128); + significand128 = result.quotient; + least_digits = result.rem.low; + if (!least_digits) + continue; + for (j = 8; j >= 0; j--) { + significand[k * 9 + j] = least_digits % 10; + least_digits = Math.floor(least_digits / 10); + } + } + } + if (is_zero) { + significand_digits = 1; + significand[index] = 0; + } + else { + significand_digits = 36; + while (!significand[index]) { + significand_digits = significand_digits - 1; + index = index + 1; + } + } + const scientific_exponent = significand_digits - 1 + exponent; + if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) { + 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++]}`); + } + string.push('E'); + if (scientific_exponent > 0) { + string.push(`+${scientific_exponent}`); + } + else { + string.push(`${scientific_exponent}`); + } + } + else { + if (exponent >= 0) { + for (let i = 0; i < significand_digits; i++) { + string.push(`${significand[index++]}`); + } + } + else { + let radix_position = significand_digits + exponent; + if (radix_position > 0) { + for (let i = 0; i < radix_position; i++) { + string.push(`${significand[index++]}`); + } + } + else { + string.push('0'); + } + string.push('.'); + 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() { + return { $numberDecimal: this.toString() }; + } + toExtendedJSON() { + return { $numberDecimal: this.toString() }; + } + static fromExtendedJSON(doc) { + return Decimal128.fromString(doc.$numberDecimal); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Decimal128("${this.toString()}")`; + } +} + +class Double extends BSONValue { + get _bsontype() { + return 'Double'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value; + } + valueOf() { + return this.value; + } + toJSON() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toExtendedJSON(options) { + if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) { + return this.value; + } + if (Object.is(Math.sign(this.value), -0)) { + return { $numberDouble: '-0.0' }; + } + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + static fromExtendedJSON(doc, options) { + const doubleValue = parseFloat(doc.$numberDouble); + return options && options.relaxed ? doubleValue : new Double(doubleValue); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + const eJSON = this.toExtendedJSON(); + return `new Double(${eJSON.$numberDouble})`; + } +} + +class Int32 extends BSONValue { + get _bsontype() { + return 'Int32'; + } + constructor(value) { + super(); + if (value instanceof Number) { + value = value.valueOf(); + } + this.value = +value | 0; + } + valueOf() { + return this.value; + } + toString(radix) { + return this.value.toString(radix); + } + toJSON() { + return this.value; + } + toExtendedJSON(options) { + if (options && (options.relaxed || options.legacy)) + return this.value; + return { $numberInt: this.value.toString() }; + } + static fromExtendedJSON(doc, options) { + return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Int32(${this.valueOf()})`; + } +} + +class MaxKey extends BSONValue { + get _bsontype() { + return 'MaxKey'; + } + toExtendedJSON() { + return { $maxKey: 1 }; + } + static fromExtendedJSON() { + return new MaxKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MaxKey()'; + } +} + +class MinKey extends BSONValue { + get _bsontype() { + return 'MinKey'; + } + toExtendedJSON() { + return { $minKey: 1 }; + } + static fromExtendedJSON() { + return new MinKey(); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return 'new MinKey()'; + } +} + +const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$'); +let PROCESS_UNIQUE = null; +const kId = Symbol('id'); +class ObjectId extends BSONValue { + get _bsontype() { + return 'ObjectId'; + } + constructor(inputId) { + super(); + let workingId; + if (typeof inputId === 'object' && inputId && 'id' in inputId) { + if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) { + throw new BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } + else { + workingId = inputId.id; + } + } + else { + workingId = inputId; + } + if (workingId == null || typeof workingId === 'number') { + this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined); + } + else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) { + this[kId] = ByteUtils.toLocalBufferType(workingId); + } + else if (typeof workingId === 'string') { + if (workingId.length === 12) { + const bytes = ByteUtils.fromUTF8(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes'); + } + } + else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = ByteUtils.fromHex(workingId); + } + else { + throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer'); + } + } + else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + get id() { + return this[kId]; + } + set id(value) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + toHexString() { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + const hexString = ByteUtils.toHex(this.id); + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + return hexString; + } + static getInc() { + return (ObjectId.index = (ObjectId.index + 1) % 0xffffff); + } + static generate(time) { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocate(12); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.randomBytes(5); + } + 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]; + buffer[11] = inc & 0xff; + buffer[10] = (inc >> 8) & 0xff; + buffer[9] = (inc >> 16) & 0xff; + return buffer; + } + toString(encoding) { + if (encoding === 'base64') + return ByteUtils.toBase64(this.id); + if (encoding === 'hex') + return this.toHexString(); + return this.toHexString(); + } + toJSON() { + return this.toHexString(); + } + equals(otherId) { + if (otherId === undefined || otherId === null) { + return false; + } + if (otherId instanceof ObjectId) { + return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]); + } + if (typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id)) { + return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); + } + 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 ByteUtils.equals(ByteUtils.fromUTF8(otherId), 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; + } + getTimestamp() { + const timestamp = new Date(); + const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false); + timestamp.setTime(Math.floor(time) * 1000); + return timestamp; + } + static createPk() { + return new ObjectId(); + } + static createFromTime(time) { + const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + return new ObjectId(buffer); + } + static createFromHexString(hexString) { + if (typeof hexString === 'undefined' || (hexString != null && hexString.length !== 24)) { + throw new BSONError('Argument passed in must be a single String of 12 bytes or a string of 24 hex characters'); + } + return new ObjectId(ByteUtils.fromHex(hexString)); + } + static isValid(id) { + if (id == null) + return false; + try { + new ObjectId(id); + return true; + } + catch { + return false; + } + } + toExtendedJSON() { + if (this.toHexString) + return { $oid: this.toHexString() }; + return { $oid: this.toString('hex') }; + } + static fromExtendedJSON(doc) { + return new ObjectId(doc.$oid); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new ObjectId("${this.toHexString()}")`; + } +} +ObjectId.index = Math.floor(Math.random() * 0xffffff); + +function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) { + 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 (typeof object?.toBSON === 'function') { + object = object.toBSON(); + } + for (const key of Object.keys(object)) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined); + } + } + return totalLength; +} +function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) { + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + switch (typeof value) { + case 'string': + return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1; + case 'number': + if (Math.floor(value) === value && + value >= JS_INT_MIN && + value <= JS_INT_MAX) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } + else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if (value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } + else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } + else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength); + } + else if (value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1); + } + else if (value._bsontype === 'Code') { + if (value.scope != null && Object.keys(value.scope).length > 0) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1); + } + } + else if (value._bsontype === 'Binary') { + const binary = value; + if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4)); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1)); + } + } + else if (value._bsontype === 'Symbol') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 4 + + 1 + + 1); + } + else if (value._bsontype === 'DBRef') { + const ordered_values = Object.assign({ + $ref: value.collection, + $id: value.oid + }, value.fields); + if (value.db != null) { + ordered_values['$db'] = value.db; + } + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined)); + } + else if (value instanceof RegExp || isRegExp(value)) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1); + } + else if (value._bsontype === 'BSONRegExp') { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1); + } + else { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1); + } + case 'function': + if (serializeFunctions) { + return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1); + } + } + return 0; +} + +function alphabetize(str) { + return str.split('').sort().join(''); +} +class BSONRegExp extends BSONValue { + get _bsontype() { + return 'BSONRegExp'; + } + constructor(pattern, options) { + super(); + 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)}`); + } + 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) { + return options ? options.split('').sort().join('') : ''; + } + toExtendedJSON(options) { + options = options || {}; + if (options.legacy) { + return { $regex: this.pattern, $options: this.options }; + } + return { $regularExpression: { pattern: this.pattern, options: this.options } }; + } + static fromExtendedJSON(doc) { + if ('$regex' in doc) { + if (typeof doc.$regex !== 'string') { + 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 BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; + } +} + +class BSONSymbol extends BSONValue { + get _bsontype() { + return 'BSONSymbol'; + } + constructor(value) { + super(); + this.value = value; + } + valueOf() { + return this.value; + } + toString() { + return this.value; + } + inspect() { + return `new BSONSymbol("${this.value}")`; + } + toJSON() { + return this.value; + } + toExtendedJSON() { + return { $symbol: this.value }; + } + static fromExtendedJSON(doc) { + return new BSONSymbol(doc.$symbol); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } +} + +const LongWithoutOverridesClass = Long; +class Timestamp extends LongWithoutOverridesClass { + get _bsontype() { + return 'Timestamp'; + } + constructor(low) { + if (low == null) { + super(0, 0, true); + } + else if (typeof low === 'bigint') { + super(low, true); + } + else if (Long.isLong(low)) { + super(low.low, low.high, true); + } + else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + if (low.t < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (low.i < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (low.t > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max'); + } + if (low.i > 4294967295) { + throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max'); + } + super(low.i.valueOf(), low.t.valueOf(), true); + } + else { + throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }'); + } + } + toJSON() { + return { + $timestamp: this.toString() + }; + } + static fromInt(value) { + return new Timestamp(Long.fromInt(value, true)); + } + static fromNumber(value) { + return new Timestamp(Long.fromNumber(value, true)); + } + static fromBits(lowBits, highBits) { + return new Timestamp({ i: lowBits, t: highBits }); + } + static fromString(str, optRadix) { + return new Timestamp(Long.fromString(str, true, optRadix)); + } + toExtendedJSON() { + return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } }; + } + static fromExtendedJSON(doc) { + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`; + } +} +Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + +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; +function validateUtf8(bytes, start, end) { + 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; +} + +const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX); +const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN); +function internalDeserialize(buffer, options, isArray) { + options = options == null ? {} : options; + const index = options && options.index ? options.index : 0; + 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})`); + } + 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"); + } + return deserializeObject(buffer, index, options, isArray); +} +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; +function deserializeObject(buffer, index, options, isArray = false) { + const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw']; + const raw = options['raw'] == null ? false : options['raw']; + const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false; + const promoteBuffers = options.promoteBuffers ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + const validation = options.validation == null ? { utf8: true } : options.validation; + let globalUTFValidation = true; + let validationSetting; + const utf8KeysSet = new Set(); + 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]; + if (!utf8ValidationValues.every(item => item === validationSetting)) { + throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false'); + } + } + if (!globalUTFValidation) { + for (const key of Object.keys(utf8ValidatedKeys)) { + utf8KeysSet.add(key); + } + } + const startIndex = index; + if (buffer.length < 5) + throw new BSONError('corrupt bson message < 5 bytes long'); + const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24); + if (size < 5 || size > buffer.length) + throw new BSONError('corrupt bson message'); + const object = isArray ? [] : {}; + let arrayIndex = 0; + const done = false; + let isPossibleDBRef = isArray ? false : null; + const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength); + while (!done) { + const elementType = buffer[index++]; + if (elementType === 0) + break; + let i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.byteLength) + throw new BSONError('Bad BSON Document: illegal CString'); + const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer.subarray(index, i)); + let shouldValidateKey = true; + if (globalUTFValidation || utf8KeysSet.has(name)) { + shouldValidateKey = validationSetting; + } + else { + shouldValidateKey = !validationSetting; + } + if (isPossibleDBRef !== false && name[0] === '$') { + isPossibleDBRef = allowedDBRefKeys.test(name); + } + let value; + index = i + 1; + if (elementType === 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 === BSON_DATA_OID) { + const oid = ByteUtils.allocate(12); + oid.set(buffer.subarray(index, index + 12)); + value = new ObjectId(oid); + index = index + 12; + } + else if (elementType === BSON_DATA_INT && promoteValues === false) { + value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24)); + } + else if (elementType === BSON_DATA_INT) { + value = + buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + } + else if (elementType === BSON_DATA_NUMBER && promoteValues === false) { + value = new Double(dataview.getFloat64(index, true)); + index = index + 8; + } + else if (elementType === BSON_DATA_NUMBER) { + value = dataview.getFloat64(index, true); + index = index + 8; + } + else if (elementType === 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 === BSON_DATA_BOOLEAN) { + if (buffer[index] !== 0 && buffer[index] !== 1) + throw new BSONError('illegal boolean type value'); + value = buffer[index++] === 1; + } + else if (elementType === 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'); + 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 === 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; + const stopIndex = index + objectSize; + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, 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 === BSON_DATA_UNDEFINED) { + value = undefined; + } + else if (elementType === BSON_DATA_NULL) { + value = null; + } + else if (elementType === BSON_DATA_LONG) { + const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); + 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); + if (useBigInt64) { + value = dataview.getBigInt64(0, true); + } + else 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 === BSON_DATA_DECIMAL128) { + const bytes = ByteUtils.allocate(16); + bytes.set(buffer.subarray(index, index + 16), 0); + index = index + 16; + value = new Decimal128(bytes); + } + else if (elementType === BSON_DATA_BINARY) { + let binarySize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + const totalBinarySize = binarySize; + const subType = buffer[index++]; + if (binarySize < 0) + throw new BSONError('Negative binary type element size found'); + if (binarySize > buffer.byteLength) + throw new BSONError('Binary type size larger than document size'); + if (buffer['slice'] != null) { + 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 = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = value.toUUID(); + } + } + } + else { + const _buffer = ByteUtils.allocate(binarySize); + 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'); + } + for (i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + if (promoteBuffers && promoteValues) { + value = _buffer; + } + else if (subType === BSON_BINARY_SUBTYPE_UUID_NEW) { + value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + } + else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + } + } + index = index + binarySize; + } + else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + const optionsArray = new Array(regExpOptions.length); + 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 === BSON_DATA_REGEXP && bsonRegExp === true) { + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const source = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + i = index; + while (buffer[i] !== 0x00 && i < buffer.length) { + i++; + } + if (i >= buffer.length) + throw new BSONError('Bad BSON Document: illegal CString'); + const regExpOptions = ByteUtils.toUTF8(buffer.subarray(index, i)); + index = i + 1; + value = new BSONRegExp(source, regExpOptions); + } + else if (elementType === 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 === BSON_DATA_TIMESTAMP) { + const i = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + const t = buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + value = new Timestamp({ i, t }); + } + else if (elementType === BSON_DATA_MIN_KEY) { + value = new MinKey(); + } + else if (elementType === BSON_DATA_MAX_KEY) { + value = new MaxKey(); + } + else if (elementType === 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); + value = new Code(functionString); + index = index + stringSize; + } + else if (elementType === BSON_DATA_CODE_W_SCOPE) { + const totalSize = buffer[index++] | + (buffer[index++] << 8) | + (buffer[index++] << 16) | + (buffer[index++] << 24); + if (totalSize < 4 + 4 + 4 + 1) { + throw new BSONError('code_w_scope total size shorter minimum expected length'); + } + 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); + index = index + stringSize; + const _index = index; + const objectSize = buffer[index] | + (buffer[index + 1] << 8) | + (buffer[index + 2] << 16) | + (buffer[index + 3] << 24); + const scopeObject = deserializeObject(buffer, _index, options, false); + index = index + objectSize; + if (totalSize < 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too short, truncating scope'); + } + if (totalSize > 4 + 4 + objectSize + stringSize) { + throw new BSONError('code_w_scope total size is too long, clips outer document'); + } + value = new Code(functionString, scopeObject); + } + else if (elementType === BSON_DATA_DBPOINTER) { + 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'); + if (validation != null && validation.utf8) { + if (!validateUtf8(buffer, index, index + stringSize - 1)) { + throw new BSONError('Invalid UTF-8 string in BSON document'); + } + } + const namespace = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); + index = index + stringSize; + const oidBuffer = ByteUtils.allocate(12); + oidBuffer.set(buffer.subarray(index, index + 12), 0); + const oid = new ObjectId(oidBuffer); + index = index + 12; + 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; + } + } + if (size !== index - startIndex) { + if (isArray) + throw new BSONError('corrupt array bson'); + throw new BSONError('corrupt object bson'); + } + if (!isPossibleDBRef) + return object; + if (isDBRefLike(object)) { + const copy = Object.assign({}, object); + delete copy.$ref; + delete copy.$id; + delete copy.$db; + return new DBRef(object.$ref, object.$id, object.$db, copy); + } + return object; +} +function getValidatedString(buffer, start, end, shouldValidateUtf8) { + const value = ByteUtils.toUTF8(buffer.subarray(start, end)); + 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; +} + +const regexp = /\x00/; +const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']); +function serializeString(buffer, key, value, index) { + buffer[index++] = BSON_DATA_STRING; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + 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; + index = index + 4 + size; + buffer[index++] = 0; + return index; +} +const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); +const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); +const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); +function serializeNumber(buffer, key, value, index) { + const isNegativeZero = Object.is(value, -0); + const type = !isNegativeZero && + Number.isSafeInteger(value) && + value <= BSON_INT32_MAX && + value >= BSON_INT32_MIN + ? BSON_DATA_INT + : BSON_DATA_NUMBER; + if (type === BSON_DATA_INT) { + NUMBER_SPACE.setInt32(0, value, true); + } + else { + NUMBER_SPACE.setFloat64(0, value, true); + } + const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; + buffer[index++] = type; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + buffer.set(bytes, index); + index += bytes.byteLength; + return index; +} +function serializeBigInt(buffer, key, value, index) { + buffer[index++] = BSON_DATA_LONG; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index += numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setBigInt64(0, value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; + return index; +} +function serializeNull(buffer, key, _, index) { + buffer[index++] = BSON_DATA_NULL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeBoolean(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BOOLEAN; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer[index++] = value ? 1 : 0; + return index; +} +function serializeDate(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DATE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const dateInMilis = Long.fromNumber(value.getTime()); + const lowBits = dateInMilis.getLowBits(); + const highBits = dateInMilis.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + buffer[index++] = 0x00; + if (value.ignoreCase) + buffer[index++] = 0x69; + if (value.global) + buffer[index++] = 0x73; + if (value.multiline) + buffer[index++] = 0x6d; + buffer[index++] = 0x00; + return index; +} +function serializeBSONRegExp(buffer, key, value, index) { + buffer[index++] = BSON_DATA_REGEXP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.pattern.match(regexp) != null) { + throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + buffer[index++] = 0x00; + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + buffer[index++] = 0x00; + return index; +} +function serializeMinMax(buffer, key, value, index) { + if (value === null) { + buffer[index++] = BSON_DATA_NULL; + } + else if (value._bsontype === 'MinKey') { + buffer[index++] = BSON_DATA_MIN_KEY; + } + else { + buffer[index++] = BSON_DATA_MAX_KEY; + } + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} +function serializeObjectId(buffer, key, value, index) { + buffer[index++] = BSON_DATA_OID; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (isUint8Array(value.id)) { + buffer.set(value.id.subarray(0, 12), index); + } + else { + throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + return index + 12; +} +function serializeBuffer(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = value.length; + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT; + buffer.set(value, index); + index = index + size; + return index; +} +function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + path.add(value); + buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + path.delete(value); + return endIndex; +} +function serializeDecimal128(buffer, key, value, index) { + buffer[index++] = BSON_DATA_DECIMAL128; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} +function serializeLong(buffer, key, value, index) { + buffer[index++] = + value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const lowBits = value.getLowBits(); + const highBits = value.getHighBits(); + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + 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) { + value = value.valueOf(); + buffer[index++] = BSON_DATA_INT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + 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) { + buffer[index++] = BSON_DATA_NUMBER; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setFloat64(0, value.value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index = index + 8; + return index; +} +function serializeFunction(buffer, key, value, index) { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + return index; +} +function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) { + if (value.scope && typeof value.scope === 'object') { + buffer[index++] = BSON_DATA_CODE_W_SCOPE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + const functionString = value.code; + index = index + 4; + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + buffer[index + 4 + codeSize - 1] = 0; + index = index + codeSize + 4; + const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path); + index = endIndex - 1; + const totalSize = endIndex - startIndex; + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + buffer[index++] = 0; + } + else { + buffer[index++] = BSON_DATA_CODE; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const functionString = value.code.toString(); + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0; + } + return index; +} +function serializeBinary(buffer, key, value, index) { + buffer[index++] = BSON_DATA_BINARY; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const data = value.buffer; + let size = value.position; + 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; + buffer[index++] = value.sub_type; + 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; + } + buffer.set(data, index); + index = index + value.position; + return index; +} +function serializeSymbol(buffer, key, value, index) { + buffer[index++] = BSON_DATA_SYMBOL; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1; + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + index = index + 4 + size - 1; + buffer[index++] = 0x00; + return index; +} +function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) { + buffer[index++] = BSON_DATA_OBJECT; + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + let startIndex = index; + let output = { + $ref: value.collection || value.namespace, + $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, true, path); + const size = endIndex - startIndex; + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + return endIndex; +} +function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) { + if (path == null) { + if (object == null) { + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + buffer[4] = 0x00; + return 5; + } + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } + else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } + else if (isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object)) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + path = new Set(); + } + path.add(object); + let index = startingIndex + 4; + if (Array.isArray(object)) { + for (let i = 0; i < object.length; i++) { + const key = `${i}`; + let value = object[i]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + if (typeof value === 'string') { + index = serializeString(buffer, key, value, index); + } + else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } + else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } + else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } + else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } + else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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 (typeof value === 'object' && value._bsontype == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + else if (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 (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else if (object instanceof Map || isMap(object)) { + const iterator = object.entries(); + let done = false; + while (!done) { + const entry = iterator.next(); + done = !!entry.done; + if (done) + continue; + const key = entry.value[0]; + let value = entry.value[1]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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 === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + else { + if (typeof object?.toBSON === 'function') { + object = object.toBSON(); + if (object != null && typeof object !== 'object') { + throw new BSONError('toBSON function did not return an object'); + } + } + for (const key of Object.keys(object)) { + let value = object[key]; + if (typeof value?.toBSON === 'function') { + value = value.toBSON(); + } + const type = typeof value; + if (typeof key === 'string' && !ignoreKeys.has(key)) { + if (key.match(regexp) != null) { + throw new BSONError('key ' + key + ' must not contain null bytes'); + } + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } + else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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) { + if (ignoreUndefined === false) + index = serializeNull(buffer, key, value, index); + } + else if (value === null) { + index = serializeNull(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, path); + } + else if (typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } + 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, path); + } + else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } + else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } + else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } + else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } + 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + path.delete(object); + buffer[index++] = 0x00; + const size = index - startingIndex; + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +function isBSONType(value) { + return (value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string'); +} +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 +}; +function deserializeValue(value, options = {}) { + if (typeof value === 'number') { + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + if (options.relaxed || options.legacy) { + return value; + } + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + return Long.fromNumber(value); + } + } + return new Double(value); + } + if (value == null || typeof value !== 'object') + return value; + if (value.$undefined) + return null; + const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null); + 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; + 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; + }); + if (valid) + return DBRef.fromExtendedJSON(v); + } + return value; +} +function serializeArray(array, options) { + return array.map((v, index) => { + options.seenObjects.push({ propertyName: `index ${index}`, obj: null }); + try { + return serializeValue(v, options); + } + finally { + options.seenObjects.pop(); + } + }); +} +function getISOString(date) { + const isoStr = date.toISOString(); + return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z'; +} +function serializeValue(value, options) { + 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 BSONError('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(), 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))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + 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) => new Binary(o.value(), o.sub_type), + Code: (o) => new Code(o.code, o.scope), + DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields), + Decimal128: (o) => new Decimal128(o.bytes), + Double: (o) => new Double(o.value), + Int32: (o) => new Int32(o.value), + Long: (o) => Long.fromBits(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) => new ObjectId(o), + BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (o) => new BSONSymbol(o.value), + Timestamp: (o) => Timestamp.fromBits(o.low, o.high) +}; +function serializeDocument(doc, options) { + if (doc == null || typeof doc !== 'object') + throw new BSONError('not an object instance'); + const bsontype = doc._bsontype; + if (typeof bsontype === 'undefined') { + const _doc = {}; + for (const name of Object.keys(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 (doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) { + throw new BSONVersionError(); + } + else if (isBSONType(doc)) { + let outDoc = doc; + if (typeof outDoc.toExtendedJSON !== 'function') { + const mapper = BSON_TYPE_MAPPINGS[doc._bsontype]; + if (!mapper) { + throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype); + } + outDoc = mapper(outDoc); + } + 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); + } +} +function parse(text, options) { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + 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, ejsonOptions); + }); +} +function stringify(value, 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; + } + const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, { + seenObjects: [{ propertyName: '(root)', obj: null }] + }); + const doc = serializeValue(value, serializeOptions); + return JSON.stringify(doc, replacer, space); +} +function EJSONserialize(value, options) { + options = options || {}; + return JSON.parse(stringify(value, options)); +} +function EJSONdeserialize(ejson, options) { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} +const EJSON = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); + +const MAXSIZE = 1024 * 1024 * 17; +let buffer = ByteUtils.allocate(MAXSIZE); +function setInternalBufferSize(size) { + if (buffer.length < size) { + buffer = ByteUtils.allocate(size); + } +} +function serialize(object, 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; + if (buffer.length < minInternalBufferSize) { + buffer = ByteUtils.allocate(minInternalBufferSize); + } + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + const finishedBuffer = ByteUtils.allocate(serializationIndex); + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + return finishedBuffer; +} +function serializeWithBufferAndIndex(object, finalBuffer, 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; + const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null); + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + return startIndex + serializationIndex - 1; +} +function deserialize(buffer, options = {}) { + return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options); +} +function calculateObjectSize(object, options = {}) { + 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); +} +function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options); + const bufferData = ByteUtils.toLocalBufferType(data); + let index = startIndex; + for (let i = 0; i < numberOfDocuments; i++) { + const size = bufferData[index] | + (bufferData[index + 1] << 8) | + (bufferData[index + 2] << 16) | + (bufferData[index + 3] << 24); + internalOptions.index = index; + documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions); + index = index + size; + } + return index; +} + +var bson = /*#__PURE__*/Object.freeze({ + __proto__: null, + Code: Code, + BSONSymbol: BSONSymbol, + DBRef: DBRef, + Binary: Binary, + ObjectId: ObjectId, + UUID: UUID, + Long: Long, + Timestamp: Timestamp, + Double: Double, + Int32: Int32, + MinKey: MinKey, + MaxKey: MaxKey, + BSONRegExp: BSONRegExp, + Decimal128: Decimal128, + setInternalBufferSize: setInternalBufferSize, + serialize: serialize, + serializeWithBufferAndIndex: serializeWithBufferAndIndex, + deserialize: deserialize, + calculateObjectSize: calculateObjectSize, + deserializeStream: deserializeStream, + BSONValue: BSONValue, + BSONError: BSONError, + BSONVersionError: BSONVersionError, + BSONType: BSONType, + EJSON: EJSON +}); + +export { bson as BSON, BSONError, BSONRegExp, BSONSymbol, BSONType, BSONValue, BSONVersionError, Binary, Code, DBRef, Decimal128, Double, EJSON, Int32, Long, MaxKey, MinKey, ObjectId, Timestamp, UUID, calculateObjectSize, deserialize, deserializeStream, serialize, serializeWithBufferAndIndex, setInternalBufferSize }; +//# sourceMappingURL=bson.mjs.map diff --git a/2_PAC/node_modules/bson/lib/bson.mjs.map b/2_PAC/node_modules/bson/lib/bson.mjs.map new file mode 100644 index 00000000..42c30225 --- /dev/null +++ b/2_PAC/node_modules/bson/lib/bson.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.mjs","sources":["../src/constants.ts","../src/error.ts","../src/utils/node_byte_utils.ts","../src/utils/web_byte_utils.ts","../src/utils/byte_utils.ts","../src/uuid_utils.ts","../src/parser/utils.ts","../src/bson_value.ts","../src/binary.ts","../src/code.ts","../src/db_ref.ts","../src/long.ts","../src/decimal128.ts","../src/double.ts","../src/int_32.ts","../src/max_key.ts","../src/min_key.ts","../src/objectid.ts","../src/parser/calculate_size.ts","../src/regexp.ts","../src/symbol.ts","../src/timestamp.ts","../src/validate_utf8.ts","../src/parser/deserializer.ts","../src/parser/serializer.ts","../src/extended_json.ts","../src/bson.ts"],"sourcesContent":[null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["constants.JS_INT_MIN","constants.JS_INT_MAX","constants.BSON_INT32_MIN","constants.BSON_INT32_MAX","constants.BSON_MAJOR_VERSION","constants.BSON_DATA_STRING","constants.BSON_DATA_OID","constants.BSON_DATA_INT","constants.BSON_DATA_NUMBER","constants.BSON_DATA_DATE","constants.BSON_DATA_BOOLEAN","constants.BSON_DATA_OBJECT","constants.BSON_DATA_ARRAY","constants.BSON_DATA_UNDEFINED","constants.BSON_DATA_NULL","constants.BSON_DATA_LONG","constants.BSON_DATA_DECIMAL128","constants.BSON_DATA_BINARY","constants.BSON_BINARY_SUBTYPE_UUID_NEW","constants.BSON_DATA_REGEXP","constants.BSON_DATA_SYMBOL","constants.BSON_DATA_TIMESTAMP","constants.BSON_DATA_MIN_KEY","constants.BSON_DATA_MAX_KEY","constants.BSON_DATA_CODE","constants.BSON_DATA_CODE_W_SCOPE","constants.BSON_DATA_DBPOINTER","constants.BSON_BINARY_SUBTYPE_DEFAULT"],"mappings":"AACO,MAAM,kBAAkB,GAAG,CAAU,CAAC;AAGtC,MAAM,cAAc,GAAG,UAAU,CAAC;AAElC,MAAM,cAAc,GAAG,CAAC,UAAU,CAAC;AAEnC,MAAM,cAAc,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;AAE3C,MAAM,cAAc,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,E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KAAK,SAAS,GAAG,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC;IAEhF,OAAO,2BAA2B,CAAC,MAAM,EAAE,kBAAkB,EAAE,eAAe,CAAC,CAAC;AAClF,CAAC;AAce,SAAA,iBAAiB,CAC/B,IAA8B,EAC9B,UAAkB,EAClB,iBAAyB,EACzB,SAAqB,EACrB,aAAqB,EACrB,OAA2B,EAAA;AAE3B,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CACnC,EAAE,gCAAgC,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC,EAAE,EACpD,OAAO,CACR,CAAC;IACF,MAAM,UAAU,GAAG,SAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;IAErD,IAAI,KAAK,GAAG,UAAU,CAAC;IAEvB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,iBAAiB,EAAE,CAAC,EAAE,EAAE;AAE1C,QAAA,MAAM,IAAI,GACR,UAAU,CAAC,KAAK,CAAC;aAChB,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;aAC3B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;aAC5B,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAEhC,QAAA,eAAe,CAAC,KAAK,GAAG,KAAK,CAAC;AAE9B,QAAA,SAAS,CAAC,aAAa,GAAG,CAAC,CAAC,GAAG,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;AAEhF,QAAA,KAAK,GAAG,KAAK,GAAG,IAAI,CAAC;AACtB,KAAA;AAGD,IAAA,OAAO,KAAK,CAAC;AACf;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/2_PAC/node_modules/bson/package.json b/2_PAC/node_modules/bson/package.json new file mode 100644 index 00000000..07fea7b6 --- /dev/null +++ b/2_PAC/node_modules/bson/package.json @@ -0,0 +1,103 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "files": [ + "lib", + "src", + "bson.d.ts", + "etc/prepare.js" + ], + "types": "bson.d.ts", + "version": "5.0.0", + "author": { + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" + }, + "license": "Apache-2.0", + "contributors": [], + "repository": "mongodb/js-bson", + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" + }, + "devDependencies": { + "@istanbuljs/nyc-config-typescript": "^1.0.2", + "@microsoft/api-extractor": "^7.33.7", + "@rollup/plugin-node-resolve": "^15.0.1", + "@rollup/plugin-typescript": "^10.0.1", + "@types/chai": "^4.3.4", + "@types/mocha": "^10.0.1", + "@types/node": "^18.11.12", + "@types/sinon": "^10.0.13", + "@types/sinon-chai": "^3.2.9", + "@typescript-eslint/eslint-plugin": "^5.46.0", + "@typescript-eslint/parser": "^5.46.0", + "benchmark": "^2.1.4", + "chai": "^4.3.7", + "chalk": "^5.1.2", + "eslint": "^8.29.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-tsdoc": "^0.2.17", + "magic-string": "^0.27.0", + "mocha": "10.1.0", + "node-fetch": "^3.2.10", + "nyc": "^15.1.0", + "prettier": "^2.8.1", + "rimraf": "^3.0.2", + "rollup": "^3.7.1", + "sinon": "^15.0.0", + "sinon-chai": "^3.7.0", + "source-map-support": "^0.5.21", + "standard-version": "^9.5.0", + "ts-node": "^10.9.1", + "tsd": "^0.25.0", + "typescript": "^4.9.4", + "typescript-cached-transpile": "0.0.6", + "uuid": "^9.0.0", + "v8-profiler-next": "^1.9.0" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + }, + "config": { + "native": false + }, + "main": "./lib/bson.cjs", + "module": "./lib/bson.mjs", + "exports": { + "import": "./lib/bson.mjs", + "require": "./lib/bson.cjs", + "react-native": "./lib/bson.cjs", + "browser": "./lib/bson.mjs" + }, + "engines": { + "node": ">=14.20.1" + }, + "scripts": { + "pretest": "npm run build", + "test": "npm run check:node && npm run check:web", + "check:node": "WEB=false mocha test/node", + "check:tsd": "npm run build:dts && tsd", + "check:web": "WEB=true mocha test/node", + "build:ts": "node ./node_modules/typescript/bin/tsc", + "build:dts": "npm run build:ts && api-extractor run --typescript-compiler-folder node_modules/typescript --local && rimraf 'lib/**/*.d.ts*' lib/parser lib/utils", + "build:bundle": "rollup -c rollup.config.mjs", + "build": "npm run build:dts && npm run build:bundle", + "check:lint": "eslint -v && eslint --ext '.js,.ts' --max-warnings=0 src test && npm run build:dts && npm run check:tsd", + "format": "eslint --ext '.js,.ts' src test --fix", + "check:coverage": "nyc --check-coverage npm run check:node", + "prepare": "node etc/prepare.js", + "release": "standard-version -i HISTORY.md" + } +} diff --git a/2_PAC/node_modules/bson/src/binary.ts b/2_PAC/node_modules/bson/src/binary.ts new file mode 100644 index 00000000..f95de920 --- /dev/null +++ b/2_PAC/node_modules/bson/src/binary.ts @@ -0,0 +1,485 @@ +import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils'; +import { isUint8Array } from './parser/utils'; +import type { EJSONOptions } from './extended_json'; +import { BSONError } from './error'; +import { BSON_BINARY_SUBTYPE_UUID_NEW } from './constants'; +import { ByteUtils } from './utils/byte_utils'; +import { BSONValue } from './bson_value'; + +/** @public */ +export type BinarySequence = Uint8Array | 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 extends BSONValue { + get _bsontype(): 'Binary' { + return '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!: Uint8Array; + 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) { + super(); + if ( + !(buffer == null) && + !(typeof buffer === 'string') && + !ArrayBuffer.isView(buffer) && + !(buffer instanceof ArrayBuffer) && + !Array.isArray(buffer) + ) { + throw new BSONError( + '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 = ByteUtils.allocate(Binary.BUFFER_SIZE); + this.position = 0; + } else { + if (typeof buffer === 'string') { + // string + this.buffer = ByteUtils.fromISO88591(buffer); + } else if (Array.isArray(buffer)) { + // number[] + this.buffer = ByteUtils.fromNumberArray(buffer); + } else { + // Buffer | TypedArray | ArrayBuffer + this.buffer = ByteUtils.toLocalBufferType(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 | 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 BSONError('only accepts single character String'); + } else if (typeof byteValue !== 'number' && byteValue.length !== 1) + throw new BSONError('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 BSONError('only accepts number in a valid unsigned byte range 0-255'); + } + + if (this.buffer.byteLength > this.position) { + this.buffer[this.position++] = decodedByte; + } else { + const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length); + newSpace.set(this.buffer, 0); + this.buffer = newSpace; + 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.byteLength < offset + sequence.length) { + const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length); + newSpace.set(this.buffer, 0); + + // Assign the new buffer + this.buffer = newSpace; + } + + if (ArrayBuffer.isView(sequence)) { + this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset); + this.position = + offset + sequence.byteLength > this.position ? offset + sequence.length : this.position; + } else if (typeof sequence === 'string') { + const bytes = ByteUtils.fromISO88591(sequence); + this.buffer.set(bytes, offset); + 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); + } + // TODO(NODE-4361): remove binary string support, value(true) should be the default / only option here. + return ByteUtils.toISO88591(this.buffer.subarray(0, this.position)); + } + + /** the length of the binary sequence */ + length(): number { + return this.position; + } + + toJSON(): string { + return ByteUtils.toBase64(this.buffer); + } + + toString(encoding?: 'hex' | 'base64' | 'utf8' | 'utf-8'): string { + if (encoding === 'hex') return ByteUtils.toHex(this.buffer); + if (encoding === 'base64') return ByteUtils.toBase64(this.buffer); + if (encoding === 'utf8' || encoding === 'utf-8') return ByteUtils.toUTF8(this.buffer); + return ByteUtils.toUTF8(this.buffer); + } + + /** @internal */ + toExtendedJSON(options?: EJSONOptions): BinaryExtendedLegacy | BinaryExtended { + options = options || {}; + const base64String = ByteUtils.toBase64(this.buffer); + + 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: Uint8Array | 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 = ByteUtils.fromBase64(doc.$binary); + } else { + if (typeof doc.$binary !== 'string') { + type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0; + data = ByteUtils.fromBase64(doc.$binary.base64); + } + } + } else if ('$uuid' in doc) { + type = 4; + data = uuidHexStringToBuffer(doc.$uuid); + } + if (!data) { + throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`); + } + return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Binary(Buffer.from("${ByteUtils.toHex(this.buffer)}", "hex"), ${this.sub_type})`; + } +} + +/** @public */ +export type UUIDExtended = { + $uuid: string; +}; +const UUID_BYTE_LENGTH = 16; + +/** + * A class representation of the BSON UUID type. + * @public + */ +export class UUID extends Binary { + static cacheHexString: boolean; + + /** 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 | Uint8Array | UUID) { + let bytes: Uint8Array; + let hexStr; + if (input == null) { + bytes = UUID.generate(); + } else if (input instanceof UUID) { + bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer)); + hexStr = input.__id; + } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) { + bytes = ByteUtils.toLocalBufferType(input); + } else if (typeof input === 'string') { + bytes = uuidHexStringToBuffer(input); + } else { + throw new BSONError( + '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).' + ); + } + super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW); + this.__id = hexStr; + } + + /** + * The UUID bytes + * @readonly + */ + get id(): Uint8Array { + return this.buffer; + } + + set id(value: Uint8Array) { + this.buffer = value; + + if (UUID.cacheHexString) { + this.__id = bufferToUuidHexString(value); + } + } + + /** + * 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?: 'hex' | 'base64'): string { + if (encoding === 'hex') return ByteUtils.toHex(this.id); + if (encoding === 'base64') return ByteUtils.toBase64(this.id); + return 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 | Uint8Array | UUID): boolean { + if (!otherId) { + return false; + } + + if (otherId instanceof UUID) { + return ByteUtils.equals(otherId.id, this.id); + } + + try { + return ByteUtils.equals(new UUID(otherId).id, 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(): Uint8Array { + const bytes = ByteUtils.randomBytes(UUID_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 bytes; + } + + /** + * Checks if a value is a valid bson UUID + * @param input - UUID, string or Buffer to validate. + */ + static isValid(input: string | Uint8Array | 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.byteLength !== UUID_BYTE_LENGTH) { + return false; + } + + return (input[6] & 0xf0) === 0x40 && (input[8] & 0x80) === 0x80; + } + + 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()}")`; + } +} diff --git a/2_PAC/node_modules/bson/src/bson.ts b/2_PAC/node_modules/bson/src/bson.ts new file mode 100644 index 00000000..8ec644bf --- /dev/null +++ b/2_PAC/node_modules/bson/src/bson.ts @@ -0,0 +1,250 @@ +import { Binary, UUID } from './binary'; +import { Code } from './code'; +import { DBRef } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { Int32 } from './int_32'; +import { Long } from './long'; +import { MaxKey } from './max_key'; +import { MinKey } from './min_key'; +import { ObjectId } from './objectid'; +import { internalCalculateObjectSize } from './parser/calculate_size'; +// Parts of the parser +import { internalDeserialize, DeserializeOptions } from './parser/deserializer'; +import { serializeInto, SerializeOptions } from './parser/serializer'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; +import { ByteUtils } from './utils/byte_utils'; +export type { UUIDExtended, BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary'; +export type { CodeExtended } from './code'; +export type { DBRefLike } from './db_ref'; +export type { Decimal128Extended } from './decimal128'; +export type { DoubleExtended } from './double'; +export type { EJSONOptions } from './extended_json'; +export type { Int32Extended } from './int_32'; +export type { LongExtended } from './long'; +export type { MaxKeyExtended } from './max_key'; +export type { MinKeyExtended } from './min_key'; +export type { ObjectIdExtended, ObjectIdLike } from './objectid'; +export type { BSONRegExpExtended, BSONRegExpExtendedLegacy } from './regexp'; +export type { BSONSymbolExtended } from './symbol'; +export type { LongWithoutOverrides, TimestampExtended, TimestampOverrides } from './timestamp'; +export type { LongWithoutOverridesClass } from './timestamp'; +export type { SerializeOptions, DeserializeOptions }; + +export { + Code, + BSONSymbol, + DBRef, + Binary, + ObjectId, + UUID, + Long, + Timestamp, + Double, + Int32, + MinKey, + MaxKey, + BSONRegExp, + Decimal128 +}; +export { BSONValue } from './bson_value'; +export { BSONError, BSONVersionError } from './error'; +export { BSONType } from './constants'; +export { EJSON } from './extended_json'; + +/** @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 = ByteUtils.allocate(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 = ByteUtils.allocate(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 = {}): Uint8Array { + // 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 = ByteUtils.allocate(minInternalBufferSize); + } + + // Attempt to serialize + const serializationIndex = serializeInto( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + null + ); + + // Create the final buffer + const finishedBuffer = ByteUtils.allocate(serializationIndex); + + // Copy into the finished buffer + finishedBuffer.set(buffer.subarray(0, serializationIndex), 0); + + // 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: Uint8Array, + 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 = serializeInto( + buffer, + object, + checkKeys, + 0, + 0, + serializeFunctions, + ignoreUndefined, + null + ); + + finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex); + + // 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: Uint8Array, options: DeserializeOptions = {}): Document { + return internalDeserialize(ByteUtils.toLocalBufferType(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: Uint8Array | ArrayBuffer, + startIndex: number, + numberOfDocuments: number, + documents: Document[], + docStartIndex: number, + options: DeserializeOptions +): number { + const internalOptions = Object.assign( + { allowObjectSmallerThanBufferSize: true, index: 0 }, + options + ); + const bufferData = ByteUtils.toLocalBufferType(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; +} diff --git a/2_PAC/node_modules/bson/src/bson_value.ts b/2_PAC/node_modules/bson/src/bson_value.ts new file mode 100644 index 00000000..b36266e0 --- /dev/null +++ b/2_PAC/node_modules/bson/src/bson_value.ts @@ -0,0 +1,18 @@ +import { BSON_MAJOR_VERSION } from './constants'; + +/** @public */ +export abstract class BSONValue { + /** @public */ + public abstract get _bsontype(): string; + + /** @internal */ + get [Symbol.for('@@mdb.bson.version')](): typeof BSON_MAJOR_VERSION { + return BSON_MAJOR_VERSION; + } + + /** @public */ + public abstract inspect(): string; + + /** @internal */ + abstract toExtendedJSON(): unknown; +} diff --git a/2_PAC/node_modules/bson/src/code.ts b/2_PAC/node_modules/bson/src/code.ts new file mode 100644 index 00000000..48889f56 --- /dev/null +++ b/2_PAC/node_modules/bson/src/code.ts @@ -0,0 +1,69 @@ +import type { Document } from './bson'; +import { BSONValue } from './bson_value'; + +/** @public */ +export interface CodeExtended { + $code: string; + $scope?: Document; +} + +/** + * A class representation of the BSON Code type. + * @public + * @category BSONType + */ +export class Code extends BSONValue { + get _bsontype(): 'Code' { + return 'Code'; + } + + code: string; + + // a code instance having a null scope is what determines whether + // it is BSONType 0x0D (just code) / 0x0F (code with scope) + scope: Document | null; + + /** + * @param code - a string or function. + * @param scope - an optional scope for the function. + */ + constructor(code: string | Function, scope?: Document | null) { + super(); + this.code = code.toString(); + this.scope = scope ?? null; + } + + toJSON(): { code: string; scope?: Document } { + if (this.scope != null) { + return { code: this.code, scope: this.scope }; + } + + return { code: this.code }; + } + + /** @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 != null ? `, ${JSON.stringify(codeJson.scope)}` : '' + })`; + } +} diff --git a/2_PAC/node_modules/bson/src/constants.ts b/2_PAC/node_modules/bson/src/constants.ts new file mode 100644 index 00000000..50a3d42e --- /dev/null +++ b/2_PAC/node_modules/bson/src/constants.ts @@ -0,0 +1,141 @@ +/** @internal */ +export const BSON_MAJOR_VERSION = 5 as const; + +/** @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; + +/** @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]; diff --git a/2_PAC/node_modules/bson/src/db_ref.ts b/2_PAC/node_modules/bson/src/db_ref.ts new file mode 100644 index 00000000..ebdcb61b --- /dev/null +++ b/2_PAC/node_modules/bson/src/db_ref.ts @@ -0,0 +1,127 @@ +import type { Document } from './bson'; +import { BSONValue } from './bson_value'; +import type { EJSONOptions } from './extended_json'; +import type { ObjectId } from './objectid'; + +/** @public */ +export interface DBRefLike { + $ref: string; + $id: ObjectId; + $db?: string; +} + +/** @internal */ +export function isDBRefLike(value: unknown): value is DBRefLike { + return ( + value != null && + typeof value === 'object' && + '$id' in value && + value.$id != null && + '$ref' in value && + typeof value.$ref === 'string' && + // If '$db' is defined it MUST be a string, otherwise it should be absent + (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')) + ); +} + +/** + * A class representation of the BSON DBRef type. + * @public + * @category BSONType + */ +export class DBRef extends BSONValue { + get _bsontype(): 'DBRef' { + return '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) { + super(); + // 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}"` : '' + })`; + } +} diff --git a/2_PAC/node_modules/bson/src/decimal128.ts b/2_PAC/node_modules/bson/src/decimal128.ts new file mode 100644 index 00000000..55543a76 --- /dev/null +++ b/2_PAC/node_modules/bson/src/decimal128.ts @@ -0,0 +1,777 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import { Long } from './long'; +import { isUint8Array } from './parser/utils'; +import { ByteUtils } from './utils/byte_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 = ByteUtils.fromNumberArray( + [ + 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 = ByteUtils.fromNumberArray( + [ + 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + ].reverse() +); +const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray( + [ + 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 BSONError(`"${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 extends BSONValue { + get _bsontype(): 'Decimal128' { + return 'Decimal128'; + } + + readonly bytes!: Uint8Array; + + /** + * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order, + * or a string representation as returned by .toString() + */ + constructor(bytes: Uint8Array | string) { + super(); + if (typeof bytes === 'string') { + this.bytes = Decimal128.fromString(bytes).bytes; + } else if (isUint8Array(bytes)) { + if (bytes.byteLength !== 16) { + throw new BSONError('Decimal128 must take a Buffer of 16 bytes'); + } + this.bytes = bytes; + } else { + throw new BSONError('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 BSONError('' + 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 BSONError('' + 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(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER); + } else if (representation[index] === 'N') { + return new Decimal128(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 BSONError('' + 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(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(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(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 = ByteUtils.allocate(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()}")`; + } +} diff --git a/2_PAC/node_modules/bson/src/double.ts b/2_PAC/node_modules/bson/src/double.ts new file mode 100644 index 00000000..45815360 --- /dev/null +++ b/2_PAC/node_modules/bson/src/double.ts @@ -0,0 +1,83 @@ +import { BSONValue } from './bson_value'; +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 extends BSONValue { + get _bsontype(): 'Double' { + return 'Double'; + } + + value!: number; + /** + * Create a Double type + * + * @param value - the number we want to represent as a double. + */ + constructor(value: number) { + super(); + 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; + } + + if (Object.is(Math.sign(this.value), -0)) { + // 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 + return { $numberDouble: '-0.0' }; + } + + return { + $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString() + }; + } + + /** @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})`; + } +} diff --git a/2_PAC/node_modules/bson/src/error.ts b/2_PAC/node_modules/bson/src/error.ts new file mode 100644 index 00000000..b01cde53 --- /dev/null +++ b/2_PAC/node_modules/bson/src/error.ts @@ -0,0 +1,60 @@ +import { BSON_MAJOR_VERSION } from './constants'; + +/** + * @public + * `BSONError` objects are thrown when runtime errors occur. + */ +export class BSONError extends Error { + /** + * @internal + * The underlying algorithm for isBSONError may change to improve how strict it is + * about determining if an input is a BSONError. But it must remain backwards compatible + * with previous minors & patches of the current major version. + */ + protected get bsonError(): true { + return true; + } + + override get name(): string { + return 'BSONError'; + } + + constructor(message: string) { + super(message); + } + + /** + * @public + * + * All errors thrown from the BSON library inherit from `BSONError`. + * This method can assist with determining if an error originates from the BSON library + * even if it does not pass an `instanceof` check against this class' constructor. + * + * @param value - any javascript value that needs type checking + */ + public static isBSONError(value: unknown): value is BSONError { + return ( + value != null && + typeof value === 'object' && + 'bsonError' in value && + value.bsonError === true && + // Do not access the following properties, just check existence + 'name' in value && + 'message' in value && + 'stack' in value + ); + } +} + +/** @public */ +export class BSONVersionError extends BSONError { + get name(): 'BSONVersionError' { + return 'BSONVersionError'; + } + + constructor() { + super( + `Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.0 or later` + ); + } +} diff --git a/2_PAC/node_modules/bson/src/extended_json.ts b/2_PAC/node_modules/bson/src/extended_json.ts new file mode 100644 index 00000000..8d79e355 --- /dev/null +++ b/2_PAC/node_modules/bson/src/extended_json.ts @@ -0,0 +1,488 @@ +import { Binary } from './binary'; +import type { Document } from './bson'; +import { Code } from './code'; +import { + BSON_INT32_MAX, + BSON_INT32_MIN, + BSON_INT64_MAX, + BSON_INT64_MIN, + BSON_MAJOR_VERSION +} from './constants'; +import { DBRef, isDBRefLike } from './db_ref'; +import { Decimal128 } from './decimal128'; +import { Double } from './double'; +import { BSONError, BSONVersionError } 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, isRegExp } from './parser/utils'; +import { BSONRegExp } from './regexp'; +import { BSONSymbol } from './symbol'; +import { Timestamp } from './timestamp'; + +/** @public */ +export type EJSONOptions = { + /** 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; + /** Enable native bigint support */ + useBigInt64?: boolean; +}; + +/** @internal */ +type BSONType = + | Binary + | Code + | DBRef + | Decimal128 + | Double + | Int32 + | Long + | MaxKey + | MinKey + | ObjectId + | BSONRegExp + | BSONSymbol + | Timestamp; + +function isBSONType(value: unknown): value is BSONType { + return ( + value != null && + typeof value === 'object' && + '_bsontype' in value && + typeof value._bsontype === 'string' + ); +} + +// 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: EJSONOptions = {}) { + if (typeof value === 'number') { + // TODO(NODE-4377): EJSON js number handling diverges from BSON + const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN; + const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN; + + if (options.relaxed || options.legacy) { + return value; + } + + if (Number.isInteger(value) && !Object.is(value, -0)) { + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (in32BitRange) { + return new Int32(value); + } + if (in64BitRange) { + if (options.useBigInt64) { + return BigInt(value); + } + 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 = EJSONOptions & { + 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 BSONError( + '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))) { + if (Number.isInteger(value) && !Object.is(value, -0)) { + // interpret as being of the smallest BSON integer type that can represent the number exactly + if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) { + return { $numberInt: value.toString() }; + } + if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) { + // TODO(NODE-4377): EJSON js number handling diverges from BSON + return { $numberLong: value.toString() }; + } + } + return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() }; + } + + if (typeof value === 'bigint') { + if (!options.relaxed) { + return { $numberLong: BigInt.asIntN(64, value).toString() }; + } + return Number(BigInt.asIntN(64, value)); + } + + 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), + BSONRegExp: (o: BSONRegExp) => new BSONRegExp(o.pattern, o.options), + BSONSymbol: (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 of Object.keys(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 ( + doc != null && + typeof doc === 'object' && + typeof doc._bsontype === 'string' && + doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } 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 BSONError('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); + } +} + +/** + * 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)); + * ``` + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function parse(text: string, options?: EJSONOptions): any { + const ejsonOptions = { + useBigInt64: options?.useBigInt64 ?? false, + relaxed: options?.relaxed ?? true, + legacy: options?.legacy ?? false + }; + 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, ejsonOptions); + }); +} + +/** + * 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( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + value: any, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSONOptions, + space?: string | number, + options?: EJSONOptions +): 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 + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function EJSONserialize(value: any, options?: EJSONOptions): 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 + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function EJSONdeserialize(ejson: Document, options?: EJSONOptions): any { + options = options || {}; + return parse(JSON.stringify(ejson), options); +} + +/** @public */ +const EJSON: { + parse: typeof parse; + stringify: typeof stringify; + serialize: typeof EJSONserialize; + deserialize: typeof EJSONdeserialize; +} = Object.create(null); +EJSON.parse = parse; +EJSON.stringify = stringify; +EJSON.serialize = EJSONserialize; +EJSON.deserialize = EJSONdeserialize; +Object.freeze(EJSON); +export { EJSON }; diff --git a/2_PAC/node_modules/bson/src/index.ts b/2_PAC/node_modules/bson/src/index.ts new file mode 100644 index 00000000..5ef41575 --- /dev/null +++ b/2_PAC/node_modules/bson/src/index.ts @@ -0,0 +1,19 @@ +import * as BSON from './bson'; + +// Export all named properties from BSON to support +// import { ObjectId, serialize } from 'bson'; +// const { ObjectId, serialize } = require('bson'); +export * from './bson'; + +// Export BSON as a namespace to support: +// import { BSON } from 'bson'; +// const { BSON } = require('bson'); +export { BSON }; + +// BSON does **NOT** have a default export + +// The following will crash in es module environments +// import BSON from 'bson'; + +// The following will work as expected, BSON as a namespace of all the APIs (BSON.ObjectId, BSON.serialize) +// const BSON = require('bson'); diff --git a/2_PAC/node_modules/bson/src/int_32.ts b/2_PAC/node_modules/bson/src/int_32.ts new file mode 100644 index 00000000..c74f3c82 --- /dev/null +++ b/2_PAC/node_modules/bson/src/int_32.ts @@ -0,0 +1,70 @@ +import { BSONValue } from './bson_value'; +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 extends BSONValue { + get _bsontype(): 'Int32' { + return 'Int32'; + } + + value!: number; + /** + * Create an Int32 type + * + * @param value - the number we want to represent as an int32. + */ + constructor(value: number | string) { + super(); + 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()})`; + } +} diff --git a/2_PAC/node_modules/bson/src/long.ts b/2_PAC/node_modules/bson/src/long.ts new file mode 100644 index 00000000..609f9392 --- /dev/null +++ b/2_PAC/node_modules/bson/src/long.ts @@ -0,0 +1,1064 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import type { EJSONOptions } from './extended_json'; +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 } = {}; + +const MAX_INT64_STRING_LENGTH = 20; + +const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/; + +/** @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 extends BSONValue { + get _bsontype(): 'Long' { + return 'Long'; + } + + /** An indicator used to reliably determine if an object is a Long or not. */ + get __isLong__(): boolean { + return 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) { + super(); + 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; + } + } + + 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 new BSONError('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 new BSONError('radix'); + + let p; + if ((p = str.indexOf('-')) > 0) throw new BSONError('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 ( + value != null && + typeof value === 'object' && + '__isLong__' in 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 new BSONError('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 new BSONError('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 | bigint { + const { useBigInt64 = false, relaxed = true } = { ...options }; + + if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) { + throw new BSONError('$numberLong string is too long'); + } + + if (!DECIMAL_REG_EX.test(doc.$numberLong)) { + throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`); + } + + if (useBigInt64) { + const bigIntResult = BigInt(doc.$numberLong); + return BigInt.asIntN(64, bigIntResult); + } + + const longResult = Long.fromString(doc.$numberLong); + if (relaxed) { + return longResult.toNumber(); + } + return longResult; + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`; + } +} diff --git a/2_PAC/node_modules/bson/src/max_key.ts b/2_PAC/node_modules/bson/src/max_key.ts new file mode 100644 index 00000000..2894f58b --- /dev/null +++ b/2_PAC/node_modules/bson/src/max_key.ts @@ -0,0 +1,36 @@ +import { BSONValue } from './bson_value'; + +/** @public */ +export interface MaxKeyExtended { + $maxKey: 1; +} + +/** + * A class representation of the BSON MaxKey type. + * @public + * @category BSONType + */ +export class MaxKey extends BSONValue { + get _bsontype(): 'MaxKey' { + return '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()'; + } +} diff --git a/2_PAC/node_modules/bson/src/min_key.ts b/2_PAC/node_modules/bson/src/min_key.ts new file mode 100644 index 00000000..f72cf26b --- /dev/null +++ b/2_PAC/node_modules/bson/src/min_key.ts @@ -0,0 +1,36 @@ +import { BSONValue } from './bson_value'; + +/** @public */ +export interface MinKeyExtended { + $minKey: 1; +} + +/** + * A class representation of the BSON MinKey type. + * @public + * @category BSONType + */ +export class MinKey extends BSONValue { + get _bsontype(): 'MinKey' { + return '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()'; + } +} diff --git a/2_PAC/node_modules/bson/src/objectid.ts b/2_PAC/node_modules/bson/src/objectid.ts new file mode 100644 index 00000000..a0358208 --- /dev/null +++ b/2_PAC/node_modules/bson/src/objectid.ts @@ -0,0 +1,317 @@ +import { BSONValue } from './bson_value'; +import { BSONError } from './error'; +import { isUint8Array } from './parser/utils'; +import { BSONDataView, ByteUtils } from './utils/byte_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 | Uint8Array; + __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 extends BSONValue { + get _bsontype(): 'ObjectId' { + return 'ObjectId'; + } + + /** @internal */ + private static index = Math.floor(Math.random() * 0xffffff); + + static cacheHexString: boolean; + + /** ObjectId Bytes @internal */ + private [kId]!: Uint8Array; + /** 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 | Uint8Array) { + super(); + // 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 BSONError('Argument passed in must have an id that is of type string or Buffer'); + } + if ('toHexString' in inputId && typeof inputId.toHexString === 'function') { + workingId = ByteUtils.fromHex(inputId.toHexString()); + } 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] = ByteUtils.toLocalBufferType(workingId); + } else if (typeof workingId === 'string') { + if (workingId.length === 12) { + // TODO(NODE-4361): Remove string of length 12 support + const bytes = ByteUtils.fromUTF8(workingId); + if (bytes.byteLength === 12) { + this[kId] = bytes; + } else { + throw new BSONError('Argument passed in must be a string of 12 bytes'); + } + } else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) { + this[kId] = ByteUtils.fromHex(workingId); + } else { + throw new BSONError( + 'Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer' + ); + } + } else { + throw new BSONError('Argument passed in does not match the accepted types'); + } + // If we are caching the hex string + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(this.id); + } + } + + /** + * The ObjectId bytes + * @readonly + */ + get id(): Uint8Array { + return this[kId]; + } + + set id(value: Uint8Array) { + this[kId] = value; + if (ObjectId.cacheHexString) { + this.__id = ByteUtils.toHex(value); + } + } + + /** Returns the ObjectId id as a 24 character hex string representation */ + toHexString(): string { + if (ObjectId.cacheHexString && this.__id) { + return this.__id; + } + + const hexString = ByteUtils.toHex(this.id); + + if (ObjectId.cacheHexString && !this.__id) { + this.__id = hexString; + } + + return hexString; + } + + /** + * Update the ObjectId index + * @internal + */ + private 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): Uint8Array { + if ('number' !== typeof time) { + time = Math.floor(Date.now() / 1000); + } + + const inc = ObjectId.getInc(); + const buffer = ByteUtils.allocate(12); + + // 4-byte timestamp + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + + // set PROCESS_UNIQUE if yet not initialized + if (PROCESS_UNIQUE === null) { + PROCESS_UNIQUE = ByteUtils.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, unless encoding is provided. + * @param encoding - hex or base64 + */ + toString(encoding?: 'hex' | 'base64'): string { + // Is the id a buffer then use the buffer toString method to return the format + if (encoding === 'base64') return ByteUtils.toBase64(this.id); + if (encoding === 'hex') return this.toHexString(); + 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] && ByteUtils.equals(this[kId], otherId[kId]); + } + + if ( + typeof otherId === 'string' && + ObjectId.isValid(otherId) && + otherId.length === 12 && + isUint8Array(this.id) + ) { + return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId)); + } + + 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 ByteUtils.equals(ByteUtils.fromUTF8(otherId), 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 = BSONDataView.fromUint8Array(this.id).getUint32(0, false); + 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 = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + // Encode time into first 4 bytes + BSONDataView.fromUint8Array(buffer).setUint32(0, time, false); + // 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 BSONError( + 'Argument passed in must be a single String of 12 bytes or a string of 24 hex characters' + ); + } + + return new ObjectId(ByteUtils.fromHex(hexString)); + } + + /** + * Checks if a value is a valid bson ObjectId + * + * @param id - ObjectId instance to validate. + */ + static isValid(id: string | number | ObjectId | ObjectIdLike | 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()}")`; + } +} diff --git a/2_PAC/node_modules/bson/src/parser/calculate_size.ts b/2_PAC/node_modules/bson/src/parser/calculate_size.ts new file mode 100644 index 00000000..fd1e4a02 --- /dev/null +++ b/2_PAC/node_modules/bson/src/parser/calculate_size.ts @@ -0,0 +1,211 @@ +import { Binary } from '../binary'; +import type { Document } from '../bson'; +import { BSONVersionError } from '../error'; +import * as constants from '../constants'; +import { ByteUtils } from '../utils/byte_utils'; +import { isAnyArrayBuffer, isDate, isRegExp } from './utils'; + +export function internalCalculateObjectSize( + 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 of Object.keys(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 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 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 ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1); + } else { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + } else { + // 64 bit + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } + case 'undefined': + if (isArray || !ignoreUndefined) + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + return 0; + case 'boolean': + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1); + case 'object': + if ( + value != null && + typeof value._bsontype === 'string' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1; + } else if (value._bsontype === 'ObjectId') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1); + } else if (value instanceof Date || isDate(value)) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } else if ( + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer || + isAnyArrayBuffer(value) + ) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength + ); + } else if ( + value._bsontype === 'Long' || + value._bsontype === 'Double' || + value._bsontype === 'Timestamp' + ) { + return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1); + } else if (value._bsontype === 'Decimal128') { + return (name != null ? ByteUtils.utf8ByteLength(name) + 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 ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 1 + + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined) + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.code.toString()) + + 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 ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + (binary.position + 1 + 4 + 1 + 4) + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1) + ); + } + } else if (value._bsontype === 'Symbol') { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + ByteUtils.utf8ByteLength(value.value) + + 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 ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined) + ); + } else if (value instanceof RegExp || isRegExp(value)) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.source) + + 1 + + (value.global ? 1 : 0) + + (value.ignoreCase ? 1 : 0) + + (value.multiline ? 1 : 0) + + 1 + ); + } else if (value._bsontype === 'BSONRegExp') { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + ByteUtils.utf8ByteLength(value.pattern) + + 1 + + ByteUtils.utf8ByteLength(value.options) + + 1 + ); + } else { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + + 1 + ); + } + case 'function': + if (serializeFunctions) { + return ( + (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + + 1 + + 4 + + ByteUtils.utf8ByteLength(value.toString()) + + 1 + ); + } + } + + return 0; +} diff --git a/2_PAC/node_modules/bson/src/parser/deserializer.ts b/2_PAC/node_modules/bson/src/parser/deserializer.ts new file mode 100644 index 00000000..50d7a8d8 --- /dev/null +++ b/2_PAC/node_modules/bson/src/parser/deserializer.ts @@ -0,0 +1,726 @@ +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 { BSONDataView, ByteUtils } from '../utils/byte_utils'; +import { validateUtf8 } from '../validate_utf8'; + +/** @public */ +export interface DeserializeOptions { + /** when deserializing a Long will return as a BigInt. */ + useBigInt64?: 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); + +export function internalDeserialize( + buffer: Uint8Array, + 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 deserialization + return deserializeObject(buffer, index, options, isArray); +} + +const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/; + +function deserializeObject( + buffer: Uint8Array, + index: number, + options: DeserializeOptions, + isArray = false +) { + 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 ?? false; + const promoteLongs = options.promoteLongs ?? true; + const promoteValues = options.promoteValues ?? true; + const useBigInt64 = options.useBigInt64 ?? false; + + if (useBigInt64 && !promoteValues) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + + if (useBigInt64 && !promoteLongs) { + throw new BSONError('Must either request bigint or Long for int64 deserialization'); + } + + // 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++ : ByteUtils.toUTF8(buffer.subarray(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 = ByteUtils.allocate(12); + oid.set(buffer.subarray(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: DeserializeOptions = options; + + // Stop index + const stopIndex = index + objectSize; + + // All elements of array to be returned as raw bson + if (fieldsAsRaw && fieldsAsRaw[name]) { + arrayOptions = { ...options, 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 dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8)); + + 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); + if (useBigInt64) { + value = dataview.getBigInt64(0, true); + } else if (promoteLongs && promoteValues === true) { + // Promote the long if possible + 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 = ByteUtils.allocate(16); + // Copy the next 16 bytes into the bytes buffer + bytes.set(buffer.subarray(index, index + 16), 0); + // Update index + index = index + 16; + // Assign the new Decimal128 value + value = new Decimal128(bytes); + } 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 = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize)); + } else { + value = new Binary(buffer.slice(index, index + binarySize), subType); + if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) { + value = value.toUUID(); + } + } + } else { + const _buffer = ByteUtils.allocate(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 if (subType === constants.BSON_BINARY_SUBTYPE_UUID_NEW) { + value = new Binary(buffer.slice(index, index + binarySize), subType).toUUID(); + } else { + value = new Binary(buffer.slice(index, index + binarySize), 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 = ByteUtils.toUTF8(buffer.subarray(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 = ByteUtils.toUTF8(buffer.subarray(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 = ByteUtils.toUTF8(buffer.subarray(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 = ByteUtils.toUTF8(buffer.subarray(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) { + // We intentionally **do not** use bit shifting here + // Bit shifting in javascript coerces numbers to **signed** int32s + // We need to keep i, and t unsigned + const i = + buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + const t = + buffer[index++] + + buffer[index++] * (1 << 8) + + buffer[index++] * (1 << 16) + + buffer[index++] * (1 << 24); + + value = new Timestamp({ i, t }); + } 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 + ); + + 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'); + } + + 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 = ByteUtils.toUTF8(buffer.subarray(index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + + // Read the oid + const oidBuffer = ByteUtils.allocate(12); + oidBuffer.set(buffer.subarray(index, index + 12), 0); + 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; +} + +function getValidatedString( + buffer: Uint8Array, + start: number, + end: number, + shouldValidateUtf8: boolean +) { + const value = ByteUtils.toUTF8(buffer.subarray(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/2_PAC/node_modules/bson/src/parser/serializer.ts b/2_PAC/node_modules/bson/src/parser/serializer.ts new file mode 100644 index 00000000..b59a1b77 --- /dev/null +++ b/2_PAC/node_modules/bson/src/parser/serializer.ts @@ -0,0 +1,988 @@ +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 { BSONError, BSONVersionError } from '../error'; +import type { Int32 } from '../int_32'; +import { Long } from '../long'; +import type { MinKey } from '../min_key'; +import type { ObjectId } from '../objectid'; +import type { BSONRegExp } from '../regexp'; +import { ByteUtils } from '../utils/byte_utils'; +import { isAnyArrayBuffer, isDate, isMap, isRegExp, isUint8Array } 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: Uint8Array, key: string, value: string, index: number) { + // Encode String type + buffer[index++] = constants.BSON_DATA_STRING; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4); + // 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 NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8); +const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4); +const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8); + +function serializeNumber(buffer: Uint8Array, key: string, value: number, index: number) { + const isNegativeZero = Object.is(value, -0); + + const type = + !isNegativeZero && + Number.isSafeInteger(value) && + value <= constants.BSON_INT32_MAX && + value >= constants.BSON_INT32_MIN + ? constants.BSON_DATA_INT + : constants.BSON_DATA_NUMBER; + + if (type === constants.BSON_DATA_INT) { + NUMBER_SPACE.setInt32(0, value, true); + } else { + NUMBER_SPACE.setFloat64(0, value, true); + } + + const bytes = + type === constants.BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER; + + buffer[index++] = type; + + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + index = index + numberOfWrittenBytes; + buffer[index++] = 0x00; + + buffer.set(bytes, index); + index += bytes.byteLength; + + return index; +} + +function serializeBigInt(buffer: Uint8Array, key: string, value: bigint, index: number) { + buffer[index++] = constants.BSON_DATA_LONG; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index += numberOfWrittenBytes; + buffer[index++] = 0; + NUMBER_SPACE.setBigInt64(0, value, true); + // Write BigInt value + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength; + return index; +} + +function serializeNull(buffer: Uint8Array, key: string, _: unknown, index: number) { + // Set long type + buffer[index++] = constants.BSON_DATA_NULL; + + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeBoolean(buffer: Uint8Array, key: string, value: boolean, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BOOLEAN; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +function serializeDate(buffer: Uint8Array, key: string, value: Date, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_DATE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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: Uint8Array, key: string, value: RegExp, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + if (value.source && value.source.match(regexp) != null) { + throw new BSONError('value ' + value.source + ' must not contain null bytes'); + } + // Adjust the index + index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index); + // 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: Uint8Array, key: string, value: BSONRegExp, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_REGEXP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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 new BSONError('pattern ' + value.pattern + ' must not contain null bytes'); + } + + // Adjust the index + index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index); + // Write zero + buffer[index++] = 0x00; + // Write the options + const sortedOptions = value.options.split('').sort().join(''); + index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +function serializeMinMax(buffer: Uint8Array, key: string, value: MinKey | MaxKey, index: number) { + // 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 = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +function serializeObjectId(buffer: Uint8Array, key: string, value: ObjectId, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_OID; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + if (isUint8Array(value.id)) { + buffer.set(value.id.subarray(0, 12), index); + } else { + throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId'); + } + + // Adjust index + return index + 12; +} + +function serializeBuffer(buffer: Uint8Array, key: string, value: Uint8Array, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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(value, index); + // Adjust the index + index = index + size; + return index; +} + +function serializeObject( + buffer: Uint8Array, + key: string, + value: Document, + index: number, + checkKeys: boolean, + depth: number, + serializeFunctions: boolean, + ignoreUndefined: boolean, + path: Set +) { + if (path.has(value)) { + throw new BSONError('Cannot convert circular structure to BSON'); + } + + path.add(value); + + // Write the type + buffer[index++] = Array.isArray(value) ? constants.BSON_DATA_ARRAY : constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + const endIndex = serializeInto( + buffer, + value, + checkKeys, + index, + depth + 1, + serializeFunctions, + ignoreUndefined, + path + ); + + path.delete(value); + + return endIndex; +} + +function serializeDecimal128(buffer: Uint8Array, key: string, value: Decimal128, index: number) { + buffer[index++] = constants.BSON_DATA_DECIMAL128; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the data from the value + buffer.set(value.bytes.subarray(0, 16), index); + return index + 16; +} + +function serializeLong(buffer: Uint8Array, key: string, value: Long, index: number) { + // Write the type + buffer[index++] = + value._bsontype === 'Long' ? constants.BSON_DATA_LONG : constants.BSON_DATA_TIMESTAMP; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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: Uint8Array, key: string, value: Int32 | number, index: number) { + value = value.valueOf(); + // Set int type 32 bits or less + buffer[index++] = constants.BSON_DATA_INT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // 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: Uint8Array, key: string, value: Double, index: number) { + // Encode as double + buffer[index++] = constants.BSON_DATA_NUMBER; + + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write float + NUMBER_SPACE.setFloat64(0, value.value, true); + buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index); + + // Adjust index + index = index + 8; + return index; +} + +function serializeFunction(buffer: Uint8Array, key: string, value: Function, index: number) { + buffer[index++] = constants.BSON_DATA_CODE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = value.toString(); + + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 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: Uint8Array, + key: string, + value: Code, + index: number, + checkKeys = false, + depth = 0, + serializeFunctions = false, + ignoreUndefined = true, + path: Set +) { + if (value.scope && typeof value.scope === 'object') { + // Write the type + buffer[index++] = constants.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + let startIndex = index; + + // Serialize the function + // Get the function string + const functionString = value.code; + // Index adjustment + index = index + 4; + // Write string into buffer + const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 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, + path + ); + 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 = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + const functionString = value.code.toString(); + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 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: Uint8Array, key: string, value: Binary, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_BINARY; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + const data = value.buffer; + // 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: Uint8Array, key: string, value: BSONSymbol, index: number) { + // Write the type + buffer[index++] = constants.BSON_DATA_SYMBOL; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 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: Uint8Array, + key: string, + value: DBRef, + index: number, + depth: number, + serializeFunctions: boolean, + path: Set +) { + // Write the type + buffer[index++] = constants.BSON_DATA_OBJECT; + // Number of written bytes + const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index); + + // 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, + true, + path + ); + + // 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: Uint8Array, + object: Document, + checkKeys: boolean, + startingIndex: number, + depth: number, + serializeFunctions: boolean, + ignoreUndefined: boolean, + path: Set | null +): number { + if (path == null) { + // We are at the root input + if (object == null) { + // ONLY the root should turn into an empty document + // BSON Empty document has a size of 5 (LE) + buffer[0] = 0x05; + buffer[1] = 0x00; + buffer[2] = 0x00; + buffer[3] = 0x00; + // All documents end with null terminator + buffer[4] = 0x00; + return 5; + } + + if (Array.isArray(object)) { + throw new BSONError('serialize does not support an array as the root input'); + } + if (typeof object !== 'object') { + throw new BSONError('serialize does not support non-object as the root input'); + } else if ('_bsontype' in object && typeof object._bsontype === 'string') { + throw new BSONError(`BSON types cannot be serialized as a document`); + } else if ( + isDate(object) || + isRegExp(object) || + isUint8Array(object) || + isAnyArrayBuffer(object) + ) { + throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`); + } + + path = new Set(); + } + + // Push the object to the path + path.add(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); + } else if (typeof value === 'number') { + index = serializeNumber(buffer, key, value, index); + } else if (typeof value === 'bigint') { + index = serializeBigInt(buffer, key, value, index); + } else if (typeof value === 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if (value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if (value === undefined) { + index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(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 (typeof value === 'object' && value._bsontype == null) { + index = serializeObject( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } else if (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 (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Code') { + index = serializeCode( + buffer, + key, + value, + index, + checkKeys, + depth, + serializeFunctions, + ignoreUndefined, + path + ); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } 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 BSONError(`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]; + let value = entry.value[1]; + + 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 new BSONError('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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 === null || (value === undefined && ignoreUndefined === false)) { + index = serializeNull(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, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } 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, + path + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } 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 BSONError(`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 BSONError('toBSON function did not return an object'); + } + } + + // Iterate over all the keys + for (const key of Object.keys(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 new BSONError('key ' + key + ' must not contain null bytes'); + } + + if (checkKeys) { + if ('$' === key[0]) { + throw new BSONError('key ' + key + " must not start with '$'"); + } else if (~key.indexOf('.')) { + throw new BSONError('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') { + index = serializeBigInt(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) { + if (ignoreUndefined === false) index = serializeNull(buffer, key, value, index); + } else if (value === null) { + index = serializeNull(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, + path + ); + } else if ( + typeof value === 'object' && + value[Symbol.for('@@mdb.bson.version')] !== constants.BSON_MAJOR_VERSION + ) { + throw new BSONVersionError(); + } else if (value._bsontype === 'ObjectId') { + index = serializeObjectId(buffer, key, value, index); + } 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, + path + ); + } else if (typeof value === 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index); + } else if (value._bsontype === 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if (value._bsontype === 'BSONSymbol') { + index = serializeSymbol(buffer, key, value, index); + } else if (value._bsontype === 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path); + } 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 BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`); + } + } + } + + // Remove the path + path.delete(object); + + // 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/2_PAC/node_modules/bson/src/parser/utils.ts b/2_PAC/node_modules/bson/src/parser/utils.ts new file mode 100644 index 00000000..1ed11701 --- /dev/null +++ b/2_PAC/node_modules/bson/src/parser/utils.ts @@ -0,0 +1,29 @@ +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]'; +} + +export function isDate(d: unknown): d is Date { + return Object.prototype.toString.call(d) === '[object Date]'; +} diff --git a/2_PAC/node_modules/bson/src/regexp.ts b/2_PAC/node_modules/bson/src/regexp.ts new file mode 100644 index 00000000..0e7b279d --- /dev/null +++ b/2_PAC/node_modules/bson/src/regexp.ts @@ -0,0 +1,114 @@ +import { BSONValue } from './bson_value'; +import { BSONError } 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 extends BSONValue { + get _bsontype(): 'BSONRegExp' { + return 'BSONRegExp'; + } + + pattern!: string; + options!: string; + /** + * @param pattern - The regular expression pattern to match + * @param options - The regular expression options + */ + constructor(pattern: string, options?: string) { + super(); + 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 BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`); + } + + /** @internal */ + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`; + } +} diff --git a/2_PAC/node_modules/bson/src/symbol.ts b/2_PAC/node_modules/bson/src/symbol.ts new file mode 100644 index 00000000..081a52ad --- /dev/null +++ b/2_PAC/node_modules/bson/src/symbol.ts @@ -0,0 +1,58 @@ +import { BSONValue } from './bson_value'; + +/** @public */ +export interface BSONSymbolExtended { + $symbol: string; +} + +/** + * A class representation of the BSON Symbol type. + * @public + * @category BSONType + */ +export class BSONSymbol extends BSONValue { + get _bsontype(): 'BSONSymbol' { + return 'BSONSymbol'; + } + + value!: string; + /** + * @param value - the string representing the symbol. + */ + constructor(value: string) { + super(); + this.value = value; + } + + /** Access the wrapped string value. */ + valueOf(): string { + return this.value; + } + + toString(): string { + return this.value; + } + + 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(); + } +} diff --git a/2_PAC/node_modules/bson/src/timestamp.ts b/2_PAC/node_modules/bson/src/timestamp.ts new file mode 100644 index 00000000..78d7fc4c --- /dev/null +++ b/2_PAC/node_modules/bson/src/timestamp.ts @@ -0,0 +1,150 @@ +import { BSONError } from './error'; +import type { Int32 } from './int_32'; +import { Long } from './long'; + +/** @public */ +export type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect'; +/** @public */ +export type LongWithoutOverrides = new ( + low: unknown, + high?: number | boolean, + 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 { + get _bsontype(): 'Timestamp' { + return 'Timestamp'; + } + + static readonly MAX_VALUE = Long.MAX_UNSIGNED_VALUE; + + /** + * @param int - A 64-bit bigint representing the Timestamp. + */ + constructor(int: bigint); + /** + * @param long - 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 }); + constructor(low?: bigint | Long | { t: number | Int32; i: number | Int32 }) { + if (low == null) { + super(0, 0, true); + } else if (typeof low === 'bigint') { + super(low, true); + } else if (Long.isLong(low)) { + super(low.low, low.high, true); + } else if (typeof low === 'object' && 't' in low && 'i' in low) { + if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide t as a number'); + } + if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) { + throw new BSONError('Timestamp constructed from { t, i } must provide i as a number'); + } + if (low.t < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive t'); + } + if (low.i < 0) { + throw new BSONError('Timestamp constructed from { t, i } must provide a positive i'); + } + if (low.t > 0xffff_ffff) { + throw new BSONError( + 'Timestamp constructed from { t, i } must provide t equal or less than uint32 max' + ); + } + if (low.i > 0xffff_ffff) { + throw new BSONError( + 'Timestamp constructed from { t, i } must provide i equal or less than uint32 max' + ); + } + + super(low.i.valueOf(), low.t.valueOf(), true); + } else { + throw new BSONError( + 'A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }' + ); + } + } + + 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({ i: lowBits, t: 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 { + // The Long check is necessary because extended JSON has different behavior given the size of the input number + const i = Long.isLong(doc.$timestamp.i) + ? doc.$timestamp.i.getLowBitsUnsigned() // Need to fetch the least significant 32 bits + : doc.$timestamp.i; + const t = Long.isLong(doc.$timestamp.t) + ? doc.$timestamp.t.getLowBitsUnsigned() // Need to fetch the least significant 32 bits + : doc.$timestamp.t; + return new Timestamp({ t, i }); + } + + /** @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/2_PAC/node_modules/bson/src/utils/byte_utils.ts b/2_PAC/node_modules/bson/src/utils/byte_utils.ts new file mode 100644 index 00000000..7c44b38a --- /dev/null +++ b/2_PAC/node_modules/bson/src/utils/byte_utils.ts @@ -0,0 +1,61 @@ +import { nodeJsByteUtils } from './node_byte_utils'; +import { webByteUtils } from './web_byte_utils'; + +/** @internal */ +export type ByteUtils = { + /** Transforms the input to an instance of Buffer if running on node, otherwise Uint8Array */ + toLocalBufferType(buffer: Uint8Array | ArrayBufferView | ArrayBuffer): Uint8Array; + /** Create empty space of size */ + allocate: (size: number) => Uint8Array; + /** Check if two Uint8Arrays are deep equal */ + equals: (a: Uint8Array, b: Uint8Array) => boolean; + /** Check if two Uint8Arrays are deep equal */ + fromNumberArray: (array: number[]) => Uint8Array; + /** Create a Uint8Array from a base64 string */ + fromBase64: (base64: string) => Uint8Array; + /** Create a base64 string from bytes */ + toBase64: (buffer: Uint8Array) => string; + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591: (codePoints: string) => Uint8Array; + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591: (buffer: Uint8Array) => string; + /** Create a Uint8Array from a hex string */ + fromHex: (hex: string) => Uint8Array; + /** Create a hex string from bytes */ + toHex: (buffer: Uint8Array) => string; + /** Create a Uint8Array containing utf8 code units from a string */ + fromUTF8: (text: string) => Uint8Array; + /** Create a string from utf8 code units */ + toUTF8: (buffer: Uint8Array) => string; + /** Get the utf8 code unit count from a string if it were to be transformed to utf8 */ + utf8ByteLength: (input: string) => number; + /** Encode UTF8 bytes generated from `source` string into `destination` at byteOffset. Returns the number of bytes encoded. */ + encodeUTF8Into(destination: Uint8Array, source: string, byteOffset: number): number; + /** Generate a Uint8Array filled with random bytes with byteLength */ + randomBytes(byteLength: number): Uint8Array; +}; + +declare const Buffer: { new (): unknown; prototype?: { _isBuffer?: boolean } } | undefined; + +/** + * Check that a global Buffer exists that is a function and + * does not have a '_isBuffer' property defined on the prototype + * (this is to prevent using the npm buffer) + */ +const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true; + +/** + * This is the only ByteUtils that should be used across the rest of the BSON library. + * + * The type annotation is important here, it asserts that each of the platform specific + * utils implementations are compatible with the common one. + * + * @internal + */ +export const ByteUtils: ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils; + +export class BSONDataView extends DataView { + static fromUint8Array(input: Uint8Array) { + return new DataView(input.buffer, input.byteOffset, input.byteLength); + } +} diff --git a/2_PAC/node_modules/bson/src/utils/node_byte_utils.ts b/2_PAC/node_modules/bson/src/utils/node_byte_utils.ts new file mode 100644 index 00000000..b25969fe --- /dev/null +++ b/2_PAC/node_modules/bson/src/utils/node_byte_utils.ts @@ -0,0 +1,141 @@ +import { BSONError } from '../error'; + +type NodeJsEncoding = 'base64' | 'hex' | 'utf8' | 'binary'; +type NodeJsBuffer = ArrayBufferView & + Uint8Array & { + write(string: string, offset: number, length: undefined, encoding: 'utf8'): number; + copy(target: Uint8Array, targetStart: number, sourceStart: number, sourceEnd: number): number; + toString: (this: Uint8Array, encoding: NodeJsEncoding) => string; + equals: (this: Uint8Array, other: Uint8Array) => boolean; + }; +type NodeJsBufferConstructor = Omit & { + alloc: (size: number) => NodeJsBuffer; + from(array: number[]): NodeJsBuffer; + from(array: Uint8Array): NodeJsBuffer; + from(array: ArrayBuffer): NodeJsBuffer; + from(array: ArrayBuffer, byteOffset: number, byteLength: number): NodeJsBuffer; + from(base64: string, encoding: NodeJsEncoding): NodeJsBuffer; + byteLength(input: string, encoding: 'utf8'): number; + isBuffer(value: unknown): value is NodeJsBuffer; +}; + +// This can be nullish, but we gate the nodejs functions on being exported whether or not this exists +// Node.js global +declare const Buffer: NodeJsBufferConstructor; +declare const require: (mod: 'node:crypto') => { randomBytes: (byteLength: number) => Uint8Array }; + +/** @internal */ +export function nodejsMathRandomBytes(byteLength: number) { + return nodeJsByteUtils.fromNumberArray( + Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)) + ); +} + +/** + * @internal + * WARNING: REQUIRE WILL BE REWRITTEN + * + * This code is carefully used by require_rewriter.mjs any modifications must be reflected in the plugin. + * + * @remarks + * "crypto" is the only dependency BSON needs. This presents a problem for creating a bundle of the BSON library + * in an es module format that can be used both on the browser and in Node.js. In Node.js when BSON is imported as + * an es module, there will be no global require function defined, making the code below fallback to the much less desireable math.random bytes. + * In order to make our es module bundle work as expected on Node.js we need to change this `require()` to a dynamic import, and the dynamic + * import must be top-level awaited since es modules are async. So we rely on a custom rollup plugin to seek out the following lines of code + * and replace `require` with `await import` and the IIFE line (`nodejsRandomBytes = (() => { ... })()`) with `nodejsRandomBytes = await (async () => { ... })()` + * when generating an es module bundle. + */ +const nodejsRandomBytes: (byteLength: number) => Uint8Array = (() => { + try { + return require('node:crypto').randomBytes; + } catch { + return nodejsMathRandomBytes; + } +})(); + +/** @internal */ +export const nodeJsByteUtils = { + toLocalBufferType(potentialBuffer: Uint8Array | NodeJsBuffer | ArrayBuffer): NodeJsBuffer { + if (Buffer.isBuffer(potentialBuffer)) { + return potentialBuffer; + } + + if (ArrayBuffer.isView(potentialBuffer)) { + return Buffer.from( + potentialBuffer.buffer, + potentialBuffer.byteOffset, + potentialBuffer.byteLength + ); + } + + const stringTag = + potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer); + if ( + stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]' + ) { + return Buffer.from(potentialBuffer); + } + + throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`); + }, + + allocate(size: number): NodeJsBuffer { + return Buffer.alloc(size); + }, + + equals(a: Uint8Array, b: Uint8Array): boolean { + return nodeJsByteUtils.toLocalBufferType(a).equals(b); + }, + + fromNumberArray(array: number[]): NodeJsBuffer { + return Buffer.from(array); + }, + + fromBase64(base64: string): NodeJsBuffer { + return Buffer.from(base64, 'base64'); + }, + + toBase64(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64'); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591(codePoints: string): NodeJsBuffer { + return Buffer.from(codePoints, 'binary'); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary'); + }, + + fromHex(hex: string): NodeJsBuffer { + return Buffer.from(hex, 'hex'); + }, + + toHex(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex'); + }, + + fromUTF8(text: string): NodeJsBuffer { + return Buffer.from(text, 'utf8'); + }, + + toUTF8(buffer: Uint8Array): string { + return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8'); + }, + + utf8ByteLength(input: string): number { + return Buffer.byteLength(input, 'utf8'); + }, + + encodeUTF8Into(buffer: Uint8Array, source: string, byteOffset: number): number { + return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8'); + }, + + randomBytes: nodejsRandomBytes +}; diff --git a/2_PAC/node_modules/bson/src/utils/web_byte_utils.ts b/2_PAC/node_modules/bson/src/utils/web_byte_utils.ts new file mode 100644 index 00000000..6e45f91e --- /dev/null +++ b/2_PAC/node_modules/bson/src/utils/web_byte_utils.ts @@ -0,0 +1,190 @@ +import { BSONError } from '../error'; + +type TextDecoder = { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + decode(input?: Uint8Array): string; +}; +type TextDecoderConstructor = { + new (label: 'utf8', options: { fatal: boolean; ignoreBOM?: boolean }): TextDecoder; +}; + +type TextEncoder = { + readonly encoding: string; + encode(input?: string): Uint8Array; +}; +type TextEncoderConstructor = { + new (): TextEncoder; +}; + +// Web global +declare const TextDecoder: TextDecoderConstructor; +declare const TextEncoder: TextEncoderConstructor; +declare const atob: (base64: string) => string; +declare const btoa: (binary: string) => string; + +type ArrayBufferViewWithTag = ArrayBufferView & { + [Symbol.toStringTag]?: string; +}; + +function isReactNative() { + const { navigator } = globalThis as { navigator?: { product?: string } }; + return typeof navigator === 'object' && navigator.product === 'ReactNative'; +} + +/** @internal */ +export function webMathRandomBytes(byteLength: number) { + if (byteLength < 0) { + throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`); + } + return webByteUtils.fromNumberArray( + Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)) + ); +} + +/** @internal */ +const webRandomBytes: (byteLength: number) => Uint8Array = (() => { + const { crypto } = globalThis as { + crypto?: { getRandomValues?: (space: Uint8Array) => Uint8Array }; + }; + if (crypto != null && typeof crypto.getRandomValues === 'function') { + return (byteLength: number) => { + // @ts-expect-error: crypto.getRandomValues cannot actually be null here + // You cannot separate getRandomValues from crypto (need to have this === crypto) + return crypto.getRandomValues(webByteUtils.allocate(byteLength)); + }; + } else { + if (isReactNative()) { + const { console } = globalThis as { console?: { warn?: (message: string) => void } }; + console?.warn?.( + 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.' + ); + } + return webMathRandomBytes; + } +})(); + +const HEX_DIGIT = /(\d|[a-f])/i; + +/** @internal */ +export const webByteUtils = { + toLocalBufferType( + potentialUint8array: Uint8Array | ArrayBufferViewWithTag | ArrayBuffer + ): Uint8Array { + const stringTag = + potentialUint8array?.[Symbol.toStringTag] ?? + Object.prototype.toString.call(potentialUint8array); + + if (stringTag === 'Uint8Array') { + return potentialUint8array as Uint8Array; + } + + if (ArrayBuffer.isView(potentialUint8array)) { + return new Uint8Array( + potentialUint8array.buffer.slice( + potentialUint8array.byteOffset, + potentialUint8array.byteOffset + potentialUint8array.byteLength + ) + ); + } + + if ( + stringTag === 'ArrayBuffer' || + stringTag === 'SharedArrayBuffer' || + stringTag === '[object ArrayBuffer]' || + stringTag === '[object SharedArrayBuffer]' + ) { + return new Uint8Array(potentialUint8array); + } + + throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`); + }, + + allocate(size: number): Uint8Array { + if (typeof size !== 'number') { + throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`); + } + return new Uint8Array(size); + }, + + equals(a: Uint8Array, b: Uint8Array): boolean { + if (a.byteLength !== b.byteLength) { + return false; + } + for (let i = 0; i < a.byteLength; i++) { + if (a[i] !== b[i]) { + return false; + } + } + return true; + }, + + fromNumberArray(array: number[]): Uint8Array { + return Uint8Array.from(array); + }, + + fromBase64(base64: string): Uint8Array { + return Uint8Array.from(atob(base64), c => c.charCodeAt(0)); + }, + + toBase64(uint8array: Uint8Array): string { + return btoa(webByteUtils.toISO88591(uint8array)); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + fromISO88591(codePoints: string): Uint8Array { + return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff); + }, + + /** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */ + toISO88591(uint8array: Uint8Array): string { + return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join(''); + }, + + fromHex(hex: string): Uint8Array { + const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1); + const buffer = []; + + for (let i = 0; i < evenLengthHex.length; i += 2) { + const firstDigit = evenLengthHex[i]; + const secondDigit = evenLengthHex[i + 1]; + + if (!HEX_DIGIT.test(firstDigit)) { + break; + } + if (!HEX_DIGIT.test(secondDigit)) { + break; + } + + const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16); + buffer.push(hexDigit); + } + + return Uint8Array.from(buffer); + }, + + toHex(uint8array: Uint8Array): string { + return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join(''); + }, + + fromUTF8(text: string): Uint8Array { + return new TextEncoder().encode(text); + }, + + toUTF8(uint8array: Uint8Array): string { + return new TextDecoder('utf8', { fatal: false }).decode(uint8array); + }, + + utf8ByteLength(input: string): number { + return webByteUtils.fromUTF8(input).byteLength; + }, + + encodeUTF8Into(buffer: Uint8Array, source: string, byteOffset: number): number { + const bytes = webByteUtils.fromUTF8(source); + buffer.set(bytes, byteOffset); + return bytes.byteLength; + }, + + randomBytes: webRandomBytes +}; diff --git a/2_PAC/node_modules/bson/src/uuid_utils.ts b/2_PAC/node_modules/bson/src/uuid_utils.ts new file mode 100644 index 00000000..37f0dcfd --- /dev/null +++ b/2_PAC/node_modules/bson/src/uuid_utils.ts @@ -0,0 +1,33 @@ +import { BSONError } from './error'; +import { ByteUtils } from './utils/byte_utils'; + +// 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): Uint8Array => { + if (!uuidValidateString(hexString)) { + throw new BSONError( + '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 ByteUtils.fromHex(sanitizedHexString); +}; + +export function bufferToUuidHexString(buffer: Uint8Array, includeDashes = true): string { + if (includeDashes) { + return [ + ByteUtils.toHex(buffer.subarray(0, 4)), + ByteUtils.toHex(buffer.subarray(4, 6)), + ByteUtils.toHex(buffer.subarray(6, 8)), + ByteUtils.toHex(buffer.subarray(8, 10)), + ByteUtils.toHex(buffer.subarray(10, 16)) + ].join('-'); + } + return ByteUtils.toHex(buffer); +} diff --git a/2_PAC/node_modules/bson/src/validate_utf8.ts b/2_PAC/node_modules/bson/src/validate_utf8.ts new file mode 100644 index 00000000..e1da934c --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/ip/README.md b/2_PAC/node_modules/ip/README.md new file mode 100644 index 00000000..22e5819f --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/ip/lib/ip.js b/2_PAC/node_modules/ip/lib/ip.js new file mode 100644 index 00000000..4b2adb5a --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/ip/package.json b/2_PAC/node_modules/ip/package.json new file mode 100644 index 00000000..f0d95e9b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/memory-pager/.travis.yml b/2_PAC/node_modules/memory-pager/.travis.yml new file mode 100644 index 00000000..1c4ab31e --- /dev/null +++ b/2_PAC/node_modules/memory-pager/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - '4' + - '6' diff --git a/2_PAC/node_modules/memory-pager/LICENSE b/2_PAC/node_modules/memory-pager/LICENSE new file mode 100644 index 00000000..56fce089 --- /dev/null +++ b/2_PAC/node_modules/memory-pager/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 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/2_PAC/node_modules/memory-pager/README.md b/2_PAC/node_modules/memory-pager/README.md new file mode 100644 index 00000000..aed17614 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/memory-pager/index.js b/2_PAC/node_modules/memory-pager/index.js new file mode 100644 index 00000000..687f346f --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/memory-pager/package.json b/2_PAC/node_modules/memory-pager/package.json new file mode 100644 index 00000000..f4847e8c --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/memory-pager/test.js b/2_PAC/node_modules/memory-pager/test.js new file mode 100644 index 00000000..16382100 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs b/2_PAC/node_modules/mongodb-connection-string-url/.esm-wrapper.mjs new file mode 100644 index 00000000..a0f5be52 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb-connection-string-url/LICENSE b/2_PAC/node_modules/mongodb-connection-string-url/LICENSE new file mode 100644 index 00000000..d57f55f4 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/LICENSE @@ -0,0 +1,192 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + 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. + 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. + diff --git a/2_PAC/node_modules/mongodb-connection-string-url/README.md b/2_PAC/node_modules/mongodb-connection-string-url/README.md new file mode 100644 index 00000000..0eb65d00 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb-connection-string-url/lib/index.d.ts b/2_PAC/node_modules/mongodb-connection-string-url/lib/index.d.ts new file mode 100644 index 00000000..49c18ea2 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb-connection-string-url/lib/index.js b/2_PAC/node_modules/mongodb-connection-string-url/lib/index.js new file mode 100644 index 00000000..8e4864d2 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb-connection-string-url/lib/index.js.map b/2_PAC/node_modules/mongodb-connection-string-url/lib/index.js.map new file mode 100644 index 00000000..d325062a --- /dev/null +++ b/2_PAC/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,CAAC,YAAY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;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/2_PAC/node_modules/mongodb-connection-string-url/lib/redact.d.ts b/2_PAC/node_modules/mongodb-connection-string-url/lib/redact.d.ts new file mode 100644 index 00000000..94a64def --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb-connection-string-url/lib/redact.js b/2_PAC/node_modules/mongodb-connection-string-url/lib/redact.js new file mode 100644 index 00000000..62c7ba71 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/lib/redact.js @@ -0,0 +1,86 @@ +"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 R = replacementString; + const replacements = [ + uri => uri.replace(redactUsernames ? /(\/\/)(.*)(@)/g : /(\/\/[^@]*:)(.*)(@)/g, `$1${R}$3`), + uri => uri.replace(/(AWS_SESSION_TOKEN(:|%3A))([^,&]+)/gi, `$1${R}`), + uri => uri.replace(/(tlsCertificateKeyFilePassword=)([^&]+)/gi, `$1${R}`), + uri => redactUsernames ? uri.replace(/(proxyUsername=)([^&]+)/gi, `$1${R}`) : uri, + uri => uri.replace(/(proxyPassword=)([^&]+)/gi, `$1${R}`) + ]; + for (const replacer of replacements) { + uri = replacer(uri); + } + return uri; +} +exports.redactConnectionString = redactConnectionString; +//# sourceMappingURL=redact.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb-connection-string-url/lib/redact.js.map b/2_PAC/node_modules/mongodb-connection-string-url/lib/redact.js.map new file mode 100644 index 00000000..24a282b9 --- /dev/null +++ b/2_PAC/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,uBAA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AAQ,IAAI,YAAY,EAAE;QACnC,GAAG,GAAG,QAAQ,CAAC,GAAG,CAAC,CAAC;KACrB;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AApCD,wDAoCC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/LICENSE.md b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/LICENSE.md new file mode 100644 index 00000000..62c0de28 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/LICENSE.md @@ -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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/README.md b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/README.md new file mode 100644 index 00000000..1df7915b --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/index.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/index.js new file mode 100644 index 00000000..7ce05327 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/mappingTable.json b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/mappingTable.json new file mode 100644 index 00000000..3d71a5ef --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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,1,"Ꭳ"],[43892,1,"Ꭴ"],[43893,1,"Ꭵ"],[43894,1,"Ꭶ"],[43895,1,"Ꭷ"],[43896,1,"Ꭸ"],[43897,1,"Ꭹ"],[43898,1,"Ꭺ"],[43899,1,"Ꭻ"],[43900,1,"Ꭼ"],[43901,1,"Ꭽ"],[43902,1,"Ꭾ"],[43903,1,"Ꭿ"],[43904,1,"Ꮀ"],[43905,1,"Ꮁ"],[43906,1,"Ꮂ"],[43907,1,"Ꮃ"],[43908,1,"Ꮄ"],[43909,1,"Ꮅ"],[43910,1,"Ꮆ"],[43911,1,"Ꮇ"],[43912,1,"Ꮈ"],[43913,1,"Ꮉ"],[43914,1,"Ꮊ"],[43915,1,"Ꮋ"],[43916,1,"Ꮌ"],[43917,1,"Ꮍ"],[43918,1,"Ꮎ"],[43919,1,"Ꮏ"],[43920,1,"Ꮐ"],[43921,1,"Ꮑ"],[43922,1,"Ꮒ"],[43923,1,"Ꮓ"],[43924,1,"Ꮔ"],[43925,1,"Ꮕ"],[43926,1,"Ꮖ"],[43927,1,"Ꮗ"],[43928,1,"Ꮘ"],[43929,1,"Ꮙ"],[43930,1,"Ꮚ"],[43931,1,"Ꮛ"],[43932,1,"Ꮜ"],[43933,1,"Ꮝ"],[43934,1,"Ꮞ"],[43935,1,"Ꮟ"],[43936,1,"Ꮠ"],[43937,1,"Ꮡ"],[43938,1,"Ꮢ"],[43939,1,"Ꮣ"],[43940,1,"Ꮤ"],[43941,1,"Ꮥ"],[43942,1,"Ꮦ"],[43943,1,"Ꮧ"],[43944,1,"Ꮨ"],[43945,1,"Ꮩ"],[43946,1,"Ꮪ"],[43947,1,"Ꮫ"],[43948,1,"Ꮬ"],[43949,1,"Ꮭ"],[43950,1,"Ꮮ"],[43951,1,"Ꮯ"],[43952,1,"Ꮰ"],[43953,1,"Ꮱ"],[43954,1,"Ꮲ"],[43955,1,"Ꮳ"],[43956,1,"Ꮴ"],[43957,1,"Ꮵ"],[43958,1,"Ꮶ"],[43959,1,"Ꮷ"],[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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/regexes.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/regexes.js new file mode 100644 index 00000000..4dd8051e --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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{1E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0100}-\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\u0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0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\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\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}-\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{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-\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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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/statusMapping.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/lib/statusMapping.js new file mode 100644 index 00000000..cfed6d6a --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/package.json b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/tr46/package.json new file mode 100644 index 00000000..8e79ba6c --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/LICENSE.md b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/LICENSE.md new file mode 100644 index 00000000..d4a994f5 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/README.md b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/README.md new file mode 100644 index 00000000..16cc3931 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/lib/index.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/lib/index.js new file mode 100644 index 00000000..0229347c --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/package.json b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/webidl-conversions/package.json new file mode 100644 index 00000000..20747bb4 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/LICENSE.txt b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/LICENSE.txt new file mode 100644 index 00000000..8e8c25c3 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/README.md b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/README.md new file mode 100644 index 00000000..4d089006 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/index.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/index.js new file mode 100644 index 00000000..c470e48e --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/Function.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/Function.js new file mode 100644 index 00000000..ea8712fd --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URL-impl.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URL-impl.js new file mode 100644 index 00000000..db3a0aea --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URL.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URL.js new file mode 100644 index 00000000..d62ac3e7 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URLSearchParams-impl.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URLSearchParams-impl.js new file mode 100644 index 00000000..ef8d604e --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URLSearchParams.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/URLSearchParams.js new file mode 100644 index 00000000..a7c24eff --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/VoidFunction.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/VoidFunction.js new file mode 100644 index 00000000..9a00672a --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/encoding.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/encoding.js new file mode 100644 index 00000000..cb66b8f1 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/infra.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/infra.js new file mode 100644 index 00000000..4a984a3b --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/percent-encoding.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/percent-encoding.js new file mode 100644 index 00000000..f8308673 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/url-state-machine.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/url-state-machine.js new file mode 100644 index 00000000..d9ecae2e --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/urlencoded.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/urlencoded.js new file mode 100644 index 00000000..e7230637 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/utils.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/lib/utils.js new file mode 100644 index 00000000..3af17706 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/package.json b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/package.json new file mode 100644 index 00000000..9cb209f9 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/webidl2js-wrapper.js b/2_PAC/node_modules/mongodb-connection-string-url/node_modules/whatwg-url/webidl2js-wrapper.js new file mode 100644 index 00000000..b731ace5 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/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/2_PAC/node_modules/mongodb-connection-string-url/package.json b/2_PAC/node_modules/mongodb-connection-string-url/package.json new file mode 100644 index 00000000..24a13d78 --- /dev/null +++ b/2_PAC/node_modules/mongodb-connection-string-url/package.json @@ -0,0 +1,62 @@ +{ + "name": "mongodb-connection-string-url", + "version": "2.6.0", + "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/2_PAC/node_modules/mongodb/LICENSE.md b/2_PAC/node_modules/mongodb/LICENSE.md new file mode 100644 index 00000000..ad410e11 --- /dev/null +++ b/2_PAC/node_modules/mongodb/LICENSE.md @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + 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} + + 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. \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/README.md b/2_PAC/node_modules/mongodb/README.md new file mode 100644 index 00000000..a619728b --- /dev/null +++ b/2_PAC/node_modules/mongodb/README.md @@ -0,0 +1,295 @@ +# MongoDB NodeJS Driver + +The official [MongoDB](https://www.mongodb.com/) driver for Node.js. + +**Upgrading to version 5? Take a look at our [upgrade guide here](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_5.0.0.md)!** + +## Quick Links + +| what | where | +| ------------- | ----------------------------------------------------------------------------------------------------------------- | +| documentation | [www.mongodb.com/docs/drivers/node](https://www.mongodb.com/docs/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 v5 | [etc/notes/CHANGES_5.0.0.md](https://github.com/mongodb/node-mongodb-native/blob/HEAD/etc/notes/CHANGES_5.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 +case in our issue management tool, JIRA: + +- 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**. + +### Support / Feedback + +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 + +Change history can be found in [`HISTORY.md`](https://github.com/mongodb/node-mongodb-native/blob/HEAD/HISTORY.md). + +### Compatibility + +For version compatibility matrices, please refer to the following links: + +- [MongoDB](https://docs.mongodb.com/drivers/node/current/compatibility/#mongodb-compatibility) +- [NodeJS](https://docs.mongodb.com/drivers/node/current/compatibility/#language-compatibility) + +#### Typescript Version + +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). + +## Installation + +The recommended way to get started using the Node.js 5.x driver is by using the `npm` (Node Package Manager) to install the dependency in your project. + +After you've created your own project using `npm init`, you can run: + +```bash +npm install mongodb +# or ... +yarn add mongodb +``` + +This will download the MongoDB driver and add a dependency entry in your `package.json` file. + +If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions: + +```sh +npm install -D @types/node +``` + +## Driver Extensions + +The MongoDB driver can optionally be enhanced by the following feature packages: + +Maintained by MongoDB: + +- Zstd network compression - [@mongodb-js/zstd](https://github.com/mongodb-js/zstd) +- MongoDB field level and queryable encryption - [mongodb-client-encryption](https://github.com/mongodb/libmongocrypt#readme) +- GSSAPI / SSPI / Kerberos authentication - [kerberos](https://github.com/mongodb-js/kerberos) + +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 compilation issues. + +Third party: + +- Snappy network compression - [snappy](https://github.com/Brooooooklyn/snappy) +- AWS authentication - [@aws-sdk/credential-providers](https://github.com/aws/aws-sdk-js-v3/tree/main/packages/credential-providers) + +## Quick Start + +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/). + +### Create the `package.json` file + +First, create a directory where your application will live. + +```bash +mkdir myProject +cd myProject +``` + +Enter the following command and answer the questions to create the initial structure for your new project: + +```bash +npm init -y +``` + +Next, install the driver as a dependency. + +```bash +npm install mongodb +``` + +### Start a MongoDB Server + +For complete MongoDB installation instructions, see [the manual](https://docs.mongodb.org/manual/installation/). + +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. + +```bash +mongod --dbpath=/data +``` + +You should see the **mongod** process start up and print some status information. + +### Connect to MongoDB + +Create a new **app.js** file and add the following code to try out some basic CRUD +operations using the MongoDB driver. + +Add code to connect to the server and the database **myProject**: + +> **NOTE:** Resolving DNS Connection issues +> +> Node.js 18 changed the default DNS resolution ordering from always prioritizing ipv4 to the ordering +> returned by the DNS provider. In some environments, this can result in `localhost` resolving to +> an ipv6 address instead of ipv4 and a consequent failure to connect to the server. +> +> This can be resolved by: +> +> - specifying the ip address family using the MongoClient `family` option (`MongoClient(, { family: 4 } )`) +> - launching mongod or mongos with the ipv6 flag enabled ([--ipv6 mongod option documentation](https://www.mongodb.com/docs/manual/reference/program/mongod/#std-option-mongod.--ipv6)) +> - using a host of `127.0.0.1` in place of localhost +> - specifying the DNS resolution ordering with the `--dns-resolution-order` Node.js command line argument (e.g. `node --dns-resolution-order=ipv4first`) + +```js +const { MongoClient } = require('mongodb'); +// or as an es module: +// import { MongoClient } from 'mongodb' + +// Connection URL +const url = 'mongodb://localhost:27017'; +const client = new MongoClient(url); + +// Database Name +const dbName = 'myProject'; + +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'); + + // the following code examples can be pasted here... + + return 'done.'; +} + +main() + .then(console.log) + .catch(console.error) + .finally(() => client.close()); +``` + +Run your app from the command line with: + +```bash +node app.js +``` + +The application should print **Connected successfully to server** to the console. + +### Insert a Document + +Add to **app.js** the following function which uses the **insertMany** +method to add three documents to the **documents** collection. + +```js +const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]); +console.log('Inserted documents =>', insertResult); +``` + +The **insertMany** command returns an object with information about the insert operations. + +### Find All Documents + +Add a query that returns all the documents. + +```js +const findResult = await collection.find({}).toArray(); +console.log('Found documents =>', findResult); +``` + +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. + +### Find Documents with a Query Filter + +Add a query filter to find only documents which meet the query criteria. + +```js +const filteredDocs = await collection.find({ a: 3 }).toArray(); +console.log('Found documents filtered by { a: 3 } =>', filteredDocs); +``` + +Only the documents which match `'a' : 3` should be returned. + +### Update a document + +The following operation updates a document in the **documents** collection. + +```js +const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } }); +console.log('Updated documents =>', updateResult); +``` + +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. + +### Remove a document + +Remove the document where the field **a** is equal to **3**. + +```js +const deleteResult = await collection.deleteMany({ a: 3 }); +console.log('Deleted documents =>', deleteResult); +``` + +### 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 +const indexName = await collection.createIndex({ a: 1 }); +console.log('index name =', indexName); +``` + +For more detailed information, see the [indexing strategies page](https://docs.mongodb.com/manual/applications/indexes/). + +## Error Handling + +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). + +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. + +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. + +```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 +} +``` + +## Next Steps + +- [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) + +## License + +[Apache 2.0](LICENSE.md) + +© 2009-2012 Christian Amor Kvalheim +© 2012-present MongoDB [Contributors](https://github.com/mongodb/node-mongodb-native/blob/HEAD/CONTRIBUTORS.md) diff --git a/2_PAC/node_modules/mongodb/etc/prepare.js b/2_PAC/node_modules/mongodb/etc/prepare.js new file mode 100644 index 00000000..2039d0b3 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/admin.js b/2_PAC/node_modules/mongodb/lib/admin.js new file mode 100644 index 00000000..c7722148 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/admin.js @@ -0,0 +1,131 @@ +"use strict"; +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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +class Admin { + /** + * Create a new Admin instance + * @internal + */ + constructor(db) { + this.s = { db }; + } + /** + * Execute a command + * + * @param command - The command to execute + * @param options - Optional settings for the command + */ + async command(command, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new run_command_1.RunCommandOperation(this.s.db, command, { dbName: 'admin', ...options })); + } + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async buildInfo(options) { + return this.command({ buildinfo: 1 }, options); + } + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async serverInfo(options) { + return this.command({ buildinfo: 1 }, options); + } + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + async serverStatus(options) { + return this.command({ serverStatus: 1 }, options); + } + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + async ping(options) { + return this.command({ ping: 1 }, options); + } + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + async addUser(username, passwordOrOptions, options) { + options = + options != null && typeof options === 'object' + ? options + : passwordOrOptions != null && typeof passwordOrOptions === 'object' + ? passwordOrOptions + : undefined; + const password = typeof passwordOrOptions === 'string' ? passwordOrOptions : undefined; + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new add_user_1.AddUserOperation(this.s.db, username, password, { dbName: 'admin', ...options })); + } + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new remove_user_1.RemoveUserOperation(this.s.db, username, { dbName: 'admin', ...options })); + } + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + async validateCollection(collectionName, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new validate_collection_1.ValidateCollectionOperation(this, collectionName, options)); + } + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + async listDatabases(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new list_databases_1.ListDatabasesOperation(this.s.db, options)); + } + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + async replSetGetStatus(options) { + return this.command({ replSetGetStatus: 1 }, options); + } +} +exports.Admin = Admin; +//# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/admin.js.map b/2_PAC/node_modules/mongodb/lib/admin.js.map new file mode 100644 index 00000000..4477dc76 --- /dev/null +++ b/2_PAC/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;AAO1C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,KAAK;IAIhB;;;OAGG;IACH,YAAY,EAAM;QAChB,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC;IAClB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,OAAO,CAAC,OAAiB,EAAE,OAA2B;QAC1D,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,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,CAAC,CAC7E,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,SAAS,CAAC,OAAiC;QAC/C,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,UAAU,CAAC,OAAiC;QAChD,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACjD,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,YAAY,CAAC,OAAiC;QAClD,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,YAAY,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC;IAED;;;;OAI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CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAClB,IAAI,iDAA2B,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,CAAC,CAC/D,CAAC;IACJ,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,aAAa,CAAC,OAA8B;QAChD,OAAO,IAAA,oCAAgB,EAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,EAAE,IAAI,uCAAsB,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC,CAAC;IAC9F,CAAC;IAED;;;;OAIG;IACH,KAAK,CAAC,gBAAgB,CAAC,OAAiC;QACtD,OAAO,IAAI,CAAC,OAAO,CAAC,EAAE,gBAAgB,EAAE,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;IACxD,CAAC;CACF;AApID,sBAoIC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/bson.js b/2_PAC/node_modules/mongodb/lib/bson.js new file mode 100644 index 00000000..1a6ae96d --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/bson.js @@ -0,0 +1,59 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.resolveBSONOptions = exports.pluckBSONSerializeOptions = exports.Timestamp = exports.serialize = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.Double = exports.deserialize = exports.Decimal128 = exports.DBRef = exports.Code = exports.calculateObjectSize = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.BSON = exports.Binary = void 0; +var bson_1 = require("bson"); +Object.defineProperty(exports, "Binary", { enumerable: true, get: function () { return bson_1.Binary; } }); +Object.defineProperty(exports, "BSON", { enumerable: true, get: function () { return bson_1.BSON; } }); +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, "BSONType", { enumerable: true, get: function () { return bson_1.BSONType; } }); +Object.defineProperty(exports, "calculateObjectSize", { enumerable: true, get: function () { return bson_1.calculateObjectSize; } }); +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, "deserialize", { enumerable: true, get: function () { return bson_1.deserialize; } }); +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, "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, "serialize", { enumerable: true, get: function () { return bson_1.serialize; } }); +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) { + 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 + }; +} +exports.resolveBSONOptions = resolveBSONOptions; +//# sourceMappingURL=bson.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/bson.js.map b/2_PAC/node_modules/mongodb/lib/bson.js.map new file mode 100644 index 00000000..8210cea8 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/bson.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bson.js","sourceRoot":"","sources":["../src/bson.ts"],"names":[],"mappings":";;;AAEA,6BAoBc;AAnBZ,8FAAA,MAAM,OAAA;AACN,4FAAA,IAAI,OAAA;AACJ,kGAAA,UAAU,OAAA;AACV,kGAAA,UAAU,OAAA;AACV,gGAAA,QAAQ,OAAA;AACR,2GAAA,mBAAmB,OAAA;AACnB,4FAAA,IAAI,OAAA;AACJ,6FAAA,KAAK,OAAA;AACL,kGAAA,UAAU,OAAA;AACV,mGAAA,WAAW,OAAA;AAEX,8FAAA,MAAM,OAAA;AACN,6FAAA,KAAK,OAAA;AACL,4FAAA,IAAI,OAAA;AACJ,8FAAA,MAAM,OAAA;AACN,8FAAA,MAAM,OAAA;AACN,gGAAA,QAAQ,OAAA;AACR,iGAAA,SAAS,OAAA;AACT,iGAAA,SAAS,OAAA;AA6CX,SAAgB,yBAAyB,CAAC,OAA6B;IACrE,MAAM,EACJ,WAAW,EACX,aAAa,EACb,cAAc,EACd,YAAY,EACZ,kBAAkB,EAClB,eAAe,EACf,UAAU,EACV,GAAG,EACH,oBAAoB,EACrB,GAAG,OAAO,CAAC;IACZ,OAAO;QACL,WAAW;QACX,aAAa;QACb,cAAc;QACd,YAAY;QACZ,kBAAkB;QAClB,eAAe;QACf,UAAU;QACV,GAAG;QACH,oBAAoB;KACrB,CAAC;AACJ,CAAC;AAvBD,8DAuBC;AAED;;;;;GAKG;AACH,SAAgB,kBAAkB,CAChC,OAA8B,EAC9B,MAA+C;IAE/C,MAAM,aAAa,GAAG,MAAM,EAAE,WAAW,CAAC;IAC1C,OAAO;QACL,GAAG,EAAE,OAAO,EAAE,GAAG,IAAI,aAAa,EAAE,GAAG,IAAI,KAAK;QAChD,YAAY,EAAE,OAAO,EAAE,YAAY,IAAI,aAAa,EAAE,YAAY,IAAI,IAAI;QAC1E,aAAa,EAAE,OAAO,EAAE,aAAa,IAAI,aAAa,EAAE,aAAa,IAAI,IAAI;QAC7E,cAAc,EAAE,OAAO,EAAE,cAAc,IAAI,aAAa,EAAE,cAAc,IAAI,KAAK;QACjF,eAAe,EAAE,OAAO,EAAE,eAAe,IAAI,aAAa,EAAE,eAAe,IAAI,KAAK;QACpF,UAAU,EAAE,OAAO,EAAE,UAAU,IAAI,aAAa,EAAE,UAAU,IAAI,KAAK;QACrE,kBAAkB,EAAE,OAAO,EAAE,kBAAkB,IAAI,aAAa,EAAE,kBAAkB,IAAI,KAAK;QAC7F,WAAW,EAAE,OAAO,EAAE,WAAW,IAAI,aAAa,EAAE,WAAW,IAAI,EAAE;QACrE,oBAAoB,EAClB,OAAO,EAAE,oBAAoB,IAAI,aAAa,EAAE,oBAAoB,IAAI,IAAI;KAC/E,CAAC;AACJ,CAAC;AAjBD,gDAiBC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/bulk/common.js b/2_PAC/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 00000000..98161224 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,874 @@ +"use strict"; +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 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 +}); +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * + * @public + */ +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; +/** + * @public + * The result of a bulk write. + */ +class BulkWriteResult { + static generateIdMap(ids) { + const idMap = {}; + for (const doc of ids) { + idMap[doc.index] = doc._id; + } + return idMap; + } + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult) { + this.result = bulkResult; + this.insertedCount = this.result.nInserted ?? 0; + this.matchedCount = this.result.nMatched ?? 0; + this.modifiedCount = this.result.nModified ?? 0; + this.deletedCount = this.result.nRemoved ?? 0; + this.upsertedCount = this.result.upserted.length ?? 0; + this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted); + this.insertedIds = BulkWriteResult.generateIdMap(this.result.insertedIds); + Object.defineProperty(this, 'result', { value: this.result, enumerable: false }); + } + /** 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 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 }); + } + } + toString() { + return `BulkWriteResult(${this.result})`; + } + isOk() { + return this.result.ok === 1; + } +} +exports.BulkWriteResult = BulkWriteResult; +/** + * An error representing a failure by the server to apply the requested write concern to the bulk operation. + * @public + * @category Error + */ +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; + } + toJSON() { + return this[kServerError]; + } + toString() { + return `WriteConcernError(${this.errmsg})`; + } +} +exports.WriteConcernError = WriteConcernError; +/** + * An error that occurred during a BulkWrite on the server. + * @public + * @category Error + */ +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; +/** 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; + } + // 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 + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + 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) { + 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 + */ +class MongoBulkWriteError extends error_1.MongoServerError { + /** Creates a new MongoBulkWriteError */ + constructor(error, result) { + 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 = error.writeErrors ?? []; + } + 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; +/** + * A builder object that is returned from {@link BulkOperationBase#find}. + * Is used to build a write operation that involves a query filter. + * + * @public + */ +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; + } + /** Specifies hint for the bulk operation. */ + hint(hint) { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + this.bulkOperation.s.currentOp.hint = hint; + return this; + } +} +exports.FindOperators = FindOperators; +/** + * 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 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 + * ```ts + * 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 + * ```ts + * 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; + } + async execute(options = {}) { + if (this.s.executed) { + throw new error_1.MongoBatchReExecutionError(); + } + 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) { + throw new error_1.MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + } + 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); + } + /** + * 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; + } +} +exports.BulkOperationBase = BulkOperationBase; +Object.defineProperty(BulkOperationBase.prototype, 'length', { + enumerable: true, + get() { + return this.s.currentIndex; + } +}); +function shouldForceServerObjectId(bulkOperation) { + 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) { + 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/2_PAC/node_modules/mongodb/lib/bulk/common.js.map b/2_PAC/node_modules/mongodb/lib/bulk/common.js.map new file mode 100644 index 00000000..b4201c78 --- /dev/null +++ b/2_PAC/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,kCAAuF;AAEvF,oCAOkB;AAGlB,iDAA6F;AAC7F,uEAAmE;AACnE,iDAAuD;AACvD,uDAAkE;AAClE,iDAA6F;AAI7F,oCAOkB;AAClB,oDAAgD;AAEhD,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CA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S,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/2_PAC/node_modules/mongodb/lib/bulk/ordered.js b/2_PAC/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 00000000..667f724f --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,67 @@ +"use strict"; +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 { + /** @internal */ + constructor(collection, options) { + super(collection, options, true); + } + 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; + } +} +exports.OrderedBulkOperation = OrderedBulkOperation; +//# sourceMappingURL=ordered.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/bulk/ordered.js.map b/2_PAC/node_modules/mongodb/lib/bulk/ordered.js.map new file mode 100644 index 00000000..3f16a990 --- /dev/null +++ b/2_PAC/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,gBAAgB;IAChB,YAAY,UAAsB,EAAE,OAAyB;QAC3D,KAAK,CAAC,UAAU,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,mBAAmB,CACjB,SAAoB,EACpB,QAAsD;QAEtD,mBAAmB;QACnB,MAAM,QAAQ,GAAG,IAAI,CAAC,mBAAmB,CAAC,QAAQ,EAAE;YAClD,SAAS,EAAE,KAAK;YAChB,oEAAoE;YACpE,wEAAwE;YACxE,eAAe,EAAE,KAAK;SAChB,CAAC,CAAC;QAEV,0DAA0D;QAC1D,IAAI,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,iBA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AAC,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;AAzED,oDAyEC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/bulk/unordered.js b/2_PAC/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 00000000..14b8f038 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,92 @@ +"use strict"; +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 { + /** @internal */ + constructor(collection, options) { + super(collection, options, false); + } + 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; + } +} +exports.UnorderedBulkOperation = UnorderedBulkOperation; +//# sourceMappingURL=unordered.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/bulk/unordered.js.map b/2_PAC/node_modules/mongodb/lib/bulk/unordered.js.map new file mode 100644 index 00000000..22bfa5d3 --- /dev/null +++ b/2_PAC/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,gBAAgB;IAChB,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;YAEhB,oEAAoE;YACpE,wEAAwE;YACxE,eAAe,EAAE,KAAK;SAChB,CAAC,CAAC;QAEV,0DAA0D;QAC1D,IAAI,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC,iBAAiB,EAAE;YACxC,iDAAiD;YACjD,MAAM,IAAI,iCAAyB,CACjC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AAC,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;AAnGD,wDAmGC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/change_stream.js b/2_PAC/node_modules/mongodb/lib/change_stream.js new file mode 100644 index 00000000..d07ec517 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/change_stream.js @@ -0,0 +1,396 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChangeStream = void 0; +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(); + 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 => { + if (eventName === 'change' && this.listenerCount('change') === 0 && this.cursor) { + this[kCursorStream]?.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() { + return this.cursor?.resumeToken; + } + /** Check if there is any document still available in the Change Stream */ + async hasNext() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const hasNext = await this.cursor.hasNext(); + return hasNext; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + /** Get the next available document from the Change Stream. */ + async next() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.next(); + const processedChange = this._processChange(change ?? null); + return processedChange; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + async tryNext() { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.tryNext(); + return change ?? null; + } + catch (error) { + try { + await this._processErrorIteratorMode(error); + } + catch (error) { + try { + await this.close(); + } + catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + async *[Symbol.asyncIterator]() { + if (this.closed) { + return; + } + try { + // Change streams run indefinitely as long as errors are resumable + // So the only loop breaking condition is if `next()` throws + while (true) { + yield await this.next(); + } + } + finally { + try { + await this.close(); + } + catch { + // we're not concerned with errors from close() + } + } + } + /** Is the cursor closed */ + get closed() { + return this[kClosed] || this.cursor.closed; + } + /** Close the Change Stream */ + async close() { + this[kClosed] = true; + const cursor = this.cursor; + try { + await cursor.close(); + } + finally { + this._endStream(); + } + } + /** + * 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().catch(() => null); + } + /** @internal */ + _streamEvents(cursor) { + 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 */ + _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 */ + async _processErrorIteratorMode(changeStreamError) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new error_1.MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + if (!(0, error_1.isResumableError)(changeStreamError, this.cursor.maxWireVersion)) { + try { + await this.close(); + } + catch { + // ignore errors from close + } + throw changeStreamError; + } + await this.cursor.close().catch(() => null); + const topology = (0, utils_1.getTopology)(this.parent); + try { + await topology.selectServerAsync(this.cursor.readPreference, {}); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + } + catch { + // if the topology can't reconnect, close the stream + await this.close(); + throw 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/2_PAC/node_modules/mongodb/lib/change_stream.js.map b/2_PAC/node_modules/mongodb/lib/change_stream.js.map new file mode 100644 index 00000000..a92b97e7 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/change_stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"change_stream.js","sourceRoot":"","sources":["../src/change_stream.ts"],"names":[],"mappings":";;;AAGA,6CAA0C;AAC1C,2CAAoG;AAEpG,wEAA8F;AAC9F,6BAA0B;AAC1B,mCAMiB;AACjB,iDAA6C;AAC7C,+CAA+D;AAK/D,mCAAuE;AAEvE,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAC7C,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC;AAE7B,MAAM,qBAAqB,GAAG;IAC5B,aAAa;IACb,YAAY;IACZ,sBAAsB;IACtB,cAAc;IACd,0BAA0B;IAC1B,oBAAoB;CACZ,CAAC;AAEX,MAAM,mBAAmB,GAAG;IAC1B,UAAU,EAAE,MAAM,CAAC,YAAY,CAAC;IAChC,QAAQ,EAAE,MAAM,CAAC,UAAU,CAAC;IA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AC,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,CAAC;SACzE;QAAC,MAAM;YACN,oDAAoD;YACpD,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;YACnB,MAAM,iBAAiB,CAAC;SACzB;IACH,CAAC;;AAlaH,oCAmaC;AAhZC,aAAa;AACG,qBAAQ,GAAG,oBAAQ,CAAC;AACpC,aAAa;AACG,iBAAI,GAAG,gBAAI,CAAC;AAC5B,aAAa;AACG,iBAAI,GAAG,gBAAI,CAAC;AAC5B,aAAa;AACG,kBAAK,GAAG,iBAAK,CAAC;AAC9B;;;;;GAKG;AACa,mBAAM,GAAG,kBAAM,CAAC;AAChC,aAAa;AACG,gBAAG,GAAG,eAAG,CAAC;AAC1B,aAAa;AACG,kBAAK,GAAG,iBAAK,CAAC;AAC9B;;;GAGG;AACa,iCAAoB,GAAG,gCAAoB,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/auth/auth_provider.js b/2_PAC/node_modules/mongodb/lib/cmap/auth/auth_provider.js new file mode 100644 index 00000000..b9a840ee --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/auth_provider.js.map new file mode 100644 index 00000000..c03ab374 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/gssapi.js b/2_PAC/node_modules/mongodb/lib/cmap/auth/gssapi.js new file mode 100644 index 00000000..b14a01f4 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/auth/gssapi.js @@ -0,0 +1,188 @@ +"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) { + 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 = mechanismProperties.SERVICE_NAME ?? 'mongodb'; + performGSSAPICanonicalizeHostName(hostAddress.host, mechanismProperties, (err, host) => { + 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, 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/2_PAC/node_modules/mongodb/lib/cmap/auth/gssapi.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/gssapi.js.map new file mode 100644 index 00000000..76606515 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/auth/gssapi.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gssapi.js","sourceRoot":"","sources":["../../../src/cmap/auth/gssapi.ts"],"names":[],"mappings":";;;AAAA,2BAA2B;AAG3B,qCAAsD;AACtD,uCAMqB;AACrB,uCAA2C;AAC3C,mDAA4D;AAE5D,cAAc;AACD,QAAA,2BAA2B,GAAG,MAAM,CAAC,MAAM,CAAC;IACvD,EAAE,EAAE,IAAI;IACR,GAAG,EAAE,KAAK;IACV,IAAI,EAAE,MAAM;IACZ,OAAO,EAAE,SAAS;IAClB,iBAAiB,EAAE,mBAAmB;CAC9B,CAAC,CAAC;AAaZ,MAAa,MAAO,SAAQ,4BAAY;IAC7B,IAAI,CAAC,WAAwB,EAAE,QAAkB;QACxD,MAAM,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,WAAW,CAAC;QAChD,IAAI,WAAW,IAAI,IAAI;YACrB,OAAO,QAAQ,CACb,IAAI,oCAA4B,CAAC,gDAAgD,CAAC,CACnF,CAAC;QACJ,MAAM,EAAE,QAAQ,EAAE,GAAG,WAAW,CAAC;QACjC,SAAS,eAAe,CACtB,OAAiB,EACjB,EAAsD;YAEtD,OAAO,UAAU,CAAC,OAAO,CAAC,IAAA,UAAE,EAAC,gBAAgB,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,EAAE,CAAC,CAAC;QAC1E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b/lib/cmap/auth/mongo_credentials.js new file mode 100644 index 00000000..b16137c1 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js @@ -0,0 +1,126 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoCredentials = void 0; +const error_1 = require("../../error"); +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 + }; + } + } + 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() { + 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 = this.mechanismProperties.CANONICALIZE_HOST_NAME ?? false; + if (!Object.values(gssapi_1.GSSAPICanonicalizationValue).includes(canonicalization)) { + throw new error_1.MongoAPIError(`Invalid CANONICALIZE_HOST_NAME value: ${canonicalization}`); + } + } + static merge(creds, options) { + return new MongoCredentials({ + username: options.username ?? creds?.username ?? '', + password: options.password ?? creds?.password ?? '', + mechanism: options.mechanism ?? creds?.mechanism ?? providers_1.AuthMechanism.MONGODB_DEFAULT, + mechanismProperties: options.mechanismProperties ?? creds?.mechanismProperties ?? {}, + source: options.source ?? options.db ?? creds?.source ?? 'admin' + }); + } +} +exports.MongoCredentials = MongoCredentials; +//# sourceMappingURL=mongo_credentials.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/mongo_credentials.js.map new file mode 100644 index 00000000..7772df04 --- /dev/null +++ b/2_PAC/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,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,kBAAkB,CAAC;SACtC;QAED,6EAA6E;QAC7E,IAAI,KAAK,CAAC,cAAc,IAAI,CAAC,EAAE;YAC7B,OAAO,yBAAa,CAAC,kBAAkB,CAAC;SACzC;KACF;IAED,+BAA+B;IAC/B,OAAO,yBAAa,CAAC,UAAU,CAAC;AAClC,CAAC;AAqBD;;;GAGG;AACH,MAAa,gBAAgB;IAY3B,YAAY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B,IAAI,KAAK,EAAE,mBAAmB,IAAI,EAAE;YACpF,MAAM,EAAE,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,EAAE,IAAI,KAAK,EAAE,MAAM,IAAI,OAAO;SACjE,CAAC,CAAC;IACL,CAAC;CACF;AAlID,4CAkIC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/auth/mongocr.js b/2_PAC/node_modules/mongodb/lib/cmap/auth/mongocr.js new file mode 100644 index 00000000..f8afea2d --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/mongocr.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/mongocr.js.map new file mode 100644 index 00000000..62e4f979 --- /dev/null +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C,KAAK,CAAC,CAAC;gBAC/B,GAAG,CAAC,MAAM,CAAC,KAAK,GAAG,QAAQ,GAAG,aAAa,EAAE,MAAM,CAAC,CAAC;gBACrD,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;aACzB;YAED,MAAM,mBAAmB,GAAG;gBAC1B,YAAY,EAAE,CAAC;gBACf,IAAI,EAAE,QAAQ;gBACd,KAAK;gBACL,GAAG;aACJ,CAAC;YAEF,UAAU,CAAC,OAAO,CAAC,IAAA,UAAE,EAAC,GAAG,MAAM,OAAO,CAAC,EAAE,mBAAmB,EAAE,SAAS,EAAE,QAAQ,CAAC,CAAC;QACrF,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAxCD,0BAwCC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js b/2_PAC/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js new file mode 100644 index 00000000..3bd4b2ff --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js @@ -0,0 +1,237 @@ +"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 (!utils_1.ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) { + // throw because the serverNonce's leading 32 bytes must equal the client nonce's 32 bytes + // https://github.com/mongodb/specifications/blob/875446db44aade414011731840831f38a6c668df/source/auth/auth.rst#id11 + // 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': utils_1.ByteUtils.toBase64(serverNonce), + '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 + } + })); + } + const credentialProvider = (0, deps_1.getAwsCredentialProvider)(); + // Check if the AWS credential provider from the SDK is present. If not, + // use the old method. + if ('kModuleError' in credentialProvider) { + // 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); + }); + }); + }); + } + else { + /* + * Creates a credential provider that will attempt to find credentials from the + * following sources (listed in order of precedence): + * + * - Environment variables exposed via process.env + * - SSO credentials from token cache + * - Web identity token credentials + * - Shared credentials and config ini files + * - The EC2/ECS Instance Metadata Service + */ + const { fromNodeProviderChain } = credentialProvider; + const provider = fromNodeProviderChain(); + provider() + .then((creds) => { + done({ + AccessKeyId: creds.accessKeyId, + SecretAccessKey: creds.secretAccessKey, + Token: creds.sessionToken, + Expiration: creds.expiration + }); + }) + .catch((error) => { + callback(new error_1.MongoAWSError(error.message)); + }); + } +} +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/2_PAC/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/mongodb_aws.js.map new file mode 100644 index 00000000..6782b208 --- /dev/null +++ b/2_PAC/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,qCAA4D;AAC5D,uCAKqB;AACrB,uCAAsE;AACtE,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,CACN,IAAI,+BAAuB,CACzB,kEAAkE,CACnE,CACF,CAAC;YACF,OAAO;SACR;QAED,IAAI,CAAC,WAAW,CAAC,QAAQ,EAAE;YACzB,mBAAmB,CAAC,WAAW,EAAE,CAAC,GAAG,EAAE,eAAe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C,EACd,QAAQ,CACT,CAAC;IAEF,MAAM,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;QACtC,GAAG,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QAExB,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,CAAC,CAAC;QACjC,GAAG,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YACjB,IAAI,OAAO,CAAC,IAAI,KAAK,KAAK,EAAE;gBAC1B,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;gBAC1B,OAAO;aACR;YAED,IAAI;gBACF,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,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/2_PAC/node_modules/mongodb/lib/cmap/auth/plain.js b/2_PAC/node_modules/mongodb/lib/cmap/auth/plain.js new file mode 100644 index 00000000..e7153a58 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/plain.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/plain.js.map new file mode 100644 index 00000000..a03580a3 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/providers.js b/2_PAC/node_modules/mongodb/lib/cmap/auth/providers.js new file mode 100644 index 00000000..d287765f --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/providers.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/providers.js.map new file mode 100644 index 00000000..48b58e79 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/scram.js b/2_PAC/node_modules/mongodb/lib/cmap/auth/scram.js new file mode 100644 index 00000000..00a77ac0 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/scram.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/scram.js.map new file mode 100644 index 00000000..c94940db --- /dev/null +++ b/2_PAC/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,SAA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;QAAE,OAAO,GAAG,CAAC;IACpB,IAAI,MAAM,EAAE;QACV,IAAI,MAAM,CAAC,IAAI,IAAI,MAAM,CAAC,MAAM;YAAE,OAAO,IAAI,wBAAgB,CAAC,MAAM,CAAC,CAAC;KACvE;IACD,OAAO;AACT,CAAC;AAED,MAAa,SAAU,SAAQ,QAAQ;IACrC;QACE,KAAK,CAAC,MAAM,CAAC,CAAC;IAChB,CAAC;CACF;AAJD,8BAIC;AAED,MAAa,WAAY,SAAQ,QAAQ;IACvC;QACE,KAAK,CAAC,QAAQ,CAAC,CAAC;IAClB,CAAC;CACF;AAJD,kCAIC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/auth/x509.js b/2_PAC/node_modules/mongodb/lib/cmap/auth/x509.js new file mode 100644 index 00000000..02fe3853 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/auth/x509.js.map b/2_PAC/node_modules/mongodb/lib/cmap/auth/x509.js.map new file mode 100644 index 00000000..84af5792 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/command_monitoring_events.js b/2_PAC/node_modules/mongodb/lib/cmap/command_monitoring_events.js new file mode 100644 index 00000000..ec8fc61c --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/command_monitoring_events.js @@ -0,0 +1,242 @@ +"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) { + if (command instanceof commands_1.Msg) { + return (0, utils_1.deepCopy)(command.command); + } + if (command.query?.$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 (!reply) { + return reply; + } + 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/2_PAC/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map b/2_PAC/node_modules/mongodb/lib/cmap/command_monitoring_events.js.map new file mode 100644 index 00000000..0c259d49 --- /dev/null +++ b/2_PAC/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,yCAA2D;AAG3D;;;;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,IAAI,CAAC;SACrC;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;Q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ACjD,OAAO;YACL,EAAE,EAAE,CAAC;YACL,MAAM,EAAE;gBACN,EAAE,EAAE,IAAA,gBAAQ,EAAC,KAAK,CAAC,QAAQ,CAAC;gBAC5B,EAAE,EAAE,SAAS,CAAC,OAAO,CAAC;gBACtB,UAAU,EAAE,IAAA,gBAAQ,EAAC,KAAK,CAAC,SAAS,CAAC;aACtC;SACF,CAAC;KACH;IAED,OAAO,IAAA,gBAAQ,EAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;AACvD,CAAC;AAED,SAAS,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/2_PAC/node_modules/mongodb/lib/cmap/commands.js b/2_PAC/node_modules/mongodb/lib/cmap/commands.js new file mode 100644 index 00000000..45b3cbfb --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/commands.js @@ -0,0 +1,479 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BinMsg = exports.Msg = exports.Response = 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; +/** @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 ?? { + 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) { + // 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 = { + 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 ?? {}; + // 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 ?? { + 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) { + // 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 = { + 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/2_PAC/node_modules/mongodb/lib/cmap/commands.js.map b/2_PAC/node_modules/mongodb/lib/cmap/commands.js.map new file mode 100644 index 00000000..1ff2b08f --- /dev/null +++ b/2_PAC/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;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,IAAI,IAAI,GAAG,EAAE;YACrE,MAAM,WAAW,GAAa,EAAE,CAAC;YACjC,WAAW,CAAC,mBAAmB,CAAC,GAAG,IAAI,CAAC;YACxC,WAAW,CAAC,WAAW,GAAG,WAAW,CAAC;YACtC,MAAM,GAAG,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,CAAW,EAAE,WAAW,CAAC,CAAC;YACvE,IAAI,CAAC,SAAS,GAAG,CAAC,GAAG,CAAC,CAAC;SACxB;QAED,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;IACrB,CAAC;IAED,6BAA6B,CAAC,EAAE,oBAAoB,EAAwB;QAG1E,IAAI,oBAAoB,KAAK,KAAK,EAAE;YAClC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;SACxB;QAED,OAAO,EAAE,IAAI,EAAE,EAAE,WAAW,EAAE,KAAK,EAAE,EAAE,CAAC;IAC1C,CAAC;CACF;AA3HD,wBA2HC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/connect.js b/2_PAC/node_modules/mongodb/lib/cmap/connect.js new file mode 100644 index 00000000..8101b1eb --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/connect.js @@ -0,0 +1,394 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LEGAL_TCP_SOCKET_OPTIONS = exports.LEGAL_TLS_SOCKET_OPTIONS = exports.prepareHandshakeDocument = 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) => { + if (err || !socket) { + return callback(err); + } + let ConnectionType = options.connectionType ?? connection_1.Connection; + if (options.autoEncrypter) { + ConnectionType = connection_1.CryptoConnection; + } + performInitialHandshake(new ConnectionType(socket, options), options, callback); + }); +} +exports.connect = connect; +function checkSupportedServer(hello, options) { + 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 ${JSON.stringify(hello.maxWireVersion) ?? 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?.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); + }); + }); +} +/** + * @internal + * + * This function is only exposed for testing purposes. + */ +function prepareHandshakeDocument(authContext, callback) { + const options = authContext.options; + const compressors = options.compressors ? options.compressors : []; + const { serverApi } = authContext.connection; + const handshakeDoc = { + [serverApi?.version ? 'hello' : constants_1.LEGACY_HELLO_COMMAND]: 1, + helloOk: true, + client: options.metadata || (0, utils_1.makeClientMetadata)(options), + compression: compressors + }; + if (options.loadBalanced === true) { + handshakeDoc.loadBalanced = true; + } + 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); +} +exports.prepareHandshakeDocument = prepareHandshakeDocument; +/** @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) { + 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; + 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) { + const hostAddress = utils_1.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); + 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/2_PAC/node_modules/mongodb/lib/cmap/connect.js.map b/2_PAC/node_modules/mongodb/lib/cmap/connect.js.map new file mode 100644 index 00000000..b46554b0 --- /dev/null +++ b/2_PAC/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,gD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AsB,CAAC,IAA2B,EAAE,GAAU;IACrE,QAAQ,IAAI,EAAE;QACZ,KAAK,OAAO;YACV,OAAO,IAAI,yBAAiB,CAAC,GAAG,CAAC,CAAC;QACpC,KAAK,SAAS;YACZ,OAAO,IAAI,gCAAwB,CAAC,sBAAsB,CAAC,CAAC;QAC9D,KAAK,OAAO;YACV,OAAO,IAAI,yBAAiB,CAAC,mBAAmB,CAAC,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/2_PAC/node_modules/mongodb/lib/cmap/connection.js b/2_PAC/node_modules/mongodb/lib/cmap/connection.js new file mode 100644 index 00000000..87ecacf1 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/connection.js @@ -0,0 +1,498 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.hasSessionSupport = exports.CryptoConnection = exports.Connection = void 0; +const timers_1 = require("timers"); +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 kDelayedTimeoutId = Symbol('delayedTimeoutId'); +const INVALID_QUEUE_SIZE = 'Connection internal queue contains more than 1 operation description'; +/** @internal */ +class Connection extends mongo_types_1.TypedEventEmitter { + constructor(stream, options) { + 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 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: 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() { + 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() { + return this.hello?.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) { + (0, timers_1.clearTimeout)(delayedTimeoutId); + this[kDelayedTimeoutId] = null; + } + // always emit the message, in case we are streaming + this.emit('message', message); + let operationDescription = this[kQueue].get(message.responseTo); + if (!operationDescription && this.isMonitoringConnection) { + // This is how we recover when the initial hello's requestId is not + // the responseTo when hello responses have been skipped: + // First check if the map is of invalid size + if (this[kQueue].size > 1) { + this.onError(new error_1.MongoRuntimeError(INVALID_QUEUE_SIZE)); + } + else { + // Get the first orphaned operation description. + const entry = this[kQueue].entries().next(); + if (entry.value != null) { + const [requestId, orphaned] = entry.value; + // If the orphaned operation description exists then set it. + operationDescription = orphaned; + // Remove the entry with the bad request id from the queue. + this[kQueue].delete(requestId); + } + } + } + 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) { + // If the operation description check above does find an orphaned + // description and sets the operationDescription then this line will put one + // back in the queue with the correct requestId and will resolve not being able + // to find the next one via the responseTo of the next streaming hello. + 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), 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, 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) { + const readPreference = (0, shared_1.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 = (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); + } + } +} +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; + } + // Save sort or indexKeys based on the command being run + // the encrypt API serializes our JS objects to BSON to pass to the native code layer + // and then deserializes the encrypted result, the protocol level components + // of the command (ex. sort) are then converted to JS objects potentially losing + // import key order information. These fields are never encrypted so we can save the values + // from before the encryption and replace them after encryption has been performed + const sort = cmd.find || cmd.findAndModify ? cmd.sort : null; + const indexKeys = cmd.createIndexes + ? cmd.indexes.map((index) => index.key) + : null; + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + // Replace the saved values + if (sort != null && (cmd.find || cmd.findAndModify)) { + encrypted.sort = sort; + } + if (indexKeys != null && cmd.createIndexes) { + for (const [offset, index] of indexKeys.entries()) { + encrypted.indexes[offset].key = index; + } + } + 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(); + } + const { remoteAddress, remotePort } = stream; + if (typeof remoteAddress === 'string' && typeof remotePort === 'number') { + return utils_1.HostAddress.fromHostPort(remoteAddress, remotePort).toString(); + } + return (0, utils_1.uuidV4)().toString('hex'); +} +function write(conn, command, options, callback) { + options = options ?? {}; + const operationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + 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) => { + // Command monitoring spec states that if ok is 1, then we must always emit + // a command suceeded event, even if there's an error. Write concern errors + // will have an ok: 1 in their reply. + if (err && reply?.ok !== 1) { + 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') { + // Since we're passing through the reply with the write concern error now, we + // need it not to be provided to the original callback in this case so + // retryability does not get tricked into thinking the command actually + // succeeded. + callback(err, err instanceof error_1.MongoWriteConcernError ? undefined : 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/2_PAC/node_modules/mongodb/lib/cmap/connection.js.map b/2_PAC/node_modules/mongodb/lib/cmap/connection.js.map new file mode 100644 index 00000000..54623a3f --- /dev/null +++ b/2_PAC/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,mCAAkD;AAGlD,4CASsB;AAEtB,oCAQkB;AAElB,gDAAsE;AAEtE,0CAAqF;AACrF,oCASkB;AAGlB,2EAIqC;AACrC,yCAAoF;AAEpF,qDAAuE;AACvE,6DAAmF;AACnF,mDAAsE;AAEtE,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,MAAM,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;AAC/B,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAC/C,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAA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,IAAI,CAAC,IAAI,CACP,UAAU,CAAC,iBAAiB,EAC5B,IAAI,iDAAqB,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,oBAAoB,CAAC,OAAO,CAAC,CAC9E,CAAC;iBACH;aACF;YAED,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;gBAClC,6EAA6E;gBAC7E,sEAAsE;gBACtE,uEAAuE;gBACvE,aAAa;gBACb,QAAQ,CAAC,GAAG,EAAE,GAAG,YAAY,8BAAsB,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC;aAC1E;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/2_PAC/node_modules/mongodb/lib/cmap/connection_pool.js b/2_PAC/node_modules/mongodb/lib/cmap/connection_pool.js new file mode 100644 index 00000000..34a950cf --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/connection_pool.js @@ -0,0 +1,591 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectionPool = exports.PoolState = void 0; +const timers_1 = require("timers"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +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 kServer = Symbol('server'); +/** @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'); +/** @internal */ +const kPoolState = Symbol('poolState'); +/** @internal */ +exports.PoolState = Object.freeze({ + paused: 'paused', + ready: 'ready', + closed: 'closed' +}); +/** + * A pool of connections which dynamically resizes, and emit events related to pool activity + * @internal + */ +class ConnectionPool extends mongo_types_1.TypedEventEmitter { + constructor(server, options) { + super(); + this.options = Object.freeze({ + ...options, + connectionType: connection_1.Connection, + maxPoolSize: options.maxPoolSize ?? 100, + minPoolSize: options.minPoolSize ?? 0, + maxConnecting: options.maxConnecting ?? 2, + maxIdleTimeMS: options.maxIdleTimeMS ?? 0, + waitQueueTimeoutMS: options.waitQueueTimeoutMS ?? 0, + minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100, + 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[kPoolState] = exports.PoolState.paused; + this[kServer] = server; + this[kConnections] = new utils_1.List(); + this[kPending] = 0; + this[kCheckedOut] = new Set(); + 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 utils_1.List(); + this[kMetrics] = new metrics_1.ConnectionPoolMetrics(); + this[kProcessingWaitQueue] = false; + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new connection_pool_events_1.ConnectionPoolCreatedEvent(this)); + }); + } + /** The address of the endpoint the pool is connected to */ + get address() { + return this.options.hostAddress.toString(); + } + /** + * Check if the pool has been closed + * + * TODO(NODE-3263): We can remove this property once shell no longer needs it + */ + get closed() { + return this[kPoolState] === exports.PoolState.closed; + } + /** 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].size; + } + get waitQueueSize() { + return this[kWaitQueue].length; + } + get loadBalanced() { + return this.options.loadBalanced; + } + get serviceGenerations() { + return this[kServiceGenerations]; + } + get serverError() { + return this[kServer].description.error; + } + /** + * This is exposed ONLY for use in mongosh, to enable + * killing all connections if a user quits the shell with + * operations in progress. + * + * This property may be removed as a part of NODE-3263. + */ + get checkedOutConnections() { + return this[kCheckedOut]; + } + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + waitQueueErrorMetrics() { + return this[kMetrics].info(this.options.maxPoolSize); + } + /** + * Set the pool state to "ready" + */ + ready() { + if (this[kPoolState] !== exports.PoolState.paused) { + return; + } + this[kPoolState] = exports.PoolState.ready; + this.emit(ConnectionPool.CONNECTION_POOL_READY, new connection_pool_events_1.ConnectionPoolReadyEvent(this)); + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this.ensureMinPoolSize(); + } + /** + * 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)); + 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(() => this.processWaitQueue()); + } + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection) { + if (!this[kCheckedOut].has(connection)) { + return; + } + const poolClosed = this.closed; + const stale = this.connectionIsStale(connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + this[kCheckedOut].delete(connection); + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new connection_pool_events_1.ConnectionCheckedInEvent(this, connection)); + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + this.destroyConnection(connection, reason); + } + process.nextTick(() => this.processWaitQueue()); + } + /** + * 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(options = {}) { + if (this.closed) { + return; + } + // handle load balanced case + if (this.loadBalanced) { + const { serviceId } = options; + if (!serviceId) { + throw new error_1.MongoRuntimeError('ConnectionPool.clear() called in load balanced mode with no 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) { + 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); + } + this.emit(ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { serviceId })); + return; + } + // handle non load-balanced case + const interruptInUseConnections = options.interruptInUseConnections ?? false; + const oldGeneration = this[kGeneration]; + this[kGeneration] += 1; + const alreadyPaused = this[kPoolState] === exports.PoolState.paused; + this[kPoolState] = exports.PoolState.paused; + this.clearMinPoolSizeTimer(); + if (!alreadyPaused) { + this.emit(ConnectionPool.CONNECTION_POOL_CLEARED, new connection_pool_events_1.ConnectionPoolClearedEvent(this, { interruptInUseConnections })); + } + if (interruptInUseConnections) { + process.nextTick(() => this.interruptInUseConnections(oldGeneration)); + } + this.processWaitQueue(); + } + /** + * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError. + * + * Only connections where `connection.generation <= minGeneration` are killed. + */ + interruptInUseConnections(minGeneration) { + for (const connection of this[kCheckedOut]) { + if (connection.generation <= minGeneration) { + this.checkIn(connection); + connection.onError(new errors_1.PoolClearedOnNetworkError(this)); + } + } + } + close(_options, _cb) { + let options = _options; + const callback = (_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'); + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + this[kPoolState] = exports.PoolState.closed; + this.clearMinPoolSizeTimer(); + this.processWaitQueue(); + (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); + } + }); + }); + } + /** Clear the min pool size timer */ + clearMinPoolSizeTimer() { + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + (0, timers_1.clearTimeout)(minPoolSizeTimer); + } + } + destroyConnection(connection, reason) { + this.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, connection, reason)); + // destroy the connection + process.nextTick(() => connection.destroy()); + } + connectionIsStale(connection) { + const serviceId = connection.serviceId; + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + return connection.generation !== generation; + } + return connection.generation !== this[kGeneration]; + } + connectionIsIdle(connection) { + return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS); + } + /** + * Destroys a connection if the connection is perished. + * + * @returns `true` if the connection was destroyed, `false` otherwise. + */ + destroyConnectionIfPerished(connection) { + const isStale = this.connectionIsStale(connection); + const isIdle = this.connectionIsIdle(connection); + if (!isStale && !isIdle && !connection.closed) { + return false; + } + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + this.destroyConnection(connection, reason); + return true; + } + createConnection(callback) { + const connectOptions = { + ...this.options, + id: this[kConnectionCounter].next().value, + generation: this[kGeneration], + cancellationToken: this[kCancellationToken] + }; + this[kPending]++; + // This is our version of a "virtual" no-I/O connection as the spec requires + this.emit(ConnectionPool.CONNECTION_CREATED, new connection_pool_events_1.ConnectionCreatedEvent(this, { id: connectOptions.id })); + (0, connect_1.connect)(connectOptions, (err, connection) => { + if (err || !connection) { + this[kPending]--; + this.emit(ConnectionPool.CONNECTION_CLOSED, new connection_pool_events_1.ConnectionClosedEvent(this, { id: connectOptions.id, serviceId: undefined }, 'error')); + if (err instanceof error_1.MongoNetworkError || err instanceof error_1.MongoServerError) { + err.connectionGeneration = connectOptions.generation; + } + callback(err ?? new error_1.MongoRuntimeError('Connection creation failed without error')); + return; + } + // The pool might have closed since we started trying to create a connection + if (this[kPoolState] !== exports.PoolState.ready) { + this[kPending]--; + connection.destroy({ force: true }); + callback(this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this)); + 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) => this.emit(event, e)); + } + if (this.loadBalanced) { + connection.on(connection_1.Connection.PINNED, pinType => this[kMetrics].markPinned(pinType)); + connection.on(connection_1.Connection.UNPINNED, pinType => this[kMetrics].markUnpinned(pinType)); + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = this.serviceGenerations.get(sid))) { + connection.generation = generation; + } + else { + this.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + connection.markAvailable(); + this.emit(ConnectionPool.CONNECTION_READY, new connection_pool_events_1.ConnectionReadyEvent(this, connection)); + this[kPending]--; + callback(undefined, connection); + return; + }); + } + ensureMinPoolSize() { + const minPoolSize = this.options.minPoolSize; + if (this[kPoolState] !== exports.PoolState.ready || minPoolSize === 0) { + return; + } + this[kConnections].prune(connection => this.destroyConnectionIfPerished(connection)); + if (this.totalConnectionCount < minPoolSize && + this.pendingConnectionCount < this.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 + this.createConnection((err, connection) => { + if (err) { + this[kServer].handleError(err); + } + if (!err && connection) { + this[kConnections].push(connection); + process.nextTick(() => this.processWaitQueue()); + } + if (this[kPoolState] === exports.PoolState.ready) { + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS); + } + }); + } + else { + (0, timers_1.clearTimeout)(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = (0, timers_1.setTimeout)(() => this.ensureMinPoolSize(), this.options.minPoolSizeCheckFrequencyMS); + } + } + processWaitQueue() { + if (this[kProcessingWaitQueue]) { + return; + } + this[kProcessingWaitQueue] = true; + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].first(); + if (!waitQueueMember) { + this[kWaitQueue].shift(); + continue; + } + if (waitQueueMember[kCancelled]) { + this[kWaitQueue].shift(); + continue; + } + if (this[kPoolState] !== exports.PoolState.ready) { + const reason = this.closed ? 'poolClosed' : 'connectionError'; + const error = this.closed ? new errors_1.PoolClosedError(this) : new errors_1.PoolClearedError(this); + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, reason)); + if (waitQueueMember.timer) { + (0, timers_1.clearTimeout)(waitQueueMember.timer); + } + this[kWaitQueue].shift(); + waitQueueMember.callback(error); + continue; + } + if (!this.availableConnectionCount) { + break; + } + const connection = this[kConnections].shift(); + if (!connection) { + break; + } + if (!this.destroyConnectionIfPerished(connection)) { + this[kCheckedOut].add(connection); + this.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection)); + if (waitQueueMember.timer) { + (0, timers_1.clearTimeout)(waitQueueMember.timer); + } + this[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + } + } + const { maxPoolSize, maxConnecting } = this.options; + while (this.waitQueueSize > 0 && + this.pendingConnectionCount < maxConnecting && + (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize)) { + const waitQueueMember = this[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + continue; + } + this.createConnection((err, connection) => { + if (waitQueueMember[kCancelled]) { + if (!err && connection) { + this[kConnections].push(connection); + } + } + else { + if (err) { + this.emit(ConnectionPool.CONNECTION_CHECK_OUT_FAILED, new connection_pool_events_1.ConnectionCheckOutFailedEvent(this, 'connectionError')); + } + else if (connection) { + this[kCheckedOut].add(connection); + this.emit(ConnectionPool.CONNECTION_CHECKED_OUT, new connection_pool_events_1.ConnectionCheckedOutEvent(this, connection)); + } + if (waitQueueMember.timer) { + (0, timers_1.clearTimeout)(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + } + process.nextTick(() => this.processWaitQueue()); + }); + } + this[kProcessingWaitQueue] = false; + } +} +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 each time the connection pool is marked ready + * @event + */ +ConnectionPool.CONNECTION_POOL_READY = constants_1.CONNECTION_POOL_READY; +/** + * 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; +//# sourceMappingURL=connection_pool.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/connection_pool.js.map b/2_PAC/node_modules/mongodb/lib/cmap/connection_pool.js.map new file mode 100644 index 00000000..9ee26f44 --- /dev/null +++ b/2_PAC/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,mCAAkD;AAGlD,4CAasB;AACtB,oCAMkB;AAClB,gDAAsE;AAEtE,oCAAkE;AAClE,uCAAoC;AACpC,6CAA+E;AAC/E,qEAYkC;AAClC,qCAKkB;AAClB,uCAAkD;AAElD,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MA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AAqB,GAAG,iCAAqB,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/connection_pool_events.js b/2_PAC/node_modules/mongodb/lib/cmap/connection_pool_events.js new file mode 100644 index 00000000..f13528d4 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/connection_pool_events.js @@ -0,0 +1,160 @@ +"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.ConnectionPoolReadyEvent = 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 ready + * @public + * @category Event + */ +class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool) { + super(pool); + } +} +exports.ConnectionPoolReadyEvent = ConnectionPoolReadyEvent; +/** + * 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, options = {}) { + super(pool); + this.serviceId = options.serviceId; + this.interruptInUseConnections = options.interruptInUseConnections; + } +} +exports.ConnectionPoolClearedEvent = ConnectionPoolClearedEvent; +//# sourceMappingURL=connection_pool_events.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/connection_pool_events.js.map b/2_PAC/node_modules/mongodb/lib/cmap/connection_pool_events.js.map new file mode 100644 index 00000000..22ad3af4 --- /dev/null +++ b/2_PAC/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,EAAE,CAAC;QACvB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;CACF;AAXD,sEAWC;AAED;;;;GAIG;AACH,MAAa,0BAA2B,SAAQ,6BAA6B;IAI3E,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;IAC9B,CAAC;CACF;AATD,gEASC;AAED;;;;GAIG;AACH,MAAa,wBAAyB,SAAQ,6BAA6B;IACzE,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;CACF;AALD,4DAKC;AAED;;;;GAIG;AACH,MAAa,yBAA0B,SAAQ,6BAA6B;IAC1E,gBAAgB;IAChB,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,CAAC,CAAC;IACd,CAAC;CACF;AALD,8DAKC;AAED;;;;GAIG;AACH,MAAa,sBAAuB,SAAQ,6BAA6B;IAIvE,gBAAgB;IAChB,YAAY,IAAoB,EAAE,UAAwC;QACxE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ASC;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;IAM3E,gBAAgB;IAChB,YACE,IAAoB,EACpB,UAAyE,EAAE;QAE3E,KAAK,CAAC,IAAI,CAAC,CAAC;QACZ,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC;IACrE,CAAC;CACF;AAfD,gEAeC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/errors.js b/2_PAC/node_modules/mongodb/lib/cmap/errors.js new file mode 100644 index 00000000..4ffd5b41 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/errors.js @@ -0,0 +1,64 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WaitQueueTimeoutError = exports.PoolClearedOnNetworkError = exports.PoolClearedError = 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 indicating a connection pool is currently paused + * @category Error + */ +class PoolClearedError extends error_1.MongoNetworkError { + constructor(pool, message) { + const errorMessage = message + ? message + : `Connection pool for ${pool.address} was cleared because another operation failed with: "${pool.serverError?.message}"`; + super(errorMessage); + this.address = pool.address; + this.addErrorLabel(error_1.MongoErrorLabel.RetryableWriteError); + } + get name() { + return 'MongoPoolClearedError'; + } +} +exports.PoolClearedError = PoolClearedError; +/** + * An error indicating that a connection pool has been cleared after the monitor for that server timed out. + * @category Error + */ +class PoolClearedOnNetworkError extends PoolClearedError { + constructor(pool) { + super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`); + } + get name() { + return 'PoolClearedOnNetworkError'; + } +} +exports.PoolClearedOnNetworkError = PoolClearedOnNetworkError; +/** + * 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/2_PAC/node_modules/mongodb/lib/cmap/errors.js.map b/2_PAC/node_modules/mongodb/lib/cmap/errors.js.map new file mode 100644 index 00000000..9ea0e0ba --- /dev/null +++ b/2_PAC/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,oCAAgF;AAGhF;;;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,gBAAiB,SAAQ,yBAAiB;IAIrD,YAAY,IAAoB,EAAE,OAAgB;QAChD,MAAM,YAAY,GAAG,OAAO;YAC1B,CAAC,CAAC,OAAO;YACT,CAAC,CAAC,uBAAuB,IAAI,CAAC,OAAO,wDAAwD,IAAI,CAAC,WAAW,EAAE,OAAO,GAAG,CAAC;QAC5H,KAAK,CAAC,YAAY,CAAC,CAAC;QACpB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAE5B,IAAI,CAAC,aAAa,CAAC,uBAAe,CAAC,mBAAmB,CAAC,CAAC;IAC1D,CAAC;IAED,IAAa,IAAI;QACf,OAAO,uBAAuB,CAAC;IACjC,CAAC;CACF;AAjBD,4CAiBC;AAED;;;GAGG;AACH,MAAa,yBAA0B,SAAQ,gBAAgB;IAC7D,YAAY,IAAoB;QAC9B,KAAK,CAAC,IAAI,EAAE,iBAAiB,IAAI,CAAC,OAAO,4CAA4C,CAAC,CAAC;IACzF,CAAC;IAED,IAAa,IAAI;QACf,OAAO,2BAA2B,CAAC;IACrC,CAAC;CACF;AARD,8DAQC;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/2_PAC/node_modules/mongodb/lib/cmap/message_stream.js b/2_PAC/node_modules/mongodb/lib/cmap/message_stream.js new file mode 100644 index 00000000..fe4fafe5 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/message_stream.js @@ -0,0 +1,156 @@ +"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) { + const agreedCompressor = operationDescription.agreedCompressor ?? 'none'; + if (agreedCompressor === '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); + const options = { + agreedCompressor, + zlibCompressionLevel: operationDescription.zlibCompressionLevel ?? 0 + }; + // Compress the message body + (0, compression_1.compress)(options, messageToBeCompressed).then(compressedMessage => { + // 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[agreedCompressor], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }, error => { + operationDescription.cb(error); + }); + } +} +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]; + const sizeOfMessage = buffer.getInt32(); + if (sizeOfMessage == null) { + return callback(); + } + if (sizeOfMessage < 0) { + return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + } + if (sizeOfMessage > stream.maxBsonMessageSize) { + return callback(new error_1.MongoParseError(`Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}`)); + } + if (sizeOfMessage > buffer.length) { + return callback(); + } + 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? + const sizeOfMessage = buffer.getInt32(); + if (sizeOfMessage != null && 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.subarray(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()) { + return processIncomingData(stream, callback); + } + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + return processIncomingData(stream, callback); + } + return callback(); + } + 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).then(messageBody => { + if (messageBody.length !== messageHeader.length) { + return callback(new error_1.MongoDecompressionError('Message body and message header must be the same length')); + } + // 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()) { + return processIncomingData(stream, callback); + } + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + if (buffer.length >= 4) { + return processIncomingData(stream, callback); + } + return callback(); + }, error => { + return callback(error); + }); +} +//# sourceMappingURL=message_stream.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/message_stream.js.map b/2_PAC/node_modules/mongodb/lib/cmap/message_stream.js.map new file mode 100644 index 00000000..a027b82a --- /dev/null +++ b/2_PAC/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,yCAA4F;AAC5F,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;AAuBjC;;;;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,kB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AC,CAAC;IAEhE,sCAAsC;IACtC,YAAY,GAAG,aAAa,CAAC,MAAM,KAAK,kBAAM,CAAC,CAAC,CAAC,iBAAM,CAAC,CAAC,CAAC,mBAAQ,CAAC;IACnE,IAAA,wBAAU,EAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC,IAAI,CAC7C,WAAW,CAAC,EAAE;QACZ,IAAI,WAAW,CAAC,MAAM,KAAK,aAAa,CAAC,MAAM,EAAE;YAC/C,OAAO,QAAQ,CACb,IAAI,+BAAuB,CAAC,yDAAyD,CAAC,CACvF,CAAC;SACH;QAED,uDAAuD;QACvD,yEAAyE;QACzE,8DAA8D;QAC9D,IAAI,sBAAsB,EAAE,EAAE;YAC5B,OAAO,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;SAC9C;QACD,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,WAAW,CAAC,CAAC,CAAC;QAE9E,IAAI,MAAM,CAAC,MAAM,IAAI,CAAC,EAAE;YACtB,OAAO,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;SAC9C;QACD,OAAO,QAAQ,EAAE,CAAC;IACpB,CAAC,EACD,KAAK,CAAC,EAAE;QACN,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC,CACF,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/metrics.js b/2_PAC/node_modules/mongodb/lib/cmap/metrics.js new file mode 100644 index 00000000..89c22109 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/metrics.js.map b/2_PAC/node_modules/mongodb/lib/cmap/metrics.js.map new file mode 100644 index 00000000..270cefe7 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cmap/stream_description.js b/2_PAC/node_modules/mongodb/lib/cmap/stream_description.js new file mode 100644 index 00000000..d2337b76 --- /dev/null +++ b/2_PAC/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?.logicalSessionTimeoutMinutes; + this.loadBalanced = !!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 => response.compression?.includes(c))[0]; + } + } +} +exports.StreamDescription = StreamDescription; +//# sourceMappingURL=stream_description.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/stream_description.js.map b/2_PAC/node_modules/mongodb/lib/cmap/stream_description.js.map new file mode 100644 index 00000000..fabbada0 --- /dev/null +++ b/2_PAC/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,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,QAAQ,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;SACtF;IACH,CAAC;CACF;AArDD,8CAqDC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/compression.js b/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/compression.js new file mode 100644 index 00000000..d2ecc6ed --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/compression.js @@ -0,0 +1,81 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.decompress = exports.compress = exports.uncompressibleCommands = exports.Compressor = void 0; +const util_1 = require("util"); +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 ZSTD_COMPRESSION_LEVEL = 3; +const zlibInflate = (0, util_1.promisify)(zlib.inflate.bind(zlib)); +const zlibDeflate = (0, util_1.promisify)(zlib.deflate.bind(zlib)); +// Facilitate compressing a message using an agreed compressor +async function compress(options, dataToBeCompressed) { + const zlibOptions = {}; + switch (options.agreedCompressor) { + case 'snappy': + if ('kModuleError' in deps_1.Snappy) { + throw deps_1.Snappy['kModuleError']; + } + return deps_1.Snappy.compress(dataToBeCompressed); + case 'zstd': + if ('kModuleError' in deps_1.ZStandard) { + throw deps_1.ZStandard['kModuleError']; + } + return deps_1.ZStandard.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL); + case 'zlib': + if (options.zlibCompressionLevel) { + zlibOptions.level = options.zlibCompressionLevel; + } + return zlibDeflate(dataToBeCompressed, zlibOptions); + default: + throw new error_1.MongoInvalidArgumentError(`Unknown compressor ${options.agreedCompressor} failed to compress`); + } +} +exports.compress = compress; +// Decompress a message using the given compressor +async function decompress(compressorID, compressedData) { + if (compressorID !== exports.Compressor.snappy && + compressorID !== exports.Compressor.zstd && + compressorID !== exports.Compressor.zlib && + compressorID !== exports.Compressor.none) { + 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) { + throw deps_1.Snappy['kModuleError']; + } + return deps_1.Snappy.uncompress(compressedData, { asBuffer: true }); + case exports.Compressor.zstd: + if ('kModuleError' in deps_1.ZStandard) { + throw deps_1.ZStandard['kModuleError']; + } + return deps_1.ZStandard.decompress(compressedData); + case exports.Compressor.zlib: + return zlibInflate(compressedData); + default: + return compressedData; + } +} +exports.decompress = decompress; +//# sourceMappingURL=compression.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map b/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/compression.js.map new file mode 100644 index 00000000..bb980454 --- /dev/null +++ b/2_PAC/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,+BAAiC;AACjC,6BAA6B;AAE7B,+CAAuD;AACvD,qCAA+C;AAC/C,uCAAiF;AAEjF,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,GAAG,CAAC;IAC5C,gCAAoB;IACpB,WAAW;IACX,cAAc;IACd,UAAU;IACV,cAAc;IACd,YAAY;IACZ,YAAY;IACZ,iBAA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YAAY,KAAK,kBAAU,CAAC,IAAI;QAChC,YAAY,KAAK,kBAAU,CAAC,IAAI,EAChC;QACA,MAAM,IAAI,+BAAuB,CAC/B,2FAA2F,YAAY,GAAG,CAC3G,CAAC;KACH;IAED,QAAQ,YAAY,EAAE;QACpB,KAAK,kBAAU,CAAC,MAAM;YACpB,IAAI,cAAc,IAAI,aAAM,EAAE;gBAC5B,MAAM,aAAM,CAAC,cAAc,CAAC,CAAC;aAC9B;YACD,OAAO,aAAM,CAAC,UAAU,CAAC,cAAc,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC,CAAC;QAE/D,KAAK,kBAAU,CAAC,IAAI;YAClB,IAAI,cAAc,IAAI,gBAAS,EAAE;gBAC/B,MAAM,gBAAS,CAAC,cAAc,CAAC,CAAC;aACjC;YACD,OAAO,gBAAS,CAAC,UAAU,CAAC,cAAc,CAAC,CAAC;QAE9C,KAAK,kBAAU,CAAC,IAAI;YAClB,OAAO,WAAW,CAAC,cAAc,CAAC,CAAC;QAErC;YACE,OAAO,cAAc,CAAC;KACzB;AACH,CAAC;AA/BD,gCA+BC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/constants.js b/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/constants.js new file mode 100644 index 00000000..ab10958c --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/constants.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.OP_MSG = exports.OP_COMPRESSED = exports.OP_DELETE = 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_DELETE = 2006; +exports.OP_COMPRESSED = 2012; +exports.OP_MSG = 2013; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map b/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/constants.js.map new file mode 100644 index 00000000..8974600c --- /dev/null +++ b/2_PAC/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,SAAS,GAAG,IAAI,CAAC;AACjB,QAAA,aAAa,GAAG,IAAI,CAAC;AACrB,QAAA,MAAM,GAAG,IAAI,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/shared.js b/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/shared.js new file mode 100644 index 00000000..1acb4f55 --- /dev/null +++ b/2_PAC/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?.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/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map b/2_PAC/node_modules/mongodb/lib/cmap/wire_protocol/shared.js.map new file mode 100644 index 00000000..367981e4 --- /dev/null +++ b/2_PAC/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,EAAE,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/2_PAC/node_modules/mongodb/lib/collection.js b/2_PAC/node_modules/mongodb/lib/collection.js new file mode 100644 index 00000000..62b9887f --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/collection.js @@ -0,0 +1,576 @@ +"use strict"; +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 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/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +class Collection { + /** + * Create a new Collection instance + * @internal + */ + constructor(db, name, options) { + (0, utils_1.checkCollectionName)(name); + // Internal state + this.s = { + db, + options, + namespace: new utils_1.MongoDBNamespace(db.databaseName, name), + pkFactory: db.options?.pkFactory ?? 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; + } + 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; + } + 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; + } + /** The current index hint for the collection */ + get hint() { + return this.s.collectionHint; + } + set hint(v) { + this.s.collectionHint = (0, utils_1.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 + */ + async insertOne(doc, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new insert_1.InsertOneOperation(this, doc, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + */ + async insertMany(docs, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new insert_1.InsertManyOperation(this, docs, (0, utils_1.resolveOptions)(this, options ?? { ordered: true }))); + } + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * 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 + * @throws MongoDriverError if operations is not an array + */ + async bulkWrite(operations, options) { + 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 ?? { ordered: true }))); + } + /** + * 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 + */ + async updateOne(filter, update, 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))); + } + /** + * 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 + */ + async replaceOne(filter, replacement, 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))); + } + /** + * 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 + */ + async updateMany(filter, update, 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))); + } + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + async deleteOne(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new delete_1.DeleteOneOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + async deleteMany(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new delete_1.DeleteManyOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + */ + async rename(newName, 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 + })); + } + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + async drop(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new drop_1.DropCollectionOperation(this.s.db, this.collectionName, options)); + } + async findOne(filter = {}, options = {}) { + return this.find(filter, options).limit(-1).batchSize(1).next(); + } + find(filter = {}, options = {}) { + return new find_cursor_1.FindCursor(this.s.db.s.client, this.s.namespace, filter, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Returns the options of the collection. + * + * @param options - Optional settings for the command + */ + async 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))); + } + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + async isCapped(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new is_capped_1.IsCappedOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + * + * @example + * ```ts + * 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' }]) + * ``` + */ + async createIndex(indexSpec, 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))); + } + /** + * 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 + * + * @example + * ```ts + * 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' + * } + * ]); + * ``` + */ + async createIndexes(indexSpecs, options) { + 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, maxTimeMS: undefined }))); + } + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + async dropIndex(indexName, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.DropIndexOperation(this, indexName, { + ...(0, utils_1.resolveOptions)(this, options), + readPreference: read_preference_1.ReadPreference.primary + })); + } + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + async dropIndexes(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.DropIndexesOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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)); + } + /** + * 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 + */ + async indexExists(indexes, options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.IndexExistsOperation(this, indexes, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + async indexInformation(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))); + } + /** + * 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 + */ + async estimatedDocumentCount(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))); + } + /** + * 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 + * + * @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 + */ + async countDocuments(filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new count_documents_1.CountDocumentsOperation(this, filter, (0, utils_1.resolveOptions)(this, options))); + } + async distinct(key, filter = {}, options = {}) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new distinct_1.DistinctOperation(this, key, filter, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + async indexes(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new indexes_1.IndexesOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + */ + async stats(options) { + return (0, execute_operation_1.executeOperation)(this.s.db.s.client, new stats_1.CollStatsOperation(this, options)); + } + /** + * 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 + */ + async findOneAndDelete(filter, 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))); + } + /** + * 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 + */ + async findOneAndReplace(filter, replacement, 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))); + } + /** + * 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 + */ + async findOneAndUpdate(filter, update, 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))); + } + /** + * 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 (!Array.isArray(pipeline)) { + throw new error_1.MongoInvalidArgumentError('Argument "pipeline" must be an array of aggregation stages'); + } + 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 use cases: + * - 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)); + } + /** + * 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 implementation. + * 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 implementation. + * 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)); + } + /** + * 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 + */ + async count(filter = {}, options = {}) { + 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))); + } +} +exports.Collection = Collection; +//# sourceMappingURL=collection.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/collection.js.map b/2_PAC/node_modules/mongodb/lib/collection.js.map new file mode 100644 index 00000000..e12827a0 --- /dev/null +++ b/2_PAC/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;AAYpD,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;AAE3D,sEAAkE;AAClE,gDAAqE;AACrE,8CAAqF;AACrF,gDAO6B;AAC7B,iDAA8D;AAC9D,uDAAuE;AACvE,mCAMiB;AACjB,mDAAoE;AAmCpE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;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,EAAE,EAAE,CAAC,OAAO,EAAE,SAAS,IAAI,0BAAkB;YACtD,cAAc,EAAE,gCAAc,CAAC,WAAW,CAAC,OAAO,CAAC;YACnD,WAAW,EAAE,IAAA,yBAAkB,EAAC,OAAO,EAAE,E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,CAAC,EAC3C,MAAM,EACN,IAAA,sBAAc,EAAC,IAAI,EAAE,OAAO,CAAC,CAC9B,CACF,CAAC;IACJ,CAAC;CACF;AA/zBD,gCA+zBC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/connection_string.js b/2_PAC/node_modules/mongodb/lib/connection_string.js new file mode 100644 index 00000000..f5821c90 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/connection_string.js @@ -0,0 +1,1086 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FEATURE_FLAGS = exports.DEFAULT_OPTIONS = exports.OPTIONS = exports.parseOptions = 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 mongo_client_1 = require("./mongo_client"); +const mongo_logger_1 = require("./mongo_logger"); +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 + */ +async function resolveSRVRecord(options) { + if (typeof options.srvHost !== 'string') { + throw new error_1.MongoAPIError('Option "srvHost" must not be empty'); + } + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + throw 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; + const addresses = await dns.promises.resolveSrv(`_${options.srvServiceName}._tcp.${lookupAddress}`); + if (addresses.length === 0) { + throw new error_1.MongoAPIError('No addresses found at host'); + } + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + throw new error_1.MongoAPIError('Server record does not share hostname with parent URI'); + } + } + const hostAddresses = addresses.map(r => utils_1.HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)); + validateLoadBalancedOptions(hostAddresses, options, true); + // Resolve TXT record and add options from there if they exist. + let record; + try { + record = await dns.promises.resolveTxt(lookupAddress); + } + catch (error) { + if (error.code !== 'ENODATA' && error.code !== 'ENOTFOUND') { + throw error; + } + return hostAddresses; + } + if (record.length > 1) { + throw 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))) { + throw new error_1.MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`); + } + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + throw new error_1.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 && + !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) { + throw new error_1.MongoParseError('Cannot combine replicaSet option with srvMaxHosts'); + } + validateLoadBalancedOptions(hostAddresses, options, true); + return hostAddresses; +} +exports.resolveSRVRecord = resolveSRVRecord; +/** + * Checks if TLS options are valid + * + * @param allOptions - All options provided by user or included in default options map + * @throws MongoAPIError if TLS options are invalid + */ +function checkTLSOptions(allOptions) { + if (!allOptions) + return; + const check = (a, b) => { + if (allOptions.has(a) && allOptions.has(b)) { + throw new error_1.MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`); + } + }; + 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, 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 getIntFromOptions(name, value) { + const parsedInt = (0, utils_1.parseInteger)(value); + if (parsedInt != null) { + return parsedInt; + } + throw new error_1.MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} +function getUIntFromOptions(name, value) { + const parsedValue = getIntFromOptions(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.'); + } + } + checkTLSOptions(allOptions); + 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 + }); + } + if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) { + throw new error_1.MongoMissingCredentialsError(`When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified`); + } + 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'; + } + validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + 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 => urlOptions.get(key) ?? []); + if (proxyOptions.some(options => options.length > 1)) { + throw new error_1.MongoParseError('Proxy options cannot be specified multiple times in the connection string'); + } + const loggerFeatureFlag = Symbol.for('@@mdb.enableMongoLogger'); + mongoOptions[loggerFeatureFlag] = mongoOptions[loggerFeatureFlag] ?? false; + let loggerEnvOptions = {}; + let loggerClientOptions = {}; + if (mongoOptions[loggerFeatureFlag]) { + loggerEnvOptions = { + MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND, + MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY, + MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION, + MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION, + MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL, + MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH, + MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH + }; + loggerClientOptions = { + mongodbLogPath: mongoOptions.mongodbLogPath + }; + } + mongoOptions.mongoLoggerOptions = mongo_logger_1.MongoLogger.resolveOptions(loggerEnvOptions, loggerClientOptions); + return mongoOptions; +} +exports.parseOptions = parseOptions; +/** + * #### Throws if LB mode is true: + * - hosts contains more than one host + * - there is a replicaSet name set + * - directConnection is set + * - if srvMaxHosts is used when an srv connection string is passed in + * + * @throws MongoParseError + */ +function validateLoadBalancedOptions(hosts, mongoOptions, isSrv) { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + throw new error_1.MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + throw new error_1.MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + throw new error_1.MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + if (isSrv && mongoOptions.srvMaxHosts > 0) { + throw 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 ?? 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] = getIntFromOptions(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUIntFromOptions(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] }) { + 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 = options.credentials?.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 = options.credentials?.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] }) { + if (!(0, utils_1.isRecord)(value)) + throw new error_1.MongoParseError('DriverInfo must be an object'); + return (0, utils_1.makeClientMetadata)({ + driverInfo: value, + appName: options.metadata?.application?.name + }); + } + }, + enableUtf8Validation: { type: 'boolean', default: true }, + family: { + transform({ name, values: [value] }) { + const transformValue = getIntFromOptions(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' + }, + maxConnecting: { + default: 2, + transform({ name, values: [value] }) { + const maxConnecting = getUIntFromOptions(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 = getUIntFromOptions(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}`); + } + }, + 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 }) { + 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: options.readPreference?.hedge, + maxStalenessSeconds: options.readPreference?.maxStalenessSeconds + }; + return new read_preference_1.ReadPreference(value, options.readPreference?.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: getUIntFromOptions('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: getUIntFromOptions('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'), + Symbol.for('@@mdb.enableMongoLogger') +]); +//# sourceMappingURL=connection_string.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/connection_string.js.map b/2_PAC/node_modules/mongodb/lib/connection_string.js.map new file mode 100644 index 00000000..b2029b85 --- /dev/null +++ b/2_PAC/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,mCAKiB;AACjB,iDAQwB;AACxB,iDAAmG;AACnG,iDAA+D;AAC/D,uDAAuE;AAEvE,mCASiB;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,YAAoB;IACnE,MAAM,KAAK,GAAG,QAAQ,CAAC;IACvB,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC;IAChD,MAAM,MA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aAAa,GAAG,IAAI,GAAG,CAAC;IACnC,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC;IACrC,MAAM,CAAC,GAAG,CAAC,yBAAyB,CAAC;CACtC,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/constants.js b/2_PAC/node_modules/mongodb/lib/constants.js new file mode 100644 index 00000000..f3b151f2 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/constants.js @@ -0,0 +1,131 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +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_READY = 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 = exports.APM_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_POOL_READY = 'connectionPoolReady'; +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_READY, + exports.CONNECTION_POOL_CLEARED, + 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 +]); +/** @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/2_PAC/node_modules/mongodb/lib/constants.js.map b/2_PAC/node_modules/mongodb/lib/constants.js.map new file mode 100644 index 00000000..483983ab --- /dev/null +++ b/2_PAC/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,GAA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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/2_PAC/node_modules/mongodb/lib/cursor/abstract_cursor.js b/2_PAC/node_modules/mongodb/lib/cursor/abstract_cursor.js new file mode 100644 index 00000000..f148cf25 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cursor/abstract_cursor.js @@ -0,0 +1,672 @@ +"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 util_1 = require("util"); +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[kId] = null; + this[kDocuments] = new utils_1.List(); + 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 (typeof options.maxAwaitTimeMS === 'number') { + this[kOptions].maxAwaitTimeMS = options.maxAwaitTimeMS; + } + 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] ?? undefined; + } + /** @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() { + return !!this[kClient].topology?.loadBalanced; + } + /** Returns current buffered documents length */ + bufferedCount() { + return this[kDocuments].length; + } + /** Returns current buffered documents */ + readBufferedDocuments(number) { + const bufferedDocs = []; + const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length); + for (let count = 0; count < documentsToRead; count++) { + const document = this[kDocuments].shift(); + if (document != null) { + bufferedDocs.push(document); + } + } + return bufferedDocs; + } + async *[Symbol.asyncIterator]() { + if (this.closed) { + return; + } + try { + while (true) { + const document = await this.next(); + // Intentional strict null check, because users can map cursors to falsey values. + // We allow mapping to all values except for null. + // eslint-disable-next-line no-restricted-syntax + if (document === null) { + if (!this.closed) { + const message = 'Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.'; + await cleanupCursorAsync(this, { needsToEmitClosed: true }).catch(() => null); + throw new error_1.MongoAPIError(message); + } + break; + } + yield document; + if (this[kId] === bson_1.Long.ZERO) { + // Cursor exhausted + break; + } + } + } + finally { + // Only close the cursor if it has not already been closed. This finally clause handles + // the case when a user would break out of a for await of loop early. + if (!this.closed) { + await this.close().catch(() => null); + } + } + } + stream(options) { + if (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); + } + async hasNext() { + if (this[kId] === bson_1.Long.ZERO) { + return false; + } + if (this[kDocuments].length !== 0) { + return true; + } + const doc = await nextAsync(this, true); + if (doc) { + this[kDocuments].unshift(doc); + return true; + } + return false; + } + /** Get the next available document from the cursor, returns null if no more documents are available. */ + async next() { + if (this[kId] === bson_1.Long.ZERO) { + throw new error_1.MongoCursorExhaustedError(); + } + return nextAsync(this, true); + } + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + async tryNext() { + if (this[kId] === bson_1.Long.ZERO) { + throw new error_1.MongoCursorExhaustedError(); + } + return nextAsync(this, false); + } + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + */ + async forEach(iterator) { + if (typeof iterator !== 'function') { + throw new error_1.MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + for await (const document of this) { + const result = iterator(document); + if (result === false) { + break; + } + } + } + async close() { + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + await cleanupCursorAsync(this, { needsToEmitClosed }); + } + /** + * 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. + */ + async toArray() { + const array = []; + for await (const document of this) { + array.push(document); + } + return array; + } + /** + * 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** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **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] = null; + this[kDocuments].clear(); + 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) { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const getMoreOperation = new get_more_1.GetMoreOperation(this[kNamespace], this[kId], this[kServer], { + ...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], (error, state) => { + if (state) { + const response = state.response; + this[kServer] = state.server; + if (response.cursor) { + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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].pushMany(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].push(state.response); + } + } + // the cursor is now initialized, even if an error occurred or it is dead + this[kInitialized] = true; + if (error) { + return cleanupCursor(this, { error }, () => callback(error, undefined)); + } + if (cursorIsDead(this)) { + return cleanupCursor(this, undefined, () => callback()); + } + callback(); + }); + } +} +exports.AbstractCursor = AbstractCursor; +/** @event */ +AbstractCursor.CLOSE = 'close'; +function nextDocument(cursor) { + const doc = cursor[kDocuments].shift(); + if (doc && cursor[kTransform]) { + return cursor[kTransform](doc); + } + return doc; +} +const nextAsync = (0, util_1.promisify)(next); +/** + * @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].length !== 0) { + 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 => { + if (err) + return callback(err); + 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, (error, response) => { + if (response) { + const cursorId = typeof response.cursor.id === 'number' + ? bson_1.Long.fromNumber(response.cursor.id) + : response.cursor.id; + cursor[kDocuments].pushMany(response.cursor.nextBatch); + cursor[kId] = cursorId; + } + if (error || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error }, () => callback(error, 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(); +} +const cleanupCursorAsync = (0, util_1.promisify)(cleanupCursor); +function cleanupCursor(cursor, options, callback) { + 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 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) { + session.endSession({ error }).finally(() => { + callback(); + }); + return; + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } + } + return callback(); + } + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + session.endSession({ error }).finally(() => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + return; + } + if (!session.inTransaction()) { + (0, sessions_1.maybeClearPinnedConnection)(session, { error }); + } + } + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + cursor[kKilled] = true; + (0, execute_operation_1.executeOperation)(cursor[kClient], new kill_cursors_1.KillCursorsOperation(cursorId, cursorNs, server, { session })).finally(() => { + completeCleanup(); + }); + return; +} +/** @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().then(() => callback(error), closeError => callback(closeError)); + } + _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 was 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(/operation was interrupted/)) { + return this.push(null); + } + // NOTE: The two above checks on the message of the error will cause a null to be pushed + // to the stream, thus closing the stream before the destroy call happens. This means + // that either of those error messages on a change stream will not get a proper + // 'error' event to be emitted (the error passed to destroy). Change stream resumability + // relies on that error event to be emitted to create its new cursor and thus was not + // working on 4.4 servers because the error emitted on failover was "interrupted at + // shutdown" while on 5.0+ it is "The server is in quiesce mode and will shut down". + // See NODE-4475. + 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/2_PAC/node_modules/mongodb/lib/cursor/abstract_cursor.js.map b/2_PAC/node_modules/mongodb/lib/cursor/abstract_cursor.js.map new file mode 100644 index 00000000..13d307bd --- /dev/null +++ b/2_PAC/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;AAC7C,+BAAiC;AAEjC,kCAA0F;AAC1F,oCASkB;AAElB,gDAAmE;AACnE,uEAAoF;AACpF,qDAA0D;AAC1D,6DAAkE;AAClE,kDAA+D;AAC/D,wDAAwE;AAExE,0CAAwE;AACxE,oCAAgE;AAEhE,gBAAgB;AAChB,MAAM,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;AACzB,gBAAgB;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AO,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;iBACxB;gBAED,wFAAwF;gBACxF,2FAA2F;gBAC3F,qFAAqF;gBACrF,8FAA8F;gBAC9F,2FAA2F;gBAC3F,yFAAyF;gBACzF,0FAA0F;gBAC1F,uBAAuB;gBACvB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;aAC1B;YAED,IAAI,MAAM,IAAI,IAAI,EAAE;gBAClB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;aACjB;iBAAM,IAAI,IAAI,CAAC,SAAS,EAAE;gBACzB,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,CAAC;aACxC;iBAAM;gBACL,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE;oBACrB,OAAO,IAAI,CAAC,SAAS,EAAE,CAAC;iBACzB;gBAED,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;aAC9B;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cursor/aggregation_cursor.js b/2_PAC/node_modules/mongodb/lib/cursor/aggregation_cursor.js new file mode 100644 index 00000000..0673ee92 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cursor/aggregation_cursor.js @@ -0,0 +1,168 @@ +"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 }); + }); + } + /** Execute the explain for the cursor */ + async explain(verbosity) { + return (0, execute_operation_1.executeOperation)(this.client, new aggregate_1.AggregateOperation(this.namespace, this[kPipeline], { + ...this[kOptions], + ...this.cursorOptions, + explain: verbosity ?? true + })); + } + 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; + } + /** 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/2_PAC/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map b/2_PAC/node_modules/mongodb/lib/cursor/aggregation_cursor.js.map new file mode 100644 index 00000000..c8e5c7a7 --- /dev/null +++ b/2_PAC/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,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAElC,IAAI,CAAC,SAAS,CAAC,GAAG,QAAQ,CAAC;QAC3B,IAAI,CAAC,QAAQ,CAAC,GAAG,OAAO,CAAC;IAC3B,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC;IACzB,CAAC;IAED,KAAK;QACH,MAAM,aAAa,GAAG,IAAA,oBAAY,EAAC,EAAE,EAAE,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvD,OAAO,aAAa,CAAC,OAAO,CAAC;QAC7B,OAAO,IAAI,iBAAiB,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE;YACzE,GAAG,aAAa;SACjB,CAAC,CAAC;IACL,CAAC;IAEQ,GAAG,CAAI,SAA8B;QAC5C,OAAO,KAAK,CAAC,GAAG,CAAC,SAAS,CAAyB,CAAC;IACtD,CAAC;IAED,gBAAgB;IAChB,WAAW,CAAC,OAAsB,EA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C,OAAO,IAAI,CAAC;IACd,CAAC;IAED,mDAAmD;IACnD,IAAI,CAAC,KAAW;QACd,IAAA,qCAAmB,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,qDAAqD;IACrD,MAAM,CAAC,OAA0B;QAC/B,IAAA,qCAAmB,EAAC,IAAI,CAAC,CAAC;QAC1B,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,sDAAsD;IACtD,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;AApLD,8CAoLC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cursor/change_stream_cursor.js b/2_PAC/node_modules/mongodb/lib/cursor/change_stream_cursor.js new file mode 100644 index 00000000..471fb6cd --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map b/2_PAC/node_modules/mongodb/lib/cursor/change_stream_cursor.js.map new file mode 100644 index 00000000..259e3ded --- /dev/null +++ b/2_PAC/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,CA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AAC,EACxB;gBACA,IAAI,CAAC,oBAAoB,GAAG,QAAQ,CAAC,aAAa,CAAC;aACpD;YAED,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;YAE7B,IAAI,CAAC,IAAI,CAAC,gBAAI,EAAE,QAAQ,CAAC,CAAC;YAC1B,IAAI,CAAC,IAAI,CAAC,oBAAQ,CAAC,CAAC;YAEpB,kBAAkB;YAClB,QAAQ,CAAC,SAAS,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;QACrD,CAAC,CACF,CAAC;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/2_PAC/node_modules/mongodb/lib/cursor/find_cursor.js b/2_PAC/node_modules/mongodb/lib/cursor/find_cursor.js new file mode 100644 index 00000000..f4388561 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/cursor/find_cursor.js @@ -0,0 +1,381 @@ +"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) { + this.close().finally(() => callback()); + return; + } + } + 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 + */ + async count(options) { + (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'); + } + return (0, execute_operation_1.executeOperation)(this.client, new count_1.CountOperation(this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + ...options + })); + } + /** Execute the explain for the cursor */ + async explain(verbosity) { + return (0, execute_operation_1.executeOperation)(this.client, new find_1.FindOperation(undefined, this.namespace, this[kFilter], { + ...this[kBuiltOptions], + ...this.cursorOptions, + explain: verbosity ?? true + })); + } + /** 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 behavior. + 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/2_PAC/node_modules/mongodb/lib/cursor/find_cursor.js.map b/2_PAC/node_modules/mongodb/lib/cursor/find_cursor.js.map new file mode 100644 index 00000000..5beda290 --- /dev/null +++ b/2_PAC/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,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,YAAY,GAAG,MAAM,CAAC,aAAa,CAAC,CAAC;AAC3C,gBAAgB;AAChB,MAAM,aAAa,GAAG,MAAM,CAAC,cAAc,CAAC,CAAC;AAE7C,uCAAuC;AAC1B,QAAA,KAAK,GAAG;IACnB,UAAU;IACV,aAAa;IACb,iBAAiB;IACjB,WAAW;IACX,SAAS;IACT,SAAS;CACD,CAAC;AAEX,cAAc;AACd,MAAa,UAA0B,SAAQ,gCAAuB;IAQpE,gBAAgB;IAChB,YACE,MAAmB,EACnB,SAA2B,EAC3B,SAAmB,EAAE,EACrB,UAAuB,EAAE;QAEzB,KAAK,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;QAElC,IAAI,CAAC,OAAO,CAAC,GAAG,MAAM,CAAC;QACvB,IAAI,CAAC,aAAa,CAAC,GAAG,OAAO,CAAC;QAE9B,IAAI,OAAO,CAAC,IAAI,IAAI,IAAI,EAAE;YACxB,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,GAAG,IAAA,iBAAU,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC;SACrD;IACH,CAAC;IAED,KAAK;QACH,MAAM,aAAa,GAAG,IAAA,oBAAY,EAAC,EAAE,EAAE,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC;QAC5D,OAAO,aAAa,CAAC,OAAO,CAAC;QAC7B,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CA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K,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;AAvaD,gCAuaC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/cursor/list_collections_cursor.js b/2_PAC/node_modules/mongodb/lib/cursor/list_collections_cursor.js new file mode 100644 index 00000000..883474b0 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map b/2_PAC/node_modules/mongodb/lib/cursor/list_collections_cursor.js.map new file mode 100644 index 00000000..2f8ecbe3 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cursor/list_indexes_cursor.js b/2_PAC/node_modules/mongodb/lib/cursor/list_indexes_cursor.js new file mode 100644 index 00000000..7d62d78f --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map b/2_PAC/node_modules/mongodb/lib/cursor/list_indexes_cursor.js.map new file mode 100644 index 00000000..f17b5768 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/db.js b/2_PAC/node_modules/mongodb/lib/db.js new file mode 100644 index 00000000..4ec84f9b --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/db.js @@ -0,0 +1,348 @@ +"use strict"; +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 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', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'enableUtf8Validation', + 'promoteValues', + 'compression', + 'retryWrites' +]; +/** + * The **Db** class is a class that represents a MongoDB Database. + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +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) { + options = 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, + // 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: options?.pkFactory ?? 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 + get options() { + return this.s.options; + } + /** + * Check if a secondary can be used (because the read preference is *not* set to primary) + */ + get secondaryOk() { + return this.s.readPreference?.preference !== 'primary' || false; + } + get readConcern() { + 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() { + if (this.s.readPreference == null) { + return this.s.client.readPreference; + } + return this.s.readPreference; + } + get bsonOptions() { + return this.s.bsonOptions; + } + // get the write Concern + get writeConcern() { + return this.s.writeConcern; + } + get namespace() { + 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 + */ + async createCollection(name, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new create_collection_1.CreateCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + */ + async command(command, 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)); + } + /** + * 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) { + return new aggregation_cursor_1.AggregationCursor(this.s.client, this.s.namespace, pipeline, (0, utils_1.resolveOptions)(this, options)); + } + /** Return the Admin db instance */ + admin() { + return new admin_1.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, options = {}) { + if (typeof options === 'function') { + throw new error_1.MongoInvalidArgumentError('The callback form of this helper has been removed.'); + } + return new collection_1.Collection(this, name, (0, utils_1.resolveOptions)(this, options)); + } + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + */ + async stats(options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new stats_1.DbStatsOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + listCollections(filter = {}, options = {}) { + return new list_collections_cursor_1.ListCollectionsCursor(this, filter, (0, utils_1.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 + */ + async renameCollection(fromCollection, toCollection, options) { + // Intentionally, we do not inherit options from parent for this operation. + return (0, execute_operation_1.executeOperation)(this.s.client, new rename_1.RenameOperation(this.collection(fromCollection), toCollection, { ...options, new_collection: true, readPreference: read_preference_1.ReadPreference.primary })); + } + /** + * 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 + */ + async dropCollection(name, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new drop_1.DropCollectionOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + async dropDatabase(options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new drop_1.DropDatabaseOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + async collections(options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new collections_1.CollectionsOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 + */ + async createIndex(name, indexSpec, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new indexes_1.CreateIndexOperation(this, name, indexSpec, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + async addUser(username, passwordOrOptions, options) { + options = + options != null && typeof options === 'object' + ? options + : passwordOrOptions != null && typeof passwordOrOptions === 'object' + ? passwordOrOptions + : undefined; + const password = typeof passwordOrOptions === 'string' ? passwordOrOptions : undefined; + return (0, execute_operation_1.executeOperation)(this.s.client, new add_user_1.AddUserOperation(this, username, password, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new remove_user_1.RemoveUserOperation(this, username, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + async setProfilingLevel(level, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new set_profiling_level_1.SetProfilingLevelOperation(this, level, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + async profilingLevel(options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new profiling_level_1.ProfilingLevelOperation(this, (0, utils_1.resolveOptions)(this, options))); + } + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + async indexInformation(name, options) { + return (0, execute_operation_1.executeOperation)(this.s.client, new indexes_1.IndexInformationOperation(this, name, (0, utils_1.resolveOptions)(this, options))); + } + /** + * 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 use cases: + * - 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)); + } +} +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 +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]}'`); + } +} +//# sourceMappingURL=db.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/db.js.map b/2_PAC/node_modules/mongodb/lib/db.js.map new file mode 100644 index 00000000..cd34ef49 --- /dev/null +++ b/2_PAC/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;AAGnE,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,mCAA8F;AAC9F,mDAAoE;AAEpE,qBAAqB;AACrB,MAAM,qBAAqB,GAAG;IAC5B,cAAc;IACd,gBAAgB;IAChB,oBAAoB;IACpB,eAAe;IACf,qBAAqB;IACrB,WAAW;IACX,oBAAoB;IACpB,KAAK;IACL,YAAY;IACZ,iBAAiB;IACjB,aAAa;IACb,kBAAkB;IAClB,iBAAiB;IACjB,gBAAgB;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,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/2_PAC/node_modules/mongodb/lib/deps.js b/2_PAC/node_modules/mongodb/lib/deps.js new file mode 100644 index 00000000..58a87178 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/deps.js @@ -0,0 +1,69 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AutoEncryptionLoggerLevel = exports.aws4 = exports.saslprep = exports.Snappy = exports.getAwsCredentialProvider = exports.ZStandard = exports.Kerberos = void 0; +const error_1 = require("./error"); +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 +function getAwsCredentialProvider() { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const credentialProvider = require('@aws-sdk/credential-providers'); + return credentialProvider; + } + catch { + return makeErrorModule(new error_1.MongoMissingDependencyError('Optional module `@aws-sdk/credential-providers` not found.' + + ' Please install it to enable getting aws credentials via the official sdk.')); + } +} +exports.getAwsCredentialProvider = getAwsCredentialProvider; +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'); +} +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/2_PAC/node_modules/mongodb/lib/deps.js.map b/2_PAC/node_modules/mongodb/lib/deps.js.map new file mode 100644 index 00000000..467de7ce --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/deps.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deps.js","sourceRoot":"","sources":["../src/deps.ts"],"names":[],"mappings":";;;AAIA,mCAAsD;AAItD,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,EAAE,EAAE;YACxB,IAAI,GAAG,KAAK,cAAc,EAAE;gBAC1B,OAAO,KAAK,CAAC;aACd;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QACD,GAAG,EAAE,GAAG,EAAE;YACR,MAAM,KAAK,CAAC;QACd,CAAC;KACF,CAAC,CAAC;AACL,CAAC;AAEU,QAAA,QAAQ,GACjB,eAAe,CACb,IAAI,mCAA2B,CAC7B,2FAA2F,CAC5F,CACF,CAAC;AAEJ,IAAI;IACF,wEAAwE;IACxE,gBAAQ,GAAG,OAAO,CAAC,U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AC;IACR,OAAO,EAAE,CAAC;IACV,IAAI,EAAE,CAAC;IACP,KAAK,EAAE,CAAC;CACA,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/encrypter.js b/2_PAC/node_modules/mongodb/lib/encrypter.js new file mode 100644 index 00000000..69762c68 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/encrypter.js @@ -0,0 +1,103 @@ +"use strict"; +/* eslint-disable @typescript-eslint/no-var-requires */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Encrypter = void 0; +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 + }; + } + 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?.on(eventName, listener); + }); + this.needsConnecting = true; + } + return internalClient; + } + async connectInternalClient() { + // TODO(NODE-4144): Remove new variable for type narrowing + const internalClient = this[kInternalClient]; + if (this.needsConnecting && internalClient != null) { + this.needsConnecting = false; + await internalClient.connect(); + } + } + close(client, force, callback) { + this.autoEncrypter.teardown(!!force, e => { + const internalClient = this[kInternalClient]; + if (internalClient != null && client !== internalClient) { + internalClient.close(force).then(() => callback(), error => callback(error)); + return; + } + callback(e); + }); + } + static checkForMongoCrypt() { + const mongodbClientEncryption = (0, utils_1.getMongoDBClientEncryption)(); + if (mongodbClientEncryption == null) { + 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'); + } + AutoEncrypterClass = mongodbClientEncryption.extension(require('../lib/index')).AutoEncrypter; + } +} +exports.Encrypter = Encrypter; +//# sourceMappingURL=encrypter.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/encrypter.js.map b/2_PAC/node_modules/mongodb/lib/encrypter.js.map new file mode 100644 index 00000000..900bb164 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/encrypter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encrypter.js","sourceRoot":"","sources":["../src/encrypter.ts"],"names":[],"mappings":";AAAA,uDAAuD;;;AAEvD,2CAAkD;AAElD,mCAAiF;AACjF,iDAAiE;AACjE,mCAA+D;A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AAO,CAAC,cAAc,CAAC,CAAC,CAAC,aAAa,CAAC;IAChG,CAAC;CACF;AA9GD,8BA8GC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/error.js b/2_PAC/node_modules/mongodb/lib/error.js new file mode 100644 index 00000000..44318b2e --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/error.js @@ -0,0 +1,801 @@ +"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', + ResetPool: 'ResetPool', + InterruptInUseConnections: 'InterruptInUseConnections', + NoWritesPerformed: 'NoWritesPerformed' +}); +/** + * @public + * @category Error + * + * @privateRemarks + * mongodb-client-encryption 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); + this.cause = 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 + * mongodb-client-encryption 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) { + if (reason && reason.error) { + super(reason.error.message || reason.error); + } + else { + super(message); + } + if (reason) { + this.reason = reason; + } + this.code = reason.error?.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) { + // 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(error.result?.code ?? error.code ?? 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/2_PAC/node_modules/mongodb/lib/error.js.map b/2_PAC/node_modules/mongodb/lib/error.js.map new file mode 100644 index 00000000..5eb67948 --- /dev/null +++ b/2_PAC/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,MAA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AK,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/2_PAC/node_modules/mongodb/lib/explain.js b/2_PAC/node_modules/mongodb/lib/explain.js new file mode 100644 index 00000000..4fb841e9 --- /dev/null +++ b/2_PAC/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?.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/2_PAC/node_modules/mongodb/lib/explain.js.map b/2_PAC/node_modules/mongodb/lib/explain.js.map new file mode 100644 index 00000000..8b114f11 --- /dev/null +++ b/2_PAC/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,OAAO,EAAE,OAAO,IAAI,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/2_PAC/node_modules/mongodb/lib/gridfs/download.js b/2_PAC/node_modules/mongodb/lib/gridfs/download.js new file mode 100644 index 00000000..f5c5c1f9 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/gridfs/download.js @@ -0,0 +1,313 @@ +"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 { + /** + * @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 + * @internal + */ + 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. + */ + async abort() { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + try { + await this.s.cursor.close(); + } + finally { + this.emit(GridFSBucketReadStream.CLOSE); + } + } + else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); + } + } + } +} +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; + const handleReadResult = ({ error, doc }) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + stream.s.cursor?.close().then(() => { + stream.emit(GridFSBucketReadStream.CLOSE); + }, error => { + stream.emit(GridFSBucketReadStream.ERROR, error); + }); + 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; + }; + stream.s.cursor.next().then(doc => handleReadResult({ error: null, doc }), error => handleReadResult({ error, doc: null })); +} +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; + } + const handleReadResult = ({ 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; + }; + stream.s.files.findOne(stream.s.filter, findOneOptions).then(doc => handleReadResult({ error: null, doc }), error => handleReadResult({ error, doc: null })); +} +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/2_PAC/node_modules/mongodb/lib/gridfs/download.js.map b/2_PAC/node_modules/mongodb/lib/gridfs/download.js.map new file mode 100644 index 00000000..57638a06 --- /dev/null +++ b/2_PAC/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;AAgElB;;;;;GAKG;AACH,MAAa,sBAAuB,SAAQ,iBAAQ;IA8BlD;;;;;;OAMG;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;IACxC,CAAC;IAED;;;;;;OAMG;IACH,KAAK,CAAC,KAAK,GAAG,CAAC;QACb,kBAAkB,CAAC,IAAI,CAAC,CAAC;QACzB,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;;;;OAMG;IACH,GAAG,CAAC,GAAG,GAAG,CAAC;QACT,kBAAkB,CAAC,IAAI,CAAC,CAAC;QACzB,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,GAAG,GAAG,CAAC;QACzB,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AI,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/2_PAC/node_modules/mongodb/lib/gridfs/index.js b/2_PAC/node_modules/mongodb/lib/gridfs/index.js new file mode 100644 index 00000000..6110d8d0 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/gridfs/index.js @@ -0,0 +1,128 @@ +"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 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); + } + /** + * Deletes a file with the given id + * + * @param id - The id of the file doc + */ + async delete(id) { + const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id }); + // Delete orphaned chunks before returning FileNotFound + await this.s._chunksCollection.deleteMany({ files_id: id }); + if (deletedCount === 0) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + throw new error_1.MongoRuntimeError(`File not found for id ${id}`); + } + } + /** Convenience wrapper around find on the files collection */ + find(filter = {}, 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 }); + } + /** + * 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 + */ + async rename(id, filename) { + const filter = { _id: id }; + const update = { $set: { filename } }; + const { matchedCount } = await this.s._filesCollection.updateOne(filter, update); + if (matchedCount === 0) { + throw new error_1.MongoRuntimeError(`File with id ${id} not found`); + } + } + /** Removes this bucket's files collection, followed by its chunks collection. */ + async drop() { + await this.s._filesCollection.drop(); + await this.s._chunksCollection.drop(); + } +} +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/2_PAC/node_modules/mongodb/lib/gridfs/index.js.map b/2_PAC/node_modules/mongodb/lib/gridfs/index.js.map new file mode 100644 index 00000000..9c65fd3c --- /dev/null +++ b/2_PAC/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;AAC7C,gDAA2D;AAG3D,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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GAAG,EAAE,GAAG,EAAE,EAAE,EAAE,CAAC;QAC3B,MAAM,MAAM,GAAG,EAAE,IAAI,EAAE,EAAE,QAAQ,EAAE,EAAE,CAAC;QACtC,MAAM,EAAE,YAAY,EAAE,GAAG,MAAM,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjF,IAAI,YAAY,KAAK,CAAC,EAAE;YACtB,MAAM,IAAI,yBAAiB,CAAC,gBAAgB,EAAE,YAAY,CAAC,CAAC;SAC7D;IACH,CAAC;IAED,iFAAiF;IACjF,KAAK,CAAC,IAAI;QACR,MAAM,IAAI,CAAC,CAAC,CAAC,gBAAgB,CAAC,IAAI,EAAE,CAAC;QACrC,MAAM,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC,IAAI,EAAE,CAAC;IACxC,CAAC;;AAnJH,oCAoJC;AAhJC;;;;;;;GAOG;AACa,kBAAK,GAAG,OAAgB,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/gridfs/upload.js b/2_PAC/node_modules/mongodb/lib/gridfs/upload.js new file mode 100644 index 00000000..b0cd641c --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/gridfs/upload.js @@ -0,0 +1,342 @@ +"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 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 { + /** + * @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. + * @internal + */ + constructor(bucket, filename, options) { + super(); + options = 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).then(() => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }, () => null); + } + } + 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)); + } + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + */ + async abort() { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new error_1.MongoAPIError('Cannot abort a stream that has already completed'); + } + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new error_1.MongoAPIError('Cannot call abort() on a stream twice'); + } + this.state.aborted = true; + await this.chunks.deleteMany({ files_id: this.id }); + } + 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 + }; +} +async function checkChunksIndex(stream) { + const index = { files_id: 1, n: 1 }; + let indexes; + try { + indexes = await stream.chunks.listIndexes().toArray(); + } + catch (error) { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } + else { + throw error; + } + } + const hasChunksIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + return true; + } + return false; + }); + if (!hasChunksIndex) { + const writeConcernOptions = getWriteOptions(stream); + await stream.chunks.createIndex(index, { + ...writeConcernOptions, + background: true, + unique: true + }); + } +} +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)).then(() => { + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }, error => { + return __handleError(stream, error, callback); + }); + return true; + } + return false; +} +async function checkIndexes(stream) { + const doc = await stream.files.findOne({}, { projection: { _id: 1 } }); + if (doc != null) { + // If at least one document exists assume the collection has the required index + return; + } + const index = { filename: 1, uploadDate: 1 }; + let indexes; + try { + indexes = await stream.files.listIndexes().toArray(); + } + catch (error) { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } + else { + throw error; + } + } + const hasFileIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + return true; + } + return false; + }); + if (!hasFileIndex) { + await stream.files.createIndex(index, { background: false }); + } + await checkChunksIndex(stream); +} +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)).then(() => { + --stream.state.outstandingRequests; + --outstandingRequests; + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }, error => { + return __handleError(stream, error); + }); + 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)).then(() => { + --stream.state.outstandingRequests; + checkDone(stream); + }, error => { + return __handleError(stream, error); + }); + 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/2_PAC/node_modules/mongodb/lib/gridfs/upload.js.map b/2_PAC/node_modules/mongodb/lib/gridfs/upload.js.map new file mode 100644 index 00000000..d7955f8d --- /dev/null +++ b/2_PAC/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;AAGpF,sDAAkD;AA0BlD;;;;;GAKG;AACH,MAAa,uBAAwB,SAAQ,iBAAQ;IA+BnD;;;;;OAKG;IACH,YAAY,MAAoB,EAAE,QAAgB,EAAE,OAAwC;QAC1F,KAAK,EAAE,CAAC;QAER,OAAO,GAAG,OAAO,IAAI,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,OAAO,CAAC,cAAc,IAAI,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC;QACrF,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;QACpD,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;Q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QACN,OAAO,aAAa,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACtC,CAAC,CACF,CAAC;IACF,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/2_PAC/node_modules/mongodb/lib/index.js b/2_PAC/node_modules/mongodb/lib/index.js new file mode 100644 index 00000000..7c167bea --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/index.js @@ -0,0 +1,161 @@ +"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.ChangeStreamCursor = exports.MongoBulkWriteError = exports.Timestamp = exports.ObjectId = exports.MinKey = exports.MaxKey = exports.Long = exports.Int32 = exports.Double = exports.Decimal128 = exports.DBRef = exports.Code = exports.BSONType = exports.BSONSymbol = exports.BSONRegExp = exports.Binary = exports.BSON = void 0; +exports.ServerDescriptionChangedEvent = exports.ServerClosedEvent = exports.ConnectionReadyEvent = exports.ConnectionPoolReadyEvent = 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.ServerApiVersion = exports.ExplainVerbosity = exports.MongoErrorLabel = exports.AutoEncryptionLoggerLevel = exports.CURSOR_FLAGS = exports.Compressor = exports.AuthMechanism = exports.GSSAPICanonicalizationValue = exports.BatchType = exports.UnorderedBulkOperation = exports.OrderedBulkOperation = exports.MongoClient = exports.ListIndexesCursor = exports.ListCollectionsCursor = exports.GridFSBucketWriteStream = exports.GridFSBucketReadStream = exports.GridFSBucket = exports.FindCursor = exports.Db = exports.Collection = exports.ClientSession = exports.ChangeStream = exports.CancellationToken = exports.AggregationCursor = void 0; +exports.SrvPollingEvent = exports.TopologyOpeningEvent = exports.TopologyDescriptionChangedEvent = exports.TopologyClosedEvent = exports.ServerOpeningEvent = exports.ServerHeartbeatSucceededEvent = exports.ServerHeartbeatStartedEvent = exports.ServerHeartbeatFailedEvent = void 0; +const admin_1 = require("./admin"); +Object.defineProperty(exports, "Admin", { enumerable: true, get: function () { return admin_1.Admin; } }); +const ordered_1 = require("./bulk/ordered"); +Object.defineProperty(exports, "OrderedBulkOperation", { enumerable: true, get: function () { return ordered_1.OrderedBulkOperation; } }); +const unordered_1 = require("./bulk/unordered"); +Object.defineProperty(exports, "UnorderedBulkOperation", { enumerable: true, get: function () { return unordered_1.UnorderedBulkOperation; } }); +const change_stream_1 = require("./change_stream"); +Object.defineProperty(exports, "ChangeStream", { enumerable: true, get: function () { return change_stream_1.ChangeStream; } }); +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 download_1 = require("./gridfs/download"); +Object.defineProperty(exports, "GridFSBucketReadStream", { enumerable: true, get: function () { return download_1.GridFSBucketReadStream; } }); +const upload_1 = require("./gridfs/upload"); +Object.defineProperty(exports, "GridFSBucketWriteStream", { enumerable: true, get: function () { return upload_1.GridFSBucketWriteStream; } }); +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 sessions_1 = require("./sessions"); +Object.defineProperty(exports, "ClientSession", { enumerable: true, get: function () { return sessions_1.ClientSession; } }); +/** @public */ +var bson_1 = require("./bson"); +Object.defineProperty(exports, "BSON", { enumerable: true, get: function () { return bson_1.BSON; } }); +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, "BSONType", { enumerable: true, get: function () { return bson_2.BSONType; } }); +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, "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 common_1 = require("./bulk/common"); +Object.defineProperty(exports, "MongoBulkWriteError", { enumerable: true, get: function () { return common_1.MongoBulkWriteError; } }); +var change_stream_cursor_1 = require("./cursor/change_stream_cursor"); +Object.defineProperty(exports, "ChangeStreamCursor", { enumerable: true, get: function () { return change_stream_cursor_1.ChangeStreamCursor; } }); +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 mongo_client_2 = require("./mongo_client"); +Object.defineProperty(exports, "ServerApiVersion", { enumerable: true, get: function () { return mongo_client_2.ServerApiVersion; } }); +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, "ConnectionPoolReadyEvent", { enumerable: true, get: function () { return connection_pool_events_1.ConnectionPoolReadyEvent; } }); +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/2_PAC/node_modules/mongodb/lib/index.js.map b/2_PAC/node_modules/mongodb/lib/index.js.map new file mode 100644 index 00000000..618ebe9f --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;AAAA,mCAAgC;AA0E9B,sFA1EO,aAAK,OA0EP;AAzEP,4CAAsD;AAuFpD,qG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node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 00000000..f9981f96 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,292 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoClient = exports.ServerApiVersion = void 0; +const util_1 = require("util"); +const bson_1 = require("./bson"); +const change_stream_1 = require("./change_stream"); +const connection_string_1 = require("./connection_string"); +const constants_1 = require("./constants"); +const db_1 = require("./db"); +const error_1 = require("./error"); +const mongo_logger_1 = require("./mongo_logger"); +const mongo_types_1 = require("./mongo_types"); +const read_preference_1 = require("./read_preference"); +const server_selection_1 = require("./sdam/server_selection"); +const topology_1 = require("./sdam/topology"); +const sessions_1 = require("./sessions"); +const utils_1 = require("./utils"); +/** @public */ +exports.ServerApiVersion = Object.freeze({ + v1: '1' +}); +/** @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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +class MongoClient extends mongo_types_1.TypedEventEmitter { + constructor(url, options) { + super(); + this[kOptions] = (0, connection_string_1.parseOptions)(url, this, options); + this.mongoLogger = new mongo_logger_1.MongoLogger(this[kOptions].mongoLoggerOptions); + // 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 isMongoClient() { + return true; + } + }; + } + get options() { + return Object.freeze({ ...this[kOptions] }); + } + get serverApi() { + return this[kOptions].serverApi && Object.freeze({ ...this[kOptions].serverApi }); + } + /** + * Intended for APM use only + * @internal + */ + get monitorCommands() { + return this[kOptions].monitorCommands; + } + set monitorCommands(value) { + this[kOptions].monitorCommands = value; + } + 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; + } + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + async connect() { + if (this.topology && this.topology.isConnected()) { + return this; + } + const options = this[kOptions]; + if (typeof options.srvHost === 'string') { + const hosts = await (0, connection_string_1.resolveSRVRecord)(options); + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + } + 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 + this.topology = topology; + topology.client = this; + topology.once(topology_1.Topology.OPEN, () => this.emit('open', this)); + for (const event of constants_1.MONGO_CLIENT_EVENTS) { + topology.on(event, (...args) => this.emit(event, ...args)); + } + const topologyConnect = async () => { + try { + await (0, util_1.promisify)(callback => topology.connect(options, callback))(); + } + catch (error) { + topology.close({ force: true }); + throw error; + } + }; + if (this.autoEncrypter) { + const initAutoEncrypter = (0, util_1.promisify)(callback => this.autoEncrypter?.init(callback)); + await initAutoEncrypter(); + await topologyConnect(); + await options.encrypter.connectInternalClient(); + } + else { + await topologyConnect(); + } + return this; + } + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + async close(force = false) { + // There's no way to set hasBeenClosed back to false + Object.defineProperty(this.s, 'hasBeenClosed', { + value: true, + enumerable: true, + configurable: false, + writable: false + }); + const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession()); + this.s.activeSessions.clear(); + await Promise.all(activeSessionEnds); + if (this.topology == null) { + return; + } + // If we would attempt to select a server and get nothing back we short circuit + // to avoid the server selection timeout. + const selector = (0, server_selection_1.readPreferenceServerSelector)(read_preference_1.ReadPreference.primaryPreferred); + const topologyDescription = this.topology.description; + const serverDescriptions = Array.from(topologyDescription.servers.values()); + const servers = selector(topologyDescription, serverDescriptions); + if (servers.length !== 0) { + const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); + if (endSessions.length !== 0) { + await this.db('admin') + .command({ endSessions }, { readPreference: read_preference_1.ReadPreference.primaryPreferred, noResponse: true }) + .catch(() => null); // outcome does not matter + } + } + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + await 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(); + }); + }); + } + /** + * 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 ?? {}; + // 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; + } + /** + * 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 async connect(url, options) { + const client = new this(url, options); + return client.connect(); + } + /** Starts a new session on the server */ + 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); + }); + return session; + } + async 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); + try { + await withSessionCallback(session); + } + finally { + try { + await session.endSession(); + } + catch { + // We are not concerned with errors from endSession() + } + } + } + /** + * 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 use cases: + * - 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)); + } +} +exports.MongoClient = MongoClient; +//# sourceMappingURL=mongo_client.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/mongo_client.js.map b/2_PAC/node_modules/mongodb/lib/mongo_client.js.map new file mode 100644 index 00000000..875f5253 --- /dev/null +++ b/2_PAC/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":";;;AAEA,+BAAiC;AAEjC,iCAA4E;AAC5E,mDAA0F;AAM1F,2DAAqE;AACrE,2CAAkD;AAClD,6BAAqC;AAGrC,mCAAoD;AACpD,iDAAiE;AACjE,+CAAkD;AAElD,uDAAuE;AAEvE,8DAAuE;AAEvE,8CAA2D;AAC3D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AAC;SACtE,CAAC;QAEF,MAAM,mBAAmB,GACvB,OAAO,kBAAkB,KAAK,UAAU,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,QAAQ,CAAC;QAE3E,IAAI,mBAAmB,IAAI,IAAI,EAAE;YAC/B,MAAM,IAAI,iCAAyB,CAAC,qCAAqC,CAAC,CAAC;SAC5E;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QAE3C,IAAI;YACF,MAAM,mBAAmB,CAAC,OAAO,CAAC,CAAC;SACpC;gBAAS;YACR,IAAI;gBACF,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC;aAC5B;YAAC,MAAM;gBACN,qDAAqD;aACtD;SACF;IACH,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;CACF;AAlUD,kCAkUC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/mongo_logger.js b/2_PAC/node_modules/mongodb/lib/mongo_logger.js new file mode 100644 index 00000000..7a133f68 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/mongo_logger.js @@ -0,0 +1,113 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MongoLogger = exports.MongoLoggableComponent = exports.SeverityLevel = void 0; +const stream_1 = require("stream"); +const utils_1 = require("./utils"); +/** @internal */ +exports.SeverityLevel = Object.freeze({ + EMERGENCY: 'emergency', + ALERT: 'alert', + CRITICAL: 'critical', + ERROR: 'error', + WARNING: 'warn', + NOTICE: 'notice', + INFORMATIONAL: 'info', + DEBUG: 'debug', + TRACE: 'trace', + OFF: 'off' +}); +/** @internal */ +exports.MongoLoggableComponent = Object.freeze({ + COMMAND: 'command', + TOPOLOGY: 'topology', + SERVER_SELECTION: 'serverSelection', + CONNECTION: 'connection' +}); +/** + * Parses a string as one of SeverityLevel + * + * @param s - the value to be parsed + * @returns one of SeverityLevel if value can be parsed as such, otherwise null + */ +function parseSeverityFromString(s) { + const validSeverities = Object.values(exports.SeverityLevel); + const lowerSeverity = s?.toLowerCase(); + if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { + return lowerSeverity; + } + return null; +} +/** + * resolves the MONGODB_LOG_PATH and mongodbLogPath options from the environment and the + * mongo client options respectively. + * + * @returns the Writable stream to write logs to + */ +function resolveLogPath({ MONGODB_LOG_PATH }, { mongodbLogPath }) { + const isValidLogDestinationString = (destination) => ['stdout', 'stderr'].includes(destination.toLowerCase()); + if (typeof mongodbLogPath === 'string' && isValidLogDestinationString(mongodbLogPath)) { + return mongodbLogPath.toLowerCase() === 'stderr' ? process.stderr : process.stdout; + } + // TODO(NODE-4813): check for minimal interface instead of instanceof Writable + if (typeof mongodbLogPath === 'object' && mongodbLogPath instanceof stream_1.Writable) { + return mongodbLogPath; + } + if (typeof MONGODB_LOG_PATH === 'string' && isValidLogDestinationString(MONGODB_LOG_PATH)) { + return MONGODB_LOG_PATH.toLowerCase() === 'stderr' ? process.stderr : process.stdout; + } + return process.stderr; +} +/** @internal */ +class MongoLogger { + constructor(options) { + this.componentSeverities = options.componentSeverities; + this.maxDocumentLength = options.maxDocumentLength; + this.logDestination = options.logDestination; + } + /* eslint-disable @typescript-eslint/no-unused-vars */ + /* eslint-disable @typescript-eslint/no-empty-function */ + emergency(component, message) { } + alert(component, message) { } + critical(component, message) { } + error(component, message) { } + warn(component, message) { } + notice(component, message) { } + info(component, message) { } + debug(component, message) { } + trace(component, message) { } + /** + * Merges options set through environment variables and the MongoClient, preferring environment + * variables when both are set, and substituting defaults for values not set. Options set in + * constructor take precedence over both environment variables and MongoClient options. + * + * @remarks + * When parsing component severity levels, invalid values are treated as unset and replaced with + * the default severity. + * + * @param envOptions - options set for the logger from the environment + * @param clientOptions - options set for the logger in the MongoClient options + * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger + */ + static resolveOptions(envOptions, clientOptions) { + // client options take precedence over env options + const combinedOptions = { + ...envOptions, + ...clientOptions, + mongodbLogPath: resolveLogPath(envOptions, clientOptions) + }; + const defaultSeverity = parseSeverityFromString(combinedOptions.MONGODB_LOG_ALL) ?? exports.SeverityLevel.OFF; + return { + componentSeverities: { + command: parseSeverityFromString(combinedOptions.MONGODB_LOG_COMMAND) ?? defaultSeverity, + topology: parseSeverityFromString(combinedOptions.MONGODB_LOG_TOPOLOGY) ?? defaultSeverity, + serverSelection: parseSeverityFromString(combinedOptions.MONGODB_LOG_SERVER_SELECTION) ?? defaultSeverity, + connection: parseSeverityFromString(combinedOptions.MONGODB_LOG_CONNECTION) ?? defaultSeverity, + default: defaultSeverity + }, + maxDocumentLength: (0, utils_1.parseUnsignedInteger)(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1000, + logDestination: combinedOptions.mongodbLogPath + }; + } +} +exports.MongoLogger = MongoLogger; +//# sourceMappingURL=mongo_logger.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/mongo_logger.js.map b/2_PAC/node_modules/mongodb/lib/mongo_logger.js.map new file mode 100644 index 00000000..d3ca2868 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/mongo_logger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"mongo_logger.js","sourceRoot":"","sources":["../src/mongo_logger.ts"],"names":[],"mappings":";;;AAAA,mCAAkC;AAElC,mCAA+C;AAE/C,gBAAgB;AACH,QAAA,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,SAAS,EAAE,WAAW;IACtB,KAAK,EAAE,OAAO;IACd,QAA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ACnB,uBAAuB,CAAC,eAAe,CAAC,eAAe,CAAC,IAAI,qBAAa,CAAC,GAAG,CAAC;QAEhF,OAAO;YACL,mBAAmB,EAAE;gBACnB,OAAO,EAAE,uBAAuB,CAAC,eAAe,CAAC,mBAAmB,CAAC,IAAI,eAAe;gBACxF,QAAQ,EAAE,uBAAuB,CAAC,eAAe,CAAC,oBAAoB,CAAC,IAAI,eAAe;gBAC1F,eAAe,EACb,uBAAuB,CAAC,eAAe,CAAC,4BAA4B,CAAC,IAAI,eAAe;gBAC1F,UAAU,EACR,uBAAuB,CAAC,eAAe,CAAC,sBAAsB,CAAC,IAAI,eAAe;gBACpF,OAAO,EAAE,eAAe;aACzB;YACD,iBAAiB,EACf,IAAA,4BAAoB,EAAC,eAAe,CAAC,+BAA+B,CAAC,IAAI,IAAI;YAC/E,cAAc,EAAE,eAAe,CAAC,cAAc;SAC/C,CAAC;IACJ,CAAC;CACF;AAxED,kCAwEC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/mongo_types.js b/2_PAC/node_modules/mongodb/lib/mongo_types.js new file mode 100644 index 00000000..892f14d4 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/mongo_types.js @@ -0,0 +1,17 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CancellationToken = exports.TypedEventEmitter = void 0; +const events_1 = require("events"); +/** + * 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/2_PAC/node_modules/mongodb/lib/mongo_types.js.map b/2_PAC/node_modules/mongodb/lib/mongo_types.js.map new file mode 100644 index 00000000..c7fcc37e --- /dev/null +++ b/2_PAC/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;AA0YtC;;;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/2_PAC/node_modules/mongodb/lib/operations/add_user.js b/2_PAC/node_modules/mongodb/lib/operations/add_user.js new file mode 100644 index 00000000..59876a31 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/add_user.js @@ -0,0 +1,74 @@ +"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 ?? {}; + } + 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 + // v5 removed the digestPassword option from AddUserOptions but we still want to throw + // an error when digestPassword is provided. + if ('digestPassword' in options && 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/2_PAC/node_modules/mongodb/lib/operations/add_user.js.map b/2_PAC/node_modules/mongodb/lib/operations/add_user.js.map new file mode 100644 index 00000000..d96b6912 --- /dev/null +++ b/2_PAC/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;AAqBpD,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,IAAI,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,CAA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,EAAE,CAAC,CAAC;YAC5C,YAAY,GAAG,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;SAClC;QAED,+BAA+B;QAC/B,MAAM,OAAO,GAAa;YACxB,UAAU,EAAE,QAAQ;YACpB,UAAU,EAAE,OAAO,CAAC,UAAU,IAAI,EAAE;YACpC,KAAK,EAAE,KAAK;YACZ,cAAc;SACf,CAAC;QAEF,cAAc;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;AApFD,4CAoFC;AAED,IAAA,yBAAa,EAAC,gBAAgB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/aggregate.js b/2_PAC/node_modules/mongodb/lib/operations/aggregate.js new file mode 100644 index 00000000..ef73f38f --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/aggregate.js @@ -0,0 +1,88 @@ +"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 ?? {}; + // 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?.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?.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 (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/2_PAC/node_modules/mongodb/lib/operations/aggregate.js.map b/2_PAC/node_modules/mongodb/lib/operations/aggregate.js.map new file mode 100644 index 00000000..a50b275f --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/aggregate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"aggregate.js","sourceRoot":"","sources":["../../src/operations/aggregate.ts"],"names":[],"mappings":";;;AACA,oCAAqD;AAGrD,oCAAsE;AACtE,uCAAwF;AACxF,2CAA0D;AAE1D,gBAAgB;AACH,QAAA,uBAAuB,GAAG,CAAU,CAAC;AAClD,MAAM,0CAA0C,GAAG,CAAU,CAAC;AA0B9D,gBAAgB;AAChB,MAAa,kBAAiC,SAAQ,0BAAmB;IAMvE,YAAY,EAAoB,EAAE,QAAoB,EAAE,OAA0B;QAChF,KAAK,CAAC,SAAS,EAAE,EAAE,GAAG,OAAO,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC;QAEhD,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAE7B,gGAAgG;QAChG,IAAI,CAAC,MAAM,GAAG,EAAE,CAAC,UAAU,IAAI,+BAAuB,CAAC;QAEvD,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QAEzB,qEAAqE;QACrE,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,IAAI,OAAO,OAAO,EAAE,GAAG,KAAK,QAAQ,EAAE;YACpC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,GAAG,EAAE,CAAC,CAAC;YAC5D,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;SAC3B;aAAM,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9B,MAAM,UAAU,GAAG,QAAQ,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;YACjD,IAAI,UAAU,CAAC,IAAI,IAAI,UAAU,CAAC,MAAM,EAAE;gBACxC,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;aAC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O,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;AAjGD,gDAiGC;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/2_PAC/node_modules/mongodb/lib/operations/bulk_write.js b/2_PAC/node_modules/mongodb/lib/operations/bulk_write.js new file mode 100644 index 00000000..77299e8d --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/bulk_write.js @@ -0,0 +1,36 @@ +"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 }).then(result => callback(undefined, result), error => callback(error)); + } +} +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/2_PAC/node_modules/mongodb/lib/operations/bulk_write.js.map b/2_PAC/node_modules/mongodb/lib/operations/bulk_write.js.map new file mode 100644 index 00000000..08366dc8 --- /dev/null +++ b/2_PAC/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,CAAC,CAAC,IAAI,CACxC,MAAM,CAAC,EAAE,CAAC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC,EACrC,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;IACJ,CAAC;CACF;AA9CD,gDA8CC;AAED,IAAA,yBAAa,EAAC,kBAAkB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/collections.js b/2_PAC/node_modules/mongodb/lib/operations/collections.js new file mode 100644 index 00000000..0c1fdf58 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/collections.js @@ -0,0 +1,32 @@ +"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) { + // Let's get the collection names + this.db + .listCollections({}, { ...this.options, nameOnly: true, readPreference: this.readPreference, session }) + .toArray() + .then(documents => { + const collections = []; + for (const { name } of documents) { + if (!name.includes('$')) { + // Filter collections removing any illegal ones + collections.push(new collection_1.Collection(this.db, name, this.db.s.options)); + } + } + // Return the collection objects + callback(undefined, collections); + }, error => callback(error)); + } +} +exports.CollectionsOperation = CollectionsOperation; +//# sourceMappingURL=collections.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/collections.js.map b/2_PAC/node_modules/mongodb/lib/operations/collections.js.map new file mode 100644 index 00000000..fda34a0f --- /dev/null +++ b/2_PAC/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,iCAAiC;QACjC,IAAI,CAAC,EAAE;aACJ,eAAe,CACd,EAAE,EACF,EAAE,GAAG,IAAI,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAClF;aACA,OAAO,EAAE;aACT,IAAI,CACH,SAAS,CAAC,EAAE;YACV,MAAM,WAAW,GAAG,EAAE,CAAC;YACvB,KAAK,MAAM,EAAE,IAAI,EAAE,IAAI,SAAS,EAAE;gBAChC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE;oBACvB,+CAA+C;oBAC/C,WAAW,CAAC,IAAI,CAAC,IAAI,uBAAU,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC;iBACpE;aACF;YACD,gCAAgC;YAChC,QAAQ,CAAC,SAAS,EAAE,WAAW,CAAC,CAAC;QACnC,CAAC,EACD,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;IACN,CAAC;CACF;AArCD,oDAqCC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/command.js b/2_PAC/node_modules/mongodb/lib/operations/command.js new file mode 100644 index 00000000..b51990e3 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/command.js @@ -0,0 +1,78 @@ +"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"); +/** @internal */ +class CommandOperation extends operation_1.AbstractOperation { + constructor(parent, options) { + 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 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); + if (this.hasAspect(operation_1.Aspect.EXPLAINABLE)) { + this.explain = explain_1.Explain.fromOptions(options); + } + else if (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 (this.writeConcern && this.hasAspect(operation_1.Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + 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) { + 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/2_PAC/node_modules/mongodb/lib/operations/command.js.map b/2_PAC/node_modules/mongodb/lib/operations/command.js.map new file mode 100644 index 00000000..9d6c2584 --- /dev/null +++ b/2_PAC/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,oCAAqD;AACrD,wCAAqD;AACrD,kDAA8C;AAG9C,+DAA4E;AAE5E,oCAMkB;AAClB,oDAAqE;AAErE,2CAA0E;AAoD1E,gBAAgB;AAChB,MAAsB,gBAAoB,SAAQ,6BAAoB;IAMpE,YAAY,MAAwB,EAAE,OAAiC;QACrE,KAAK,CAAC,OAAO,CAAC,CAAC;Q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A,2BAAmB,EAAC,GAAG,EAAE,IAAI,CAAC,OAAO,CAAC,CAAC;SAC9C;QAED,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,GAAG,EAAE,OAAO,EAAE,QAAQ,CAAC,CAAC;IAClD,CAAC;CACF;AAxFD,4CAwFC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/common_functions.js b/2_PAC/node_modules/mongodb/lib/operations/common_functions.js new file mode 100644 index 00000000..e07d309a --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/common_functions.js @@ -0,0 +1,69 @@ +"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() + .then(indexes => { + if (!Array.isArray(indexes)) + return callback(undefined, []); + if (full) + return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }, error => callback(error)); +} +exports.indexInformation = indexInformation; +function prepareDocs(coll, docs, options) { + 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; + }); +} +exports.prepareDocs = prepareDocs; +//# sourceMappingURL=common_functions.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/common_functions.js.map b/2_PAC/node_modules/mongodb/lib/operations/common_functions.js.map new file mode 100644 index 00000000..a9e7d5a3 --- /dev/null +++ b/2_PAC/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;IAED,oCAAoC;IACpC,IAAI,QAAQ,CAAC,WAAW,EAAE;QAAE,OAAO,QAAQ,CAAC,IAAI,gCAAwB,EAAE,CAAC,CAAC;IAC5E,gEAAgE;IAChE,SAAS,cAAc,CAAC,OAAY;QAClC,+BAA+B;QAC/B,MAAM,IAAI,GAAQ,EAAE,CAAC;QACrB,0BAA0B;QAC1B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,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C;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/2_PAC/node_modules/mongodb/lib/operations/count.js b/2_PAC/node_modules/mongodb/lib/operations/count.js new file mode 100644 index 00000000..706dde67 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/operations/count.js.map b/2_PAC/node_modules/mongodb/lib/operations/count.js.map new file mode 100644 index 00000000..aeee5fd7 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"count.js","sourceRoot":"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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/2_PAC/node_modules/mongodb/lib/operations/count_documents.js b/2_PAC/node_modules/mongodb/lib/operations/count_documents.js new file mode 100644 index 00000000..562c9c06 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/operations/count_documents.js.map b/2_PAC/node_modules/mongodb/lib/operations/count_documents.js.map new file mode 100644 index 00000000..bc1ce7b6 --- /dev/null +++ b/2_PAC/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"],"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;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/2_PAC/node_modules/mongodb/lib/operations/create_collection.js b/2_PAC/node_modules/mongodb/lib/operations/create_collection.js new file mode 100644 index 00000000..ce6bfe72 --- /dev/null +++ b/2_PAC/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 () => { + const db = this.db; + const name = this.name; + const options = this.options; + const encryptedFields = 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 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/2_PAC/node_modules/mongodb/lib/operations/create_collection.js.map b/2_PAC/node_modules/mongodb/lib/operations/create_collection.js.map new file mode 100644 index 00000000..a3e244cf --- /dev/null +++ b/2_PAC/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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,MAAM,EAAE,EAAE;YACjD,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,IAAI,GAAa,GAAG,CAAC,EAAE;gBAC3B,IAAI,GAAG,EAAE;oBACP,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;iBACpB;gBAED,OAAO,CAAC,IAAI,uBAAU,CAAC,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC;YAC7C,CAAC,CAAC;YAEF,MAAM,GAAG,GAAa,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;YACvC,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE;gBACvB,IACG,OAAe,CAAC,CAAC,CAAC,IAAI,IAAI;oBAC3B,OAAQ,OAAe,CAAC,CAAC,CAAC,KAAK,UAAU;oBACzC,CAAC,sBAAsB,CAAC,GAAG,CAAC,CAAC,CAAC,EAC9B;oBACA,GAAG,CAAC,CAAC,CAAC,GAAI,OAAe,CAAC,CAAC,CAAC,CAAC;iBAC9B;aACF;YAED,qCAAqC;YACrC,KAAK,CAAC,cAAc,CAAC,MAAM,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/2_PAC/node_modules/mongodb/lib/operations/delete.js b/2_PAC/node_modules/mongodb/lib/operations/delete.js new file mode 100644 index 00000000..0164a261 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/delete.js @@ -0,0 +1,119 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.makeDeleteStatement = exports.DeleteManyOperation = exports.DeleteOneOperation = exports.DeleteOperation = void 0; +const error_1 = require("../error"); +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) { + const options = this.options ?? {}; + 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; + } + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + callback(new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`)); + 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) => { + 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: this.writeConcern?.w !== 0 ?? 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) => { + 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: this.writeConcern?.w !== 0 ?? 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.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/2_PAC/node_modules/mongodb/lib/operations/delete.js.map b/2_PAC/node_modules/mongodb/lib/operations/delete.js.map new file mode 100644 index 00000000..d1133e44 --- /dev/null +++ b/2_PAC/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;AAKrE,uCAAwF;AACxF,2CAA0D;AAkC1D,gBAAgB;AAChB,MAAa,eAAgB,SAAQ,0BAA8B;IAIjE,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,K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I,EAAE;QAChB,EAAE,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;KACxB;IAED,OAAO,EAAE,CAAC;AACZ,CAAC;AAlBD,kDAkBC;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/2_PAC/node_modules/mongodb/lib/operations/distinct.js b/2_PAC/node_modules/mongodb/lib/operations/distinct.js new file mode 100644 index 00000000..13a06dee --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/distinct.js @@ -0,0 +1,67 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DistinctOperation = void 0; +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 ?? {}; + 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; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (typeof options.comment !== 'undefined') { + cmd.comment = options.comment; + } + // 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); + } + 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/2_PAC/node_modules/mongodb/lib/operations/distinct.js.map b/2_PAC/node_modules/mongodb/lib/operations/distinct.js.map new file mode 100644 index 00000000..ef191acf --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/distinct.js.map @@ -0,0 +1 @@ +{"version":3,"file":"distinct.js","sourceRoot":"","sources":["../../src/operations/distinct.ts"],"names":[],"mappings":";;;AAIA,oCAAoF;AACpF,uCAAsE;AACtE,2CAAoD;AAKpD;;;GAGG;AACH,MAAa,iBAAkB,SAAQ,0BAAuB;IAQ5D;;;;;;;OAOG;IACH,YAAY,UAAsB,EAAE,GAAW,EAAE,KAAe,EAAE,OAAyB;QACzF,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAE3B,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;QACf,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAAyB;QAEzB,MAAM,IAAI,GAAG,IAAI,CAAC,UAAU,CAAC;QAC7B,MAAM,GAA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AAC,SAAS,EAAE,kBAAM,CAAC,WAAW,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/drop.js b/2_PAC/node_modules/mongodb/lib/operations/drop.js new file mode 100644 index 00000000..50b39dc0 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/drop.js @@ -0,0 +1,83 @@ +"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 () => { + const db = this.db; + const options = this.options; + const name = this.name; + const encryptedFieldsMap = db.s.client.options.autoEncryption?.encryptedFieldsMap; + let encryptedFields = options.encryptedFields ?? encryptedFieldsMap?.[`${db.databaseName}.${name}`]; + if (!encryptedFields && encryptedFieldsMap) { + // If the MongoClient was configured 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 error_1.MongoServerError) || + err.code !== error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + throw err; + } + } + } + } + return 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/2_PAC/node_modules/mongodb/lib/operations/drop.js.map b/2_PAC/node_modules/mongodb/lib/operations/drop.js.map new file mode 100644 index 00000000..47f28932 --- /dev/null +++ b/2_PAC/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,EA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,CAAC,GAAG,CAAC,CAAC;YAC9B,IAAI,MAAM,CAAC,EAAE;gBAAE,OAAO,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;YAChD,QAAQ,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QAC7B,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAlBD,sDAkBC;AAED,IAAA,yBAAa,EAAC,uBAAuB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC;AACjE,IAAA,yBAAa,EAAC,qBAAqB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/estimated_document_count.js b/2_PAC/node_modules/mongodb/lib/operations/estimated_document_count.js new file mode 100644 index 00000000..e5948f2c --- /dev/null +++ b/2_PAC/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?.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/2_PAC/node_modules/mongodb/lib/operations/estimated_document_count.js.map b/2_PAC/node_modules/mongodb/lib/operations/estimated_document_count.js.map new file mode 100644 index 00000000..927b7bca --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/estimated_document_count.js.map @@ -0,0 +1 @@ +{"version":3,"file":"estimated_document_count.js","sourceRoot":"","sources":["../../src/operations/estimated_document_count.ts"],"names":[],"mappings":";;;AAKA,uCAAsE;AACtE,2CAAoD;AAYpD,gBAAgB;AAChB,MAAa,+BAAgC,SAAQ,0BAAwB;IAI3E,YAAY,UAAsB,EAAE,UAAyC,EAAE;QAC7E,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,cAAc,GAAG,UAAU,CAAC,cAAc,CAAC;IAClD,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA0B;QAE1B,MAAM,GAAG,GAAa,EAAE,KAAK,EAAE,IAAI,CAAC,cAAc,EAAE,CAAC;QAErD,IAAI,OAAO,IAAI,CAAC,OAAO,CAAC,SAAS,KAAK,QAAQ,EAAE;YAC9C,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,OAAO,CAAC,SAAS,CAAC;SACxC;QAED,iEAAiE;QACjE,gDAAgD;QAChD,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;YACtC,GAAG,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;SACpC;QAED,KAAK,CAAC,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE;YAC3D,IAAI,GAAG,EAAE;gBACP,QAAQ,CAAC,GAAG,CAAC,CAAC;gBACd,OAAO;aACR;YAED,QAAQ,CAAC,SAAS,EAAE,QAAQ,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC;QACxC,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AApCD,0EAoCC;AAED,IAAA,yBAAa,EAAC,+BAA+B,EAAE;IAC7C,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;CACvB,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/eval.js b/2_PAC/node_modules/mongodb/lib/operations/eval.js new file mode 100644 index 00000000..0354c60c --- /dev/null +++ b/2_PAC/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 ?? {}; + 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/2_PAC/node_modules/mongodb/lib/operations/eval.js.map b/2_PAC/node_modules/mongodb/lib/operations/eval.js.map new file mode 100644 index 00000000..cc43a0dc --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/eval.js.map @@ -0,0 +1 @@ +{"version":3,"file":"eval.js","sourceRoot":"","sources":["../../src/operations/eval.ts"],"names":[],"mappings":";;;AAAA,kCAAyC;AAGzC,oCAA4C;AAC5C,wDAAoD;AAIpD,uCAAsE;AAOtE,gBAAgB;AAChB,MAAa,aAAc,SAAQ,0BAA0B;IAK3D,YACE,EAAmB,EACnB,IAAU,EACV,UAAkC,EAClC,OAAqB;QAErB,KAAK,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;QAEnB,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,gCAAgC;QAChC,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,gBAAgB,EAAE;YAC5C,KAAK,EAAE,gCAAc,CAAC,OAAO;YAC7B,YAAY,EAAE,KAAK;YACnB,QAAQ,EAAE,KAAK;SAChB,CAAC,CAAC;IACL,CAAC;IAEQ,OAAO,CACd,MAAc,EACd,OAAkC,EAClC,QAA4B;QAE5B,IAAI,SAAS,GAAG,IAAI,CAAC,IAAI,CAAC;QAC1B,IAAI,eAAe,GAAe,EAAE,CAAC;QAErC,wCAAwC;QACxC,IAAI,CAAC,CAAC,SAAS,IAAK,SAA8C,CAAC,SAAS,KAAK,MAAM,CAAC,EAAE;YACxF,SAAS,GAAG,IAAI,WAAI,CAAC,SAAkB,CAAC,CAAC;SAC1C;QAED,oCAAoC;QACpC,IAAI,IAAI,CAAC,UAAU,IAAI,IAAI,IAAI,OAAO,IAAI,CAAC,UAAU,KAAK,UAAU,EAAE;YACpE,eAAe,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;SACxF;QAED,4BAA4B;QAC5B,MAAM,GAAG,GAAa,EAAE,KAAK,EAAE,SAAS,EAAE,IAAI,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/2_PAC/node_modules/mongodb/lib/operations/execute_operation.js b/2_PAC/node_modules/mongodb/lib/operations/execute_operation.js new file mode 100644 index 00000000..bb7978ed --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/execute_operation.js @@ -0,0 +1,181 @@ +"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) { + return (0, utils_1.maybeCallback)(() => executeOperationAsync(client, operation), callback); +} +exports.executeOperation = executeOperation; +async function executeOperationAsync(client, operation) { + if (!(operation instanceof operation_1.AbstractOperation)) { + // TODO(NODE-3483): Extend MongoRuntimeError + throw new error_1.MongoRuntimeError('This method requires a valid operation instance'); + } + if (client.topology == null) { + // Auto connect on operation + if (client.s.hasBeenClosed) { + throw new error_1.MongoNotConnectedError('Client must be connected before running operations'); + } + client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true; + try { + await client.connect(); + } + finally { + delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')]; + } + } + const { topology } = client; + if (topology == null) { + throw new error_1.MongoRuntimeError('client.connect did not create a topology but also did not throw'); + } + if (topology.shouldCheckForSessionSupport()) { + await topology.selectServerAsync(read_preference_1.ReadPreference.primaryPreferred, {}); + } + // 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) { + throw new error_1.MongoExpiredSessionError('Use of expired sessions is not permitted'); + } + else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + throw 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. + throw 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; + } + } + const readPreference = operation.readPreference ?? read_preference_1.ReadPreference.primary; + const inTransaction = !!session?.inTransaction(); + if (inTransaction && !readPreference.equals(read_preference_1.ReadPreference.primary)) { + throw new error_1.MongoTransactionError(`Read preference in a transaction must be primary, not: ${readPreference.mode}`); + } + if (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)(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 = (0, server_selection_1.secondaryWritableServerSelector)(topology.commonWireVersion, readPreference); + } + else { + selector = readPreference; + } + const server = await topology.selectServerAsync(selector, { session }); + if (session == null) { + // No session also means it is not retryable, early exit + return operation.executeAsync(server, undefined); + } + if (!operation.hasAspect(operation_1.Aspect.RETRYABLE)) { + // non-retryable operation, early exit + try { + return await operation.executeAsync(server, session); + } + finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } + } + 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); + const willRetry = (hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite); + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + try { + return await operation.executeAsync(server, session); + } + catch (operationError) { + if (willRetry && operationError instanceof error_1.MongoError) { + return await retryOperation(operation, operationError, { + session, + topology, + selector + }); + } + throw operationError; + } + finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } +} +async function retryOperation(operation, originalError, { session, topology, selector }) { + 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) { + throw new error_1.MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError + }); + } + if (isWriteOperation && !(0, error_1.isRetryableWriteError)(originalError)) { + throw originalError; + } + if (isReadOperation && !(0, error_1.isRetryableReadError)(originalError)) { + throw originalError; + } + if (originalError instanceof error_1.MongoNetworkError && + 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 + const server = await topology.selectServerAsync(selector, { session }); + if (isWriteOperation && !(0, utils_1.supportsRetryableWrites)(server)) { + throw new error_1.MongoUnexpectedServerResponseError('Selected server does not support retryable writes'); + } + try { + return await operation.executeAsync(server, session); + } + catch (retryError) { + if (retryError instanceof error_1.MongoError && + retryError.hasErrorLabel(error_1.MongoErrorLabel.NoWritesPerformed)) { + throw originalError; + } + throw retryError; + } +} +//# sourceMappingURL=execute_operation.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/execute_operation.js.map b/2_PAC/node_modules/mongodb/lib/operations/execute_operation.js.map new file mode 100644 index 00000000..e21b3921 --- /dev/null +++ b/2_PAC/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,oCAckB;AAElB,wDAAoD;AAEpD,+DAIkC;AAGlC,oCAA4E;AAC5E,2CAAwD;AAExD,MAAM,8BAA8B,GAAG,2BAAmB,CAAC,gBAAgB,CAAC;AAC5E,MAAM,iCAAiC,GACrC,oHAAoH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,CAAC;KAClB;AACH,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/find.js b/2_PAC/node_modules/mongodb/lib/operations/find.js new file mode 100644 index 00000000..e98c892d --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/find.js @@ -0,0 +1,155 @@ +"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"); +/** @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 options = this.options; + 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.oplogReplay === 'boolean') { + findCommand.oplogReplay = options.oplogReplay; + } + 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/2_PAC/node_modules/mongodb/lib/operations/find.js.map b/2_PAC/node_modules/mongodb/lib/operations/find.js.map new file mode 100644 index 00000000..be1e12ff --- /dev/null +++ b/2_PAC/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,oCAAqD;AACrD,kDAA8C;AAG9C,kCAA2C;AAC3C,oCAA+F;AAC/F,uCAAwF;AACxF,2CAA0D;AAyD1D,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,MAAM,CAAC,EAAE;YACvD,MAAM,IAAI,iCAAyB,CAAC,iDAAiD,CAAC,CAAC;SACxF;QAED,oEAAoE;QACpE,IAAI,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;YAC3B,MAAM,UAAU,GAAG,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;YACxF,IAAI,UAAU,KAAK,MAAM,CAAC,MAAM,EAAE;gBAChC,MAAM,IAAI,iCAA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,WAAW,CAAC,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC;KAC/C;IAED,IAAI,OAAO,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;QACxC,WAAW,CAAC,eAAe,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC;KAChD;SAAM,IAAI,OAAO,OAAO,CAAC,eAAe,KAAK,SAAS,EAAE;QACvD,WAAW,CAAC,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC;KACvD;IAED,IAAI,OAAO,OAAO,CAAC,SAAS,KAAK,SAAS,EAAE;QAC1C,WAAW,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;KAC3C;IAED,IAAI,OAAO,OAAO,CAAC,mBAAmB,KAAK,SAAS,EAAE;QACpD,WAAW,CAAC,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,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/2_PAC/node_modules/mongodb/lib/operations/find_and_modify.js b/2_PAC/node_modules/mongodb/lib/operations/find_and_modify.js new file mode 100644 index 00000000..f44efb84 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/find_and_modify.js @@ -0,0 +1,151 @@ +"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 ?? {}; + 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) { + 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 = this.writeConcern?.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; + } + // 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/2_PAC/node_modules/mongodb/lib/operations/find_and_modify.js.map b/2_PAC/node_modules/mongodb/lib/operations/find_and_modify.js.map new file mode 100644 index 00000000..d68f9f95 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/find_and_modify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"find_and_modify.js","sourceRoot":"","sources":["../../src/operations/find_and_modify.ts"],"names":[],"mappings":";;;AAEA,oCAA8E;AAC9E,wDAAoD;AAGpD,kCAAuD;AACvD,oCAA+F;AAE/F,uCAAsE;AACtE,2CAAoD;AAEpD,cAAc;AACD,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;CACN,CAAC,CAAC;AA+EZ,SAAS,uCAAuC,CAC9C,OAA6B,EAC7B,OAA2D;IAE3D,OAAO,CAAC,GAAG,GAAG,OAAO,CAAC,cAAc,KAAK,sBAAc,CAAC,KAAK,CAAC;IAC9D,OAAO,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC;IAEzC,IAAI,OAAO,CAAC,wBAAwB,KAAK,IAAI,EAAE;QAC7C,OAAO,CAAC,wBAAwB,GAAG,OAAO,CAAC,wBAAwB,CAAC;KACrE;IACD,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,gBAAgB;AAChB,MAAM,sBAAuB,SAAQ,0BAA0B;IAO7D,YACE,UAAsB,EACtB,KAAe,EACf,OAAqF;QAErF,KAAK,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG;YACb,MAAM,EAAE,KAAK;YACb,GAAG,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QAED,KAAK,CAAC,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC;QACnC,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,MAAM,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/2_PAC/node_modules/mongodb/lib/operations/get_more.js b/2_PAC/node_modules/mongodb/lib/operations/get_more.js new file mode 100644 index 00000000..94ba64ed --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/get_more.js @@ -0,0 +1,58 @@ +"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; + 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')); + } + if (this.cursorId == null || this.cursorId.isZero()) { + return callback(new error_1.MongoRuntimeError('Unable to iterate cursor with no id')); + } + const collection = this.ns.collection; + if (collection == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + return callback(new error_1.MongoRuntimeError('A collection name must be determined before getMore')); + } + const getMoreCmd = { + getMore: this.cursorId, + collection + }; + if (typeof this.options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(this.options.batchSize); + } + if (typeof this.options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; + } + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined && (0, utils_1.maxWireVersion)(server) >= 9) { + getMoreCmd.comment = this.options.comment; + } + const commandOptions = { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch', + ...this.options + }; + server.command(this.ns, getMoreCmd, commandOptions, 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/2_PAC/node_modules/mongodb/lib/operations/get_more.js.map b/2_PAC/node_modules/mongodb/lib/operations/get_more.js.map new file mode 100644 index 00000000..3803d986 --- /dev/null +++ b/2_PAC/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;AA+BzF,gBAAgB;AAChB,MAAa,gBAAiB,SAAQ,6BAAiB;IAIrD,YAAY,EAAoB,EAAE,QAAc,EAAE,MAAc,EAAE,OAAuB;QACvF,KAAK,CAAC,OAAO,CAAC,CAAC;QAEf,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,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,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AAQ,CAAC,CAAC;IAChE,CAAC;CACF;AAlED,4CAkEC;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/2_PAC/node_modules/mongodb/lib/operations/indexes.js b/2_PAC/node_modules/mongodb/lib/operations/indexes.js new file mode 100644 index 00000000..bf8748ab --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/indexes.js @@ -0,0 +1,269 @@ +"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 isIndexDirection(x) { + return (typeof x === 'number' || x === '2d' || x === '2dsphere' || x === 'text' || x === 'geoHaystack'); +} +function isSingleIndexTuple(t) { + return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]); +} +function makeIndexSpec(indexSpec, options) { + const key = new Map(); + const indexSpecs = !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec; + // Iterate through array and handle different types + for (const spec of indexSpecs) { + if (typeof spec === 'string') { + key.set(spec, 1); + } + else if (Array.isArray(spec)) { + key.set(spec[0], spec[1] ?? 1); + } + else if (spec instanceof Map) { + for (const [property, value] of spec) { + key.set(property, value); + } + } + else if ((0, utils_1.isObject)(spec)) { + for (const [property, value] of Object.entries(spec)) { + key.set(property, value); + } + } + } + return { ...options, key }; +} +/** @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 ?? {}; + this.collectionName = collectionName; + this.indexes = indexes.map(userIndex => { + // Ensure the key is a Map to preserve index key ordering + const key = userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key)); + const name = userIndex.name != null ? userIndex.name : Array.from(key).flat().join('_'); + const validIndexOptions = Object.fromEntries(Object.entries({ ...userIndex }).filter(([optionName]) => VALID_INDEX_OPTIONS.has(optionName))); + return { + ...validIndexOptions, + name, + key + }; + }); + } + execute(server, session, callback) { + const options = this.options; + const indexes = this.indexes; + const serverWireVersion = (0, utils_1.maxWireVersion)(server); + 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) { + 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().then(indexes => { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + super.execute(server, session, callback); + }, error => { + if (error instanceof error_1.MongoError && error.code === error_1.MONGODB_ERROR_CODES.NamespaceNotFound) { + // ignore "NamespaceNotFound" errors + return super.execute(server, session, callback); + } + return callback(error); + }); + } +} +exports.EnsureIndexOperation = EnsureIndexOperation; +/** @internal */ +class DropIndexOperation extends command_1.CommandOperation { + constructor(collection, indexName, options) { + super(collection, options); + this.options = 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 ?? {}; + 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 ?? {}; + 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/2_PAC/node_modules/mongodb/lib/operations/indexes.js.map b/2_PAC/node_modules/mongodb/lib/operations/indexes.js.map new file mode 100644 index 00000000..ea0f4774 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/indexes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"indexes.js","sourceRoot":"","sources":["../../src/operations/indexes.ts"],"names":[],"mappings":";;;AAGA,oCAAoF;AAEpF,wDAAoD;AAGpD,oCAAgF;AAChF,uCAKmB;AACnB,yDAA+E;AAC/E,2CAAuE;AAEvE,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC;IAClC,YAAY;IACZ,QAAQ;IACR,MAAM;IACN,yBAAyB;IACzB,QAAQ;IACR,QAAQ;IACR,oBAAoB;IACpB,eAAe;IACf,WAAW;IACX,SAAS;IAET,eAAe;IACf,SAAS;IACT,kBAAkB;IAClB,mBAAmB;IACnB,kBAAkB;IAElB,oBAAoB;IACpB,sBAAsB;IAEtB,aAAa;IACb,MAAM;IACN,KAAK;IACL,KAAK;IAEL,sBAAsB;IACtB,YAAY;IAEZ,mBAAmB;IACnB,oBAAoB;CACrB,CAAC,CAAC;AAaH,SAAS,gBAAgB,CAAC,CAAU;IAClC,OAAO,CACL,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,UAAU,IAAI,CAAC,KAAK,MAAM,IAAI,CAAC,KAAK,aAAa,CAC/F,CAAC;AACJ,CAAC;AA8ED,SAAS,kBAAkB,CAAC,CAAU;IACpC,OAAO,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACtE,CAAC;AAED,SAAS,aAAa,CACpB,SAA6B,EAC7B,OAA8B;IAE9B,MAAM,GAAG,GAAgC,IAAI,GAAG,EAAE,CAAC;IAEnD,MAAM,UAAU,GACd,CAAC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C;AAC5D,IAAA,yBAAa,EAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,eAAe,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/insert.js b/2_PAC/node_modules/mongodb/lib/operations/insert.js new file mode 100644 index 00000000..adf31329 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/insert.js @@ -0,0 +1,95 @@ +"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) { + super(undefined, options); + this.options = { ...options, checkKeys: options.checkKeys ?? false }; + this.ns = ns; + this.documents = documents; + } + execute(server, session, callback) { + const options = this.options ?? {}; + 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) => { + 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: this.writeConcern?.w !== 0 ?? 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) => { + 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: writeConcern?.w !== 0 ?? 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/2_PAC/node_modules/mongodb/lib/operations/insert.js.map b/2_PAC/node_modules/mongodb/lib/operations/insert.js.map new file mode 100644 index 00000000..22affc58 --- /dev/null +++ b/2_PAC/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,eA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AC,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/2_PAC/node_modules/mongodb/lib/operations/is_capped.js b/2_PAC/node_modules/mongodb/lib/operations/is_capped.js new file mode 100644 index 00000000..096ebe22 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/is_capped.js @@ -0,0 +1,28 @@ +"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() + .then(collections => { + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + callback(undefined, !!collections[0].options?.capped); + }, error => callback(error)); + } +} +exports.IsCappedOperation = IsCappedOperation; +//# sourceMappingURL=is_capped.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/is_capped.js.map b/2_PAC/node_modules/mongodb/lib/operations/is_capped.js.map new file mode 100644 index 00000000..0cb6b533 --- /dev/null +++ b/2_PAC/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,EAAE;aACT,IAAI,CACH,WAAW,CAAC,EAAE;YACZ,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,SAAS,EAAE,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QACxD,CAAC,EACD,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;IACN,CAAC;CACF;AAnCD,8CAmCC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/kill_cursors.js b/2_PAC/node_modules/mongodb/lib/operations/kill_cursors.js new file mode 100644 index 00000000..63d6e3e6 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/kill_cursors.js @@ -0,0 +1,32 @@ +"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')); + } + const killCursors = this.ns.collection; + if (killCursors == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + return callback(new error_1.MongoRuntimeError('A collection name must be determined before killCursors')); + } + const killCursorsCommand = { + killCursors, + cursors: [this.cursorId] + }; + server.command(this.ns, killCursorsCommand, { 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/2_PAC/node_modules/mongodb/lib/operations/kill_cursors.js.map b/2_PAC/node_modules/mongodb/lib/operations/kill_cursors.js.map new file mode 100644 index 00000000..022ad687 --- /dev/null +++ b/2_PAC/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;AAYzF,MAAa,oBAAqB,SAAQ,6BAAiB;IAGzD,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;QAED,MAAM,WAAW,GAAG,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC;QACvC,IAAI,WAAW,IAAI,IAAI,EAAE;YACvB,gEAAgE;YAChE,wFAAwF;YACxF,OAAO,QAAQ,CACb,IAAI,yBAAiB,CAAC,yDAAyD,CAAC,CACjF,CAAC;SACH;QAED,MAAM,kBAAkB,GAAuB;YAC7C,WAAW;YACX,OAAO,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC;SACzB,CAAC;QAEF,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,kBAAkB,EAAE,EAAE,OAAO,EAAE,EAAE,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC,CAAC;IAC7E,CAAC;CACF;AAjCD,oDAiCC;AAED,IAAA,yBAAa,EAAC,oBAAoB,EAAE,CAAC,kBAAM,CAAC,uBAAuB,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/list_collections.js b/2_PAC/node_modules/mongodb/lib/operations/list_collections.js new file mode 100644 index 00000000..7ed8465d --- /dev/null +++ b/2_PAC/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 ?? {}; + 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/2_PAC/node_modules/mongodb/lib/operations/list_collections.js.map b/2_PAC/node_modules/mongodb/lib/operations/list_collections.js.map new file mode 100644 index 00000000..b42d5ba0 --- /dev/null +++ b/2_PAC/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,IAAI,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/2_PAC/node_modules/mongodb/lib/operations/list_databases.js b/2_PAC/node_modules/mongodb/lib/operations/list_databases.js new file mode 100644 index 00000000..8cd6ec82 --- /dev/null +++ b/2_PAC/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 ?? {}; + 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/2_PAC/node_modules/mongodb/lib/operations/list_databases.js.map b/2_PAC/node_modules/mongodb/lib/operations/list_databases.js.map new file mode 100644 index 00000000..875353e9 --- /dev/null +++ b/2_PAC/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,IAAI,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/2_PAC/node_modules/mongodb/lib/operations/operation.js b/2_PAC/node_modules/mongodb/lib/operations/operation.js new file mode 100644 index 00000000..9a0297fb --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/operation.js @@ -0,0 +1,73 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.defineAspects = exports.AbstractOperation = exports.Aspect = void 0; +const util_1 = require("util"); +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 = {}) { + this.executeAsync = (0, util_1.promisify)((server, session, callback) => { + this.execute(server, session, callback); + }); + this.readPreference = this.hasAspect(exports.Aspect.WRITE_OPERATION) + ? read_preference_1.ReadPreference.primary + : read_preference_1.ReadPreference.fromOptions(options) ?? 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/2_PAC/node_modules/mongodb/lib/operations/operation.js.map b/2_PAC/node_modules/mongodb/lib/operations/operation.js.map new file mode 100644 index 00000000..4ad62a39 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/operation.js.map @@ -0,0 +1 @@ +{"version":3,"file":"operation.js","sourceRoot":"","sources":["../../src/operations/operation.ts"],"names":[],"mappings":";;;AAAA,+BAAiC;AAEjC,kCAA6E;AAC7E,wDAAwE;AAK3D,QAAA,MAAM,GAAG;IACpB,cAAc,EAAE,MA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,SAAS,CAAC,MAAc;QACtB,MAAM,IAAI,GAAG,IAAI,CAAC,WAAmC,CAAC;QACtD,IAAI,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;AAxED,8CAwEC;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/2_PAC/node_modules/mongodb/lib/operations/options_operation.js b/2_PAC/node_modules/mongodb/lib/operations/options_operation.js new file mode 100644 index 00000000..37fb7e62 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/options_operation.js @@ -0,0 +1,28 @@ +"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() + .then(collections => { + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new error_1.MongoAPIError(`collection ${coll.namespace} not found`)); + } + callback(undefined, collections[0].options); + }, error => callback(error)); + } +} +exports.OptionsOperation = OptionsOperation; +//# sourceMappingURL=options_operation.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/options_operation.js.map b/2_PAC/node_modules/mongodb/lib/operations/options_operation.js.map new file mode 100644 index 00000000..9b27753b --- /dev/null +++ b/2_PAC/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,EAAE;aACT,IAAI,CACH,WAAW,CAAC,EAAE;YACZ,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,SAAS,EAAE,WAAW,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;QAC9C,CAAC,EACD,KAAK,CAAC,EAAE,CAAC,QAAQ,CAAC,KAAK,CAAC,CACzB,CAAC;IACN,CAAC;CACF;AAnCD,4CAmCC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/profiling_level.js b/2_PAC/node_modules/mongodb/lib/operations/profiling_level.js new file mode 100644 index 00000000..33802dfa --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/operations/profiling_level.js.map b/2_PAC/node_modules/mongodb/lib/operations/profiling_level.js.map new file mode 100644 index 00000000..8630fdc0 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/operations/remove_user.js b/2_PAC/node_modules/mongodb/lib/operations/remove_user.js new file mode 100644 index 00000000..daab3ebf --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/operations/remove_user.js.map b/2_PAC/node_modules/mongodb/lib/operations/remove_user.js.map new file mode 100644 index 00000000..d689529a --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/operations/rename.js b/2_PAC/node_modules/mongodb/lib/operations/rename.js new file mode 100644 index 00000000..82b7ec36 --- /dev/null +++ b/2_PAC/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?.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/2_PAC/node_modules/mongodb/lib/operations/rename.js.map b/2_PAC/node_modules/mongodb/lib/operations/rename.js.map new file mode 100644 index 00000000..63e983d0 --- /dev/null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B,mBAAmB;YACnB,IAAI,GAAG,EAAE,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/2_PAC/node_modules/mongodb/lib/operations/run_command.js b/2_PAC/node_modules/mongodb/lib/operations/run_command.js new file mode 100644 index 00000000..10f3ebab --- /dev/null +++ b/2_PAC/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 ?? {}; + 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/2_PAC/node_modules/mongodb/lib/operations/run_command.js.map b/2_PAC/node_modules/mongodb/lib/operations/run_command.js.map new file mode 100644 index 00000000..43096290 --- /dev/null +++ b/2_PAC/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,IAAI,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/2_PAC/node_modules/mongodb/lib/operations/set_profiling_level.js b/2_PAC/node_modules/mongodb/lib/operations/set_profiling_level.js new file mode 100644 index 00000000..4ff83297 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/operations/set_profiling_level.js.map b/2_PAC/node_modules/mongodb/lib/operations/set_profiling_level.js.map new file mode 100644 index 00000000..4928b616 --- /dev/null +++ b/2_PAC/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,oCAAwE;AAIxE,oCAAwC;AACxC,uCAAsE;AAEtE,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,WAAW,EAAE,KAAK,CAAC,CAAC,CAAC;AAEzD,cAAc;AACD,QAAA,cAAc,GAAG,MAAM,CAAC,MAAM,CAAC;IAC1C,GAAG,EAAE,KAAK;IACV,QAAQ,EAAE,WAAW;IACrB,GAAG,EAAE,KAAK;CACF,C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BACf,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/2_PAC/node_modules/mongodb/lib/operations/stats.js b/2_PAC/node_modules/mongodb/lib/operations/stats.js new file mode 100644 index 00000000..6139ca3c --- /dev/null +++ b/2_PAC/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 ?? {}; + 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/2_PAC/node_modules/mongodb/lib/operations/stats.js.map b/2_PAC/node_modules/mongodb/lib/operations/stats.js.map new file mode 100644 index 00000000..321a494c --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/stats.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stats.js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C,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/2_PAC/node_modules/mongodb/lib/operations/update.js b/2_PAC/node_modules/mongodb/lib/operations/update.js new file mode 100644 index 00000000..122dc7d3 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/operations/update.js @@ -0,0 +1,183 @@ +"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) { + const options = this.options ?? {}; + 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 unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + callback(new error_1.MongoCompatibilityError(`hint is not supported with unacknowledged writes`)); + 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) => { + 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: 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 + }); + }); + } +} +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) => { + 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: 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 + }); + }); + } +} +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) => { + 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: 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 + }); + }); + } +} +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/2_PAC/node_modules/mongodb/lib/operations/update.js.map b/2_PAC/node_modules/mongodb/lib/operations/update.js.map new file mode 100644 index 00000000..4488092a --- /dev/null +++ b/2_PAC/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,oCAA0E;AAC1E,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,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;QACnC,MAAM,OAAO,GAAG,OA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EAAE,CAAC,SAAS,GAAG,OAAO,CAAC,SAAS,CAAC;KAClC;IAED,OAAO,EAAE,CAAC;AACZ,CAAC;AAnCD,kDAmCC;AAED,IAAA,yBAAa,EAAC,eAAe,EAAE,CAAC,kBAAM,CAAC,SAAS,EAAE,kBAAM,CAAC,eAAe,EAAE,kBAAM,CAAC,cAAc,CAAC,CAAC,CAAC;AAClG,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;AACH,IAAA,yBAAa,EAAC,mBAAmB,EAAE;IACjC,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,eAAe;IACtB,kBAAM,CAAC,cAAc;CACtB,CAAC,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/operations/validate_collection.js b/2_PAC/node_modules/mongodb/lib/operations/validate_collection.js new file mode 100644 index 00000000..1a7c978e --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/operations/validate_collection.js.map b/2_PAC/node_modules/mongodb/lib/operations/validate_collection.js.map new file mode 100644 index 00000000..9d72c418 --- /dev/null +++ b/2_PAC/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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AAO,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/2_PAC/node_modules/mongodb/lib/read_concern.js b/2_PAC/node_modules/mongodb/lib/read_concern.js new file mode 100644 index 00000000..28580c33 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/read_concern.js @@ -0,0 +1,73 @@ +"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) { + /** + * 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 = exports.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) { + 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/2_PAC/node_modules/mongodb/lib/read_concern.js.map b/2_PAC/node_modules/mongodb/lib/read_concern.js.map new file mode 100644 index 00000000..5df31985 --- /dev/null +++ b/2_PAC/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,wBAAgB,CAAC,KAAK,CAAC,IAAI,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/2_PAC/node_modules/mongodb/lib/read_preference.js b/2_PAC/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 00000000..e192281a --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,195 @@ +"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' +}); +/** + * 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/ + */ +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?.hedge; + this.maxStalenessSeconds = undefined; + this.minWireVersion = undefined; + options = 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) { + 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, 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; + } + /** + * 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 + * @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; + } +} +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/2_PAC/node_modules/mongodb/lib/read_preference.js.map b/2_PAC/node_modules/mongodb/lib/read_preference.js.map new file mode 100644 index 00000000..7c6ac51d --- /dev/null +++ b/2_PAC/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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B,GAAG,IAAI,cAAc,CAAC,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/2_PAC/node_modules/mongodb/lib/sdam/common.js b/2_PAC/node_modules/mongodb/lib/sdam/common.js new file mode 100644 index 00000000..60b96aa3 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/common.js @@ -0,0 +1,56 @@ +"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; +const timers_1 = require("timers"); +// 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(timers_1.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/2_PAC/node_modules/mongodb/lib/sdam/common.js.map b/2_PAC/node_modules/mongodb/lib/sdam/common.js.map new file mode 100644 index 00000000..95a76c42 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/sdam/common.ts"],"names":[],"mappings":";;;AAAA,mCAAsC;AAMtC,qBAAqB;AACR,QAAA,aAAa,GAAG,SAAS,CAAC;AAC1B,QAAA,YAAY,GAAG,QAAQ,CAAC;AACxB,QAAA,gBAAgB,GAAG,YAAY,CAAC;AAChC,QAAA,eAAe,GAAG,WAAW,CAAC;AAE3C;;;GAGG;AACU,QAAA,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC;IACxC,MAAM,EAAE,QAAQ;IAChB,mBAAmB,EAAE,qBAAqB;IAC1C,qBAAqB,EAAE,uBAAuB;IAC9C,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAKZ;;;GAGG;AACU,QAAA,UAAU,GAAG,MAAM,CAAC,MAAM,CAAC;IACtC,UAAU,EAAE,YAAY;IACxB,MAAM,EAAE,QAAQ;IAChB,eAAe,EAAE,iBAAiB;IAClC,SAAS,EAAE,WAAW;IACtB,WAAW,EAAE,aAAa;IAC1B,SAAS,EAAE,WAAW;IACtB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,OAAO,EAAE,SAAS;IAClB,YAAY,EAAE,cAAc;CACpB,CAAC,CAAC;AAQZ,gBAAgB;AAChB,SAAgB,eAAe,CAAC,KAAiB;IAC/C,KAAK,CAAC,OAAO,CAAC,qBAAY,CAAC,CAAC;IAC5B,KAAK,CAAC,KAAK,EAAE,CAAC;AAChB,CAAC;AAHD,0CAGC;AAWD,+EAA+E;AAC/E,SAAgB,mBAAmB,CACjC,MAAgC,EAChC,YAAyB;IAEzB,IAAI,MAAM,CAAC,WAAW,IAAI,IAAI,EAAE;QAC9B,MAAM,CAAC,WAAW,GAAG,YAAY,CAAC;KACnC;SAAM;QACL,IAAI,YAAY,CAAC,WAAW,CAAC,WAAW,CAAC,MAAM,CAAC,WAAW,CAAC,WAAW,CAAC,EAAE;YACxE,MAAM,CAAC,WAAW,GAAG,YAAY,CAAC;SACnC;KACF;AACH,CAAC;AAXD,kDAWC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sdam/events.js b/2_PAC/node_modules/mongodb/lib/sdam/events.js new file mode 100644 index 00000000..686f82d0 --- /dev/null +++ b/2_PAC/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 ?? {}; + } +} +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/2_PAC/node_modules/mongodb/lib/sdam/events.js.map b/2_PAC/node_modules/mongodb/lib/sdam/events.js.map new file mode 100644 index 00000000..67f5af72 --- /dev/null +++ b/2_PAC/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;IACvC,CAAC;CACF;AAtBD,sEAsBC;AAED;;;;GAIG;AACH,MAAa,kBAAkB;IAM7B,gBAAgB;IAChB,YAAY,UAAkB,EAAE,OAAe;QAC7C,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAXD,gDAWC;AAED;;;;GAIG;AACH,MAAa,iBAAiB;IAM5B,gBAAgB;IAChB,YAAY,UAAkB,EAAE,OAAe;QAC7C,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;CACF;AAXD,8CAWC;AAED;;;;GAIG;AACH,MAAa,+BAA+B;IAQ1C,gBAAgB;IAChB,YACE,UAAkB,EAClB,mBAAwC,EACxC,cAAmC;QAEnC,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,mBAAmB,GAAG,mBAAmB,CAAC;QAC/C,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;IACvC,CAAC;CACF;AAlBD,0EAkBC;AAED;;;;GAIG;AACH,MAAa,oBAAoB;IAI/B,gBAAgB;IAChB,YAAY,UAAkB;QAC5B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;CACF;AARD,oDAQC;AAED;;;;GAIG;AACH,MAAa,mBAAmB;IAI9B,gBAAgB;IAChB,YAAY,UAAkB;QAC5B,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;IAC/B,CAAC;CACF;AARD,kDAQC;AAED;;;;;;GAMG;AACH,MAAa,2BAA2B;IAItC,gBAAgB;IAChB,YAAY,YAAoB;QAC9B,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,CAAC;CACF;AARD,kEAQC;AAED;;;;GAIG;AACH,MAAa,6BAA6B;IAQxC,gBAAgB;IAChB,YAAY,YAAoB,EAAE,QAAgB,EAAE,KAAsB;QACxE,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,KAAK,GAAG,KAAK,IAAI,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/2_PAC/node_modules/mongodb/lib/sdam/monitor.js b/2_PAC/node_modules/mongodb/lib/sdam/monitor.js new file mode 100644 index 00000000..054ea66c --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/monitor.js @@ -0,0 +1,416 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MonitorInterval = 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 { + get connection() { + return this[kConnection]; + } + constructor(server, options) { + 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: 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: '', + 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); + } + connect() { + if (this.s.state !== common_1.STATE_CLOSED) { + return; + } + // start + const heartbeatFrequencyMS = this.options.heartbeatFrequencyMS; + const minHeartbeatFrequencyMS = this.options.minHeartbeatFrequencyMS; + this[kMonitorId] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: minHeartbeatFrequencyMS, + immediate: true + }); + } + requestCheck() { + if (INVALID_REQUEST_CHECK_STATES.has(this.s.state)) { + return; + } + this[kMonitorId]?.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] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: 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) { + 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, callback) { + let start = (0, utils_1.now)(); + monitor.emit(server_1.Server.SERVER_HEARTBEAT_STARTED, new events_1.ServerHeartbeatStartedEvent(monitor.address)); + function failureHandler(err) { + monitor[kConnection]?.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)); + const error = !(err instanceof error_1.MongoError) ? new error_1.MongoError(err) : err; + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + if (error instanceof error_1.MongoNetworkTimeoutError) { + error.addErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections); + } + monitor.emit('resetServer', error); + 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' : constants_1.LEGACY_HELLO_COMMAND]: 1, + ...(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) => { + 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 { + monitor[kRTTPinger]?.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; + 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) => { + if (monitor.s.state === STATE_MONITORING) { + process.nextTick(callback); + return; + } + 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) { + return done(); + } + } + // if the check indicates streaming is supported, immediately reschedule monitoring + if (hello && hello.topologyVersion) { + (0, timers_1.setTimeout)(() => { + if (!isInCloseState(monitor)) { + monitor[kMonitorId]?.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 + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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() { + this.closed = true; + (0, timers_1.clearTimeout)(this[kMonitorId]); + this[kConnection]?.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?.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(); + }); +} +/** + * @internal + */ +class MonitorInterval { + constructor(fn, options = {}) { + this.isExpeditedCallToFnScheduled = false; + this.stopped = false; + this.isExecutionInProgress = false; + this.hasExecutedOnce = false; + this._executeAndReschedule = () => { + if (this.stopped) + return; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + } + this.isExpeditedCallToFnScheduled = false; + this.isExecutionInProgress = true; + this.fn(() => { + this.lastExecutionEnded = (0, utils_1.now)(); + this.isExecutionInProgress = false; + this._reschedule(this.heartbeatFrequencyMS); + }); + }; + this.fn = fn; + this.lastExecutionEnded = -Infinity; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1000; + this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500; + if (options.immediate) { + this._executeAndReschedule(); + } + else { + this._reschedule(undefined); + } + } + wake() { + const currentTime = (0, utils_1.now)(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + // TODO(NODE-4674): Add error handling and logging to the monitor + if (timeSinceLastCall < 0) { + return this._executeAndReschedule(); + } + if (this.isExecutionInProgress) { + return; + } + // debounce multiple calls to wake within the `minInterval` + if (this.isExpeditedCallToFnScheduled) { + return; + } + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeSinceLastCall < this.minHeartbeatFrequencyMS) { + this.isExpeditedCallToFnScheduled = true; + this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall); + return; + } + this._executeAndReschedule(); + } + stop() { + this.stopped = true; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + this.timerId = undefined; + } + this.lastExecutionEnded = -Infinity; + this.isExpeditedCallToFnScheduled = false; + } + toString() { + return JSON.stringify(this); + } + toJSON() { + const currentTime = (0, utils_1.now)(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + return { + timerId: this.timerId != null ? 'set' : 'cleared', + lastCallTime: this.lastExecutionEnded, + isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled, + stopped: this.stopped, + heartbeatFrequencyMS: this.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS, + currentTime, + timeSinceLastCall + }; + } + _reschedule(ms) { + if (this.stopped) + return; + if (this.timerId) { + (0, timers_1.clearTimeout)(this.timerId); + } + this.timerId = (0, timers_1.setTimeout)(this._executeAndReschedule, ms || this.heartbeatFrequencyMS); + } +} +exports.MonitorInterval = MonitorInterval; +//# sourceMappingURL=monitor.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sdam/monitor.js.map b/2_PAC/node_modules/mongodb/lib/sdam/monitor.js.map new file mode 100644 index 00000000..895e1aca --- /dev/null +++ b/2_PAC/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,mCAAkD;AAElD,kCAAyC;AACzC,6CAA0C;AAC1C,mDAAmE;AACnE,4CAAoD;AACpD,oCAAiF;AACjF,gDAAsE;AAEtE,oCAAmG;AACnG,qCAAmE;AACnE,qCAIkB;AAClB,qCAAkC;AAGlC,gBAAgB;AAChB,MAAM,OAAO,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;AACjC,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,WAAW,GAAG,MAAM,CAAC,YAAY,CAAC,CAAC;AACzC,gBAAgB;AAChB,MAAM,kBAAkB,GAAG,MAAM,CAAC,mBAAmB,CAAC,CAAC;AACvD,gBAAgB;AAChB,MAAM,UAAU,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;AACvC,gBAAgB;AAChB,MAAM,cAAc,GAAG,MAAM,CAAC,eAAe,CAAC,CAAC;AAE/C,MAAM,UAAU,GAAG,MAAM,CAAC;AAC1B,MAAM,gBAAgB,GAAG,YAAY,CAAC;AACtC,MAAM,eAAe,GAAG,IAAA,wBAAgB,EAAC;IACvC,CAAC,sBAAa,CAAC,EAAE,CAAC,sBAAa,EAAE,UAAU,EAAE,qBAAY,CAAC;IAC1D,CAAC,qBAAY,CAAC,EAAE,CAAC,qBAAY,EAAE,gBAAgB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,kBAAkB,GAAG,CAAC,QAAQ,CAAC;QACpC,IAAI,CAAC,4BAA4B,GAAG,KAAK,CAAC;IAC5C,CAAC;IAED,QAAQ;QACN,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IAC9B,CAAC;IAED,MAAM;QACJ,MAAM,WAAW,GAAG,IAAA,WAAG,GAAE,CAAC;QAC1B,MAAM,iBAAiB,GAAG,WAAW,GAAG,IAAI,CAAC,kBAAkB,CAAC;QAChE,OAAO;YACL,OAAO,EAAE,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;YACjD,YAAY,EAAE,IAAI,CAAC,kBAAkB;YACrC,yBAAyB,EAAE,IAAI,CAAC,4BAA4B;YAC5D,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,oBAAoB,EAAE,IAAI,CAAC,oBAAoB;YAC/C,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;YACrD,WAAW;YACX,iBAAiB;SAClB,CAAC;IACJ,CAAC;IAEO,WAAW,CAAC,EAAW;QAC7B,IAAI,IAAI,CAAC,OAAO;YAAE,OAAO;QACzB,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,IAAA,qBAAY,EAAC,IAAI,CAAC,OAAO,CAAC,CAAC;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,IAAA,mBAAU,EAAC,IAAI,CAAC,qBAAqB,EAAE,EAAE,IAAI,IAAI,CAAC,oBAAoB,CAAC,CAAC;IACzF,CAAC;CAiBF;AA7GD,0CA6GC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sdam/server.js b/2_PAC/node_modules/mongodb/lib/sdam/server.js new file mode 100644 index 00000000..a8564ef7 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/server.js @@ -0,0 +1,367 @@ +"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 errors_1 = require("../cmap/errors"); +const constants_1 = require("../constants"); +const error_1 = require("../error"); +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, + state: common_1.STATE_CLOSED, + topology, + pool: new connection_pool_1.ConnectionPool(this, 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('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() { + 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) { + this[kMonitor]?.connect(); + } + else { + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Server.CONNECT, this); + } + } + /** Destroy the server connection */ + destroy(options, callback) { + 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) { + this[kMonitor]?.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() { + if (!this.loadBalanced) { + this[kMonitor]?.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; + } + 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; + if (!err) { + return cb(new error_1.MongoRuntimeError('Failed to create connection without error')); + } + if (!(err instanceof errors_1.PoolClearedError)) { + this.handleError(err); + } + return cb(err); + } + conn.command(ns, cmd, finalOptions, makeOperationHandler(this, conn, cmd, finalOptions, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + })); + }, callback); + } + /** + * Handle SDAM error + * @internal + */ + handleError(error, connection) { + if (!(error instanceof error_1.MongoError)) { + return; + } + const isStaleError = error.connectionGeneration && error.connectionGeneration < this.s.pool.generation; + if (isStaleError) { + return; + } + const isNetworkNonTimeoutError = error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError); + const isNetworkTimeoutBeforeHandshakeError = (0, error_1.isNetworkErrorBeforeHandshake)(error); + const isAuthHandshakeError = error.hasErrorLabel(error_1.MongoErrorLabel.HandshakeError); + if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + if (!this.loadBalanced) { + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + markServerUnknown(this, error); + } + else if (connection) { + this.s.pool.clear({ serviceId: connection.serviceId }); + } + } + else { + if ((0, error_1.isSDAMUnrecoverableError)(error)) { + if (shouldHandleStateChangeError(this, error)) { + const shouldClearPool = (0, utils_1.maxWireVersion)(this) <= 7 || (0, error_1.isNodeShuttingDownError)(error); + if (this.loadBalanced && connection && shouldClearPool) { + this.s.pool.clear({ serviceId: connection.serviceId }); + } + if (!this.loadBalanced) { + if (shouldClearPool) { + error.addErrorLabel(error_1.MongoErrorLabel.ResetPool); + } + markServerUnknown(this, error); + process.nextTick(() => this.requestCheck()); + } + } + } + } + } +} +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) { + // Load balancer servers can never be marked unknown. + if (server.loadBalanced) { + return; + } + if (error instanceof error_1.MongoNetworkError && !(error instanceof error_1.MongoNetworkTimeoutError)) { + server[kMonitor]?.reset(); + } + server.emit(Server.DESCRIPTION_RECEIVED, new server_description_1.ServerDescription(server.description.hostAddress, undefined, { error })); +} +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?.session; + return function handleOperationResult(error, result) { + // We should not swallow an error if it is present. + if (error == null && result != null) { + return callback(undefined, result); + } + if (options != null && 'noResponse' in options && options.noResponse === true) { + return callback(undefined, null); + } + 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); + } + } + 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 (session && + session.isPinned && + error.hasErrorLabel(error_1.MongoErrorLabel.TransientTransactionError)) { + session.unpin({ force: true }); + } + server.handleError(error, connection); + return callback(error); + }; +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sdam/server.js.map b/2_PAC/node_modules/mongodb/lib/sdam/server.js.map new file mode 100644 index 00000000..f4c17e6d --- /dev/null +++ b/2_PAC/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,mDAAgF;AAChF,6DAIiC;AACjC,2CAAkD;AAClD,4CAWsB;AAEtB,oCAekB;AAElB,gDAAmD;AAGnD,kDAAuD;AACvD,oCAOkB;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;AAqCnC,gBAAgB;AAChB,MAAa,MAAO,SAAQ,+BAA+B;IAsB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I,EAAE,CAAC,CAAC;SAChC;QAED,MAAM,CAAC,WAAW,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;QAEtC,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC,CAAC;AACJ,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sdam/server_description.js b/2_PAC/node_modules/mongodb/lib/sdam/server_description.js new file mode 100644 index 00000000..1cf4da37 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/server_description.js @@ -0,0 +1,189 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.compareTopologyVersion = exports.parseServerType = exports.ServerDescription = void 0; +const bson_1 = require("../bson"); +const error_1 = require("../error"); +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 = {}) { + if (address == null || address === '') { + throw new error_1.MongoRuntimeError('ServerDescription must be provided with a non-empty address'); + } + this.address = + typeof address === 'string' + ? utils_1.HostAddress.fromString(address).toString() // Use HostAddress to normalize + : address.toString(); + this.type = parseServerType(hello, options); + this.hosts = hello?.hosts?.map((host) => host.toLowerCase()) ?? []; + this.passives = hello?.passives?.map((host) => host.toLowerCase()) ?? []; + this.arbiters = hello?.arbiters?.map((host) => host.toLowerCase()) ?? []; + this.tags = hello?.tags ?? {}; + this.minWireVersion = hello?.minWireVersion ?? 0; + this.maxWireVersion = hello?.maxWireVersion ?? 0; + this.roundTripTime = options?.roundTripTime ?? -1; + this.lastUpdateTime = (0, utils_1.now)(); + this.lastWriteDate = hello?.lastWrite?.lastWriteDate ?? 0; + this.error = options.error ?? null; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this.topologyVersion = this.error?.topologyVersion ?? hello?.topologyVersion ?? null; + this.setName = hello?.setName ?? null; + this.setVersion = hello?.setVersion ?? null; + this.electionId = hello?.electionId ?? null; + this.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes ?? null; + this.primary = hello?.primary ?? null; + this.me = hello?.me?.toLowerCase() ?? null; + this.$clusterTime = hello?.$clusterTime ?? null; + } + get hostAddress() { + return utils_1.HostAddress.fromString(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) { + // Despite using the comparator that would determine a nullish topologyVersion as greater than + // for equality we should only always perform direct equality comparison + const topologyVersionsEqual = this.topologyVersion === other?.topologyVersion || + compareTopologyVersion(this.topologyVersion, other?.topologyVersion) === 0; + const electionIdsEqual = this.electionId != null && other?.electionId != null + ? (0, utils_1.compareObjectId)(this.electionId, other.electionId) === 0 + : 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?.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. + * + * 1. If the response topologyVersion is unset or the ServerDescription's + * topologyVersion is null, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is not equal to the + * ServerDescription's, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is equal to the + * ServerDescription's, the client MUST use the counter field to determine + * which topologyVersion is more recent. + * + * ```ts + * currentTv < newTv === -1 + * currentTv === newTv === 0 + * currentTv > newTv === 1 + * ``` + */ +function compareTopologyVersion(currentTv, newTv) { + if (currentTv == null || newTv == null) { + return -1; + } + if (!currentTv.processId.equals(newTv.processId)) { + return -1; + } + // TODO(NODE-2674): Preserve int64 sent from MongoDB + const currentCounter = bson_1.Long.isLong(currentTv.counter) + ? currentTv.counter + : bson_1.Long.fromNumber(currentTv.counter); + const newCounter = bson_1.Long.isLong(newTv.counter) ? newTv.counter : bson_1.Long.fromNumber(newTv.counter); + return currentCounter.compare(newCounter); +} +exports.compareTopologyVersion = compareTopologyVersion; +//# sourceMappingURL=server_description.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sdam/server_description.js.map b/2_PAC/node_modules/mongodb/lib/sdam/server_description.js.map new file mode 100644 index 00000000..7e851737 --- /dev/null +++ b/2_PAC/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;AACnD,oCAA2E;AAC3E,oCAAiG;AAEjG,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;AAuBH;;;;;GAKG;AACH,MAAa,iBAAiB;IAwB5B;;;;;;OAMG;IACH,YACE,OAA6B,EAC7B,KAAgB,EAChB,UAAoC,EAAE;QAEtC,IAAI,OAAO,IAAI,IAAI,IAAI,OAAO,KAAK,EAAE,EAAE;YACrC,MAAM,IAAI,yBAAiB,CAAC,6DAA6D,CAAC,CAAC;SAC5F;QAED,IAAI,CAAC,OAAO;YACV,OAAO,OAAO,KAAK,QAAQ;gBACzB,CAAC,CAAC,mBAAW,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC,+BAA+B;gBAC5E,CAAC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ACpC,QAAQ,CAAC,KAAK,CAAC,CAAC,GAAW,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,IAAI,CAAC,GAAG,CAAC,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,SAAgB,sBAAsB,CACpC,SAAkC,EAClC,KAA8B;IAE9B,IAAI,SAAS,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI,EAAE;QACtC,OAAO,CAAC,CAAC,CAAC;KACX;IAED,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE;QAChD,OAAO,CAAC,CAAC,CAAC;KACX;IAED,oDAAoD;IACpD,MAAM,cAAc,GAAG,WAAI,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,CAAC;QACnD,CAAC,CAAC,SAAS,CAAC,OAAO;QACnB,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,UAAU,GAAG,WAAI,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,WAAI,CAAC,UAAU,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAE/F,OAAO,cAAc,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;AAC5C,CAAC;AAnBD,wDAmBC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sdam/server_selection.js b/2_PAC/node_modules/mongodb/lib/sdam/server_selection.js new file mode 100644 index 00000000..36e28162 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/server_selection.js @@ -0,0 +1,226 @@ +"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) => { + 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 === 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) => { + 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, 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/2_PAC/node_modules/mongodb/lib/sdam/server_selection.js.map b/2_PAC/node_modules/mongodb/lib/sdam/server_selection.js.map new file mode 100644 index 00000000..50c687dc --- /dev/null +++ b/2_PAC/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,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CACvD,CAAC;AACN,CAAC;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mB,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/2_PAC/node_modules/mongodb/lib/sdam/srv_polling.js b/2_PAC/node_modules/mongodb/lib/sdam/srv_polling.js new file mode 100644 index 00000000..8714ad1e --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/srv_polling.js @@ -0,0 +1,117 @@ +"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 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) { + super(); + if (!options || !options.srvHost) { + throw new error_1.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.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) { + (0, timers_1.clearTimeout)(this._timeout); + this.generation += 1; + this._timeout = undefined; + } + } + // TODO(NODE-4994): implement new logging logic for SrvPoller failures + schedule() { + if (this._timeout) { + (0, timers_1.clearTimeout)(this._timeout); + } + this._timeout = (0, timers_1.setTimeout)(() => { + this._poll().catch(() => null); + }, this.intervalMS); + } + success(srvRecords) { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + failure() { + this.haMode = true; + this.schedule(); + } + async _poll() { + const generation = this.generation; + let srvRecords; + try { + srvRecords = await dns.promises.resolveSrv(this.srvAddress); + } + catch (dnsError) { + this.failure(); + return; + } + if (generation !== this.generation) { + return; + } + const finalAddresses = []; + for (const record of srvRecords) { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } + } + if (!finalAddresses.length) { + this.failure(); + 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/2_PAC/node_modules/mongodb/lib/sdam/srv_polling.js.map b/2_PAC/node_modules/mongodb/lib/sdam/srv_polling.js.map new file mode 100644 index 00000000..ab1714c1 --- /dev/null +++ b/2_PAC/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,mCAAkD;AAElD,oCAA6C;AAC7C,gDAAmD;AACnD,oCAAuC;AAEvC;;;;;;;GAOG;AACH,SAAS,mBAAmB,CAAC,UAAkB,EAAE,YAAoB;IACnE,MAAM,KAAK,GAAG,QAAQ,CAAC;IACvB,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC;IAChD,MAAM,MAAM,GAAG,IAAI,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC;IACrD,OAAO,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC9B,CAAC;AAED;;;GAGG;AACH,MAAa,eAAe;IAE1B,YAAY,UAA2B;Q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R;QAED,MAAM,cAAc,GAAoB,EAAE,CAAC;QAC3C,KAAK,MAAM,MAAM,IAAI,UAAU,EAAE;YAC/B,IAAI,mBAAmB,CAAC,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE;gBAClD,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;aAC7B;SACF;QAED,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE;YAC1B,IAAI,CAAC,OAAO,EAAE,CAAC;YACf,OAAO;SACR;QAED,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IAC/B,CAAC;;AAxGH,8BAyGC;AA/FC,aAAa;AACG,8BAAoB,GAAG,oBAA6B,CAAC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sdam/topology.js b/2_PAC/node_modules/mongodb/lib/sdam/topology.js new file mode 100644 index 00000000..06c99e4c --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/topology.js @@ -0,0 +1,643 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerCapabilities = exports.Topology = void 0; +const timers_1 = require("timers"); +const util_1 = require("util"); +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) { + super(); + this.selectServerAsync = (0, util_1.promisify)((selector, options, callback) => this.selectServer(selector, options, callback)); + // Options should only be undefined in tests, MongoClient will always have defined options + options = 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 utils_1.List(); + 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?.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 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) { + const previousType = event.previousDescription.type; + const newType = event.newDescription.type; + const transitionToSharded = previousType !== common_1.TopologyType.Sharded && newType === common_1.TopologyType.Sharded; + const srvListeners = this.s.srvPoller?.listeners(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY); + const listeningToSrvPolling = !!srvListeners?.includes(this.s.detectSrvRecords); + if (transitionToSharded && !listeningToSrvPolling) { + this.s.srvPoller?.on(srv_polling_1.SrvPoller.SRV_RECORD_DISCOVERY, this.s.detectSrvRecords); + this.s.srvPoller?.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()); + } + connect(options, callback) { + if (typeof options === 'function') + (callback = options), (options = {}); + options = 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 = options.readPreference ?? 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?.(undefined, this); + }); + return; + } + stateTransition(this, common_1.STATE_CONNECTED); + this.emit(Topology.OPEN, this); + this.emit(Topology.CONNECT, this); + callback?.(undefined, this); + }); + } + close(options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } + if (typeof options === 'boolean') { + options = { force: options }; + } + options = options ?? {}; + if (this.s.state === common_1.STATE_CLOSED || this.s.state === common_1.STATE_CLOSING) { + return 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?.()); + } + /** + * 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; + } + // 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 ?? {}; + 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?.directConnection) { + return common_1.TopologyType.Single; + } + if (options?.replicaSet) { + return common_1.TopologyType.ReplicaSetNoPrimary; + } + if (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; + if (incomingServerDescription.error instanceof error_1.MongoError && + incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.ResetPool)) { + const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel(error_1.MongoErrorLabel.InterruptInUseConnections); + server.s.pool.clear({ interruptInUseConnections }); + } + else if (incomingServerDescription.error == null) { + const newTopologyType = topology.s.description.type; + const shouldMarkPoolReady = incomingServerDescription.isDataBearing || + (incomingServerDescription.type !== common_1.ServerType.Unknown && + newTopologyType === common_1.TopologyType.Single); + if (shouldMarkPoolReady) { + server.s.pool.ready(); + } + } + } + } + // 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) { + (0, timers_1.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) { + (0, timers_1.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 { + const descriptions = (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) { + (0, timers_1.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?.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/2_PAC/node_modules/mongodb/lib/sdam/topology.js.map b/2_PAC/node_modules/mongodb/lib/sdam/topology.js.map new file mode 100644 index 00000000..42cd9191 --- /dev/null +++ b/2_PAC/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,mCAAkD;AAClD,+BAAiC;AAMjC,4DAAsE;AACtE,4CAcsB;AACtB,oCAQkB;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,MAA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C;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/2_PAC/node_modules/mongodb/lib/sdam/topology_description.js b/2_PAC/node_modules/mongodb/lib/sdam/topology_description.js new file mode 100644 index 00000000..6ee1b0c2 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sdam/topology_description.js @@ -0,0 +1,360 @@ +"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 = null, setName = null, maxSetVersion = null, maxElectionId = null, commonWireVersion = null, options = null) { + options = options ?? {}; + this.type = topologyType ?? common_1.TopologyType.Unknown; + this.servers = serverDescriptions ?? new Map(); + this.stale = false; + this.compatible = true; + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 0; + this.localThresholdMS = options.localThresholdMS ?? 15; + this.setName = setName ?? null; + this.maxElectionId = maxElectionId ?? null; + this.maxSetVersion = maxSetVersion ?? null; + this.commonWireVersion = commonWireVersion ?? 0; + // 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 = null; + 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 = null; + 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; + 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); + } + } + if (typeof serverDescription.setName === 'string' && + typeof setName === 'string' && + serverDescription.setName !== setName) { + if (topologyType === common_1.TopologyType.Single) { + // "Single" Topology with setName mismatch is direct connection usage, mark unknown do not remove + serverDescription = new server_description_1.ServerDescription(address); + } + else { + serverDescriptions.delete(address); + } + } + // 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 null; + } + /** + * 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; + } +} +function updateRsFromPrimary(serverDescriptions, serverDescription, setName = null, maxSetVersion = null, maxElectionId = null) { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + if (serverDescription.maxWireVersion >= 17) { + const electionIdComparison = (0, utils_1.compareObjectId)(maxElectionId, serverDescription.electionId); + const maxElectionIdIsEqual = electionIdComparison === 0; + const maxElectionIdIsLess = electionIdComparison === -1; + const maxSetVersionIsLessOrEqual = (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1); + if (maxElectionIdIsLess || (maxElectionIdIsEqual && maxSetVersionIsLessOrEqual)) { + // The reported electionId was greater + // or the electionId was equal and reported setVersion was greater + // Always update both values, they are a tuple + maxElectionId = serverDescription.electionId; + maxSetVersion = serverDescription.setVersion; + } + else { + // Stale primary + // replace serverDescription with a default ServerDescription of type "Unknown" + serverDescriptions.set(serverDescription.address, new server_description_1.ServerDescription(serverDescription.address)); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } + else { + const electionId = serverDescription.electionId ? serverDescription.electionId : null; + if (serverDescription.setVersion && electionId) { + if (maxSetVersion && maxElectionId) { + if (maxSetVersion > serverDescription.setVersion || + (0, utils_1.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 = null) { + 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 = null) { + 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/2_PAC/node_modules/mongodb/lib/sdam/topology_description.js.map b/2_PAC/node_modules/mongodb/lib/sdam/topology_description.js.map new file mode 100644 index 00000000..c11143c5 --- /dev/null +++ b/2_PAC/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,oCAA+D;AAC/D,oCAAoD;AACpD,qCAAoD;AACpD,6DAAyD;AAGzD,4CAA4C;AAC5C,MAAM,4BAA4B,GAAG,cAAc,CAAC,4BAA4B,CAAC;AACjF,MAAM,4BAA4B,GAAG,cAAc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H,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/2_PAC/node_modules/mongodb/lib/sessions.js b/2_PAC/node_modules/mongodb/lib/sessions.js new file mode 100644 index 00000000..4fcb6129 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sessions.js @@ -0,0 +1,737 @@ +"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 util_1 = require("util"); +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 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 ?? {}; + 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; + const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true; + this.supports = { + // if we can enable causal consistency, do so by default + causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue + }; + 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() { + return this[kServerSession]?.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() { + return this.client.topology?.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; + } + /** + * Ends this session on the server + * + * @param options - Optional settings. Currently reserved for future use + */ + async endSession(options) { + try { + if (this.inTransaction()) { + await this.abortTransaction(); + } + if (!this.hasEnded) { + 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); + } + } + catch { + // spec indicates that we should ignore all errors for `endSessions` + } + finally { + maybeClearPinnedConnection(this, { force: true, ...options }); + } + } + /** + * 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) { + 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 || + clusterTime.signature.hash?._bsontype !== 'Binary' || + (typeof clusterTime.signature.keyId !== 'number' && + clusterTime.signature.keyId?._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 utils_1.ByteUtils.equals(this.id.id.buffer, 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) { + if (this[kSnapshotEnabled]) { + throw new error_1.MongoCompatibilityError('Transactions are not supported in 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: 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(transactions_1.TxnState.STARTING_TRANSACTION); + } + /** + * Commits the currently active transaction in this session. + */ + async commitTransaction() { + return endTransactionAsync(this, 'commitTransaction'); + } + /** + * Aborts the currently active transaction in this session. + */ + async abortTransaction() { + return endTransactionAsync(this, 'abortTransaction'); + } + /** + * 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 + */ + async 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?.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?.error == null || 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?.forceClear) { + loadBalancer.s.pool.clear({ serviceId: 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) { + 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); + }); +} +const endTransactionAsync = (0, util_1.promisify)(endTransaction); +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 = new utils_1.List(); + } + /** + * 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() { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + let session = 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) { + const sessionTimeoutMinutes = this.client.topology?.logicalSessionTimeoutMinutes ?? 10; + if (this.client.topology?.loadBalanced && !sessionTimeoutMinutes) { + this.sessions.unshift(session); + } + if (!sessionTimeoutMinutes) { + return; + } + this.sessions.prune(session => session.hasTimedOut(sessionTimeoutMinutes)); + 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) { + 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 (options.writeConcern?.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; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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 || 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; +} +exports.applySession = applySession; +function updateSessionFromResponse(session, document) { + 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?.[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; + } + } +} +exports.updateSessionFromResponse = updateSessionFromResponse; +//# sourceMappingURL=sessions.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/sessions.js.map b/2_PAC/node_modules/mongodb/lib/sessions.js.map new file mode 100644 index 00000000..522205d3 --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/sessions.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sessions.js","sourceRoot":"","sources":["../src/sessions.ts"],"names":[],"mappings":";;;;AAAA,+BAAiC;AAEjC,iCAA2D;AAE3D,4CAAuD;AACvD,wDAAwD;AACxD,2CAA+C;AAE/C,mCAciB;AAEjB,+CAAkD;AAClD,sEAAkE;AAClE,0DAAoE;AACpE,iDAAkD;AAClD,uDAAmD;AACnD,0CAA+E;AAC/E,iDAAiG;AACjG,mCAUiB;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,gBAA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,EAAE,QAAQ,CAAC,YAAY,CAAC,CAAC;KACrD;IAED,IAAI,QAAQ,CAAC,aAAa,IAAI,OAAO,IAAI,OAAO,CAAC,QAAQ,CAAC,iBAAiB,EAAE;QAC3E,OAAO,CAAC,oBAAoB,CAAC,QAAQ,CAAC,aAAa,CAAC,CAAC;KACtD;IAED,IAAI,QAAQ,CAAC,aAAa,IAAI,OAAO,IAAI,OAAO,CAAC,aAAa,EAAE,EAAE;QAChE,OAAO,CAAC,WAAW,CAAC,cAAc,GAAG,QAAQ,CAAC,aAAa,CAAC;KAC7D;IAED,IAAI,OAAO,EAAE,CAAC,gBAAgB,CAAC,IAAI,OAAO,CAAC,aAAa,CAAC,IAAI,IAAI,EAAE;QACjE,iEAAiE;QACjE,4CAA4C;QAC5C,MAAM,aAAa,GAAG,QAAQ,CAAC,MAAM,EAAE,aAAa,IAAI,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/2_PAC/node_modules/mongodb/lib/sort.js b/2_PAC/node_modules/mongodb/lib/sort.js new file mode 100644 index 00000000..c04b6b54 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/lib/sort.js.map b/2_PAC/node_modules/mongodb/lib/sort.js.map new file mode 100644 index 00000000..4072af4c --- /dev/null +++ b/2_PAC/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,YAAi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,EAAE,CAAC;QAClE,GAAG,CAAC,EAAE;QACN,gBAAgB,CAAC,CAAC,CAAC;KACpB,CAAC,CAAC;IACH,OAAO,IAAI,GAAG,CAAC,WAAW,CAAC,CAAC;AAC9B,CAAC;AAED,iFAAiF;AACjF,SAAgB,UAAU,CACxB,IAAsB,EACtB,SAAyB;IAEzB,IAAI,IAAI,IAAI,IAAI;QAAE,OAAO,SAAS,CAAC;IACnC,IAAI,OAAO,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/2_PAC/node_modules/mongodb/lib/transactions.js b/2_PAC/node_modules/mongodb/lib/transactions.js new file mode 100644 index 00000000..a4235b07 --- /dev/null +++ b/2_PAC/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 ?? {}; + 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/2_PAC/node_modules/mongodb/lib/transactions.js.map b/2_PAC/node_modules/mongodb/lib/transactions.js.map new file mode 100644 index 00000000..8a6982e2 --- /dev/null +++ b/2_PAC/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;AAE9D,uDAAmD;AAEnD,mDAA+C;AAE/C,gBAAgB;AACH,QAAA,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC;IACpC,cAAc,EAAE,gBAAgB;IAChC,oBAAoB,EAAE,sBAAsB;IAC5C,uBAAuB,EAAE,yBAAyB;IAClD,qBAAqB,EAAE,uBAAuB;IAC9C,2BAA2B,EAAE,6BAA6B;IAC1D,mBAAmB,EAAE,qBAAqB;CAClC,CAAC,CAAC;AAKZ,MAAM,YAAY,GAAwC;IACxD,CAAC,gBAAQ,CAAC,cAAc,CAAC,EAAE,CAAC,gBAAQ,CAAC,cAAc,EAAE,gBAAQ,CAAC,oBAAoB,CAAC;IACnF,CAAC,gBAAQ,CAAC,oBAAoB,CAAC,EAAE;QAC/B,gBAAQ,CAAC,uBAAuB;QAChC,gBAAQ,CAAC,qBAAqB;QAC9B,gBAAQ,CAAC,2BAA2B;QACpC,gBAAQ,CAAC,mBAAmB;KAC7B;IACD,CAAC,gBAAQ,CAAC,uBAAuB,CAAC,EAAE;QAClC,gBAAQ,CAAC,uBAAuB;QAChC,gBAAQ,CAAC,qBAAqB;QAC9B,gBAAQ,CAAC,mBAAmB;KAC7B;IACD,CAAC,gBAAQ,CAAC,qBAAqB,CAAC,EAAE;QAChC,gBAAQ,CAAC,qBAAqB;Q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IAAI,CAAC,WAAW,EAAE,CAAC;aACpB;YACD,OAAO;SACR;QAED,MAAM,IAAI,yBAAiB,CACzB,4CAA4C,IAAI,CAAC,KAAK,SAAS,SAAS,GAAG,CAC5E,CAAC;IACJ,CAAC;IAED,gBAAgB;IAChB,SAAS,CAAC,MAAc;QACtB,IAAI,IAAI,CAAC,QAAQ,EAAE;YACjB,IAAI,CAAC,aAAa,GAAG,MAAM,CAAC;SAC7B;IACH,CAAC;IAED,gBAAgB;IAChB,WAAW;QACT,IAAI,CAAC,aAAa,GAAG,SAAS,CAAC;IACjC,CAAC;CACF;AAxGD,kCAwGC;AAED,SAAgB,oBAAoB,CAAC,OAAiB;IACpD,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,iBAAiB,IAAI,OAAO,CAAC,gBAAgB,CAAC,CAAC;AACnE,CAAC;AAFD,oDAEC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/utils.js b/2_PAC/node_modules/mongodb/lib/utils.js new file mode 100644 index 00000000..9a2d657d --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/utils.js @@ -0,0 +1,1055 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseUnsignedInteger = exports.parseInteger = exports.compareObjectId = exports.getMongoDBClientEncryption = exports.commandSupportsReadConcern = exports.shuffle = exports.supportsRetryableWrites = exports.enumToString = exports.emitWarningOnce = exports.emitWarning = exports.MONGODB_WARNING_CODE = exports.DEFAULT_PK_FACTORY = exports.HostAddress = exports.BufferPool = exports.List = exports.deepCopy = exports.isRecord = exports.setDifference = exports.isHello = exports.isSuperset = exports.resolveOptions = exports.hasAtomicOperators = exports.calculateDurationInMs = exports.now = exports.makeClientMetadata = exports.makeStateMachine = exports.errorStrictEqual = exports.arrayStrictEqual = exports.eachAsyncSeries = exports.eachAsync = exports.maxWireVersion = exports.uuidV4 = exports.databaseNamespace = exports.maybeCallback = exports.makeCounter = exports.MongoDBNamespace = exports.ns = exports.getTopology = exports.decorateWithExplain = exports.decorateWithReadConcern = exports.decorateWithCollation = exports.isPromiseLike = exports.applyWriteConcern = exports.applyRetryableWrites = exports.filterOptions = exports.mergeOptions = exports.isObject = exports.normalizeHintField = exports.checkCollectionName = exports.ByteUtils = void 0; +const crypto = require("crypto"); +const os = require("os"); +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 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.ByteUtils = { + toLocalBufferType(buffer) { + return Buffer.isBuffer(buffer) + ? buffer + : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + }, + equals(seqA, seqB) { + return exports.ByteUtils.toLocalBufferType(seqA).equals(seqB); + }, + compare(seqA, seqB) { + return exports.ByteUtils.toLocalBufferType(seqA).compare(seqB); + }, + toBase64(uint8array) { + return exports.ByteUtils.toLocalBufferType(uint8array).toString('base64'); + } +}; +/** + * 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; +/** + * Ensure Hint field is in a shape we expect: + * - object of index names mapping to 1 or -1 + * - just an index name + * @internal + */ +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; +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) { + if (db && db.s.options?.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 ?? {}; + 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 resolution type of the possible promise + * @param value - An object that could be a promise + * @returns true if the provided value is a Promise + */ +function isPromiseLike(value) { + return !!value && typeof value.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; +/** + * 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 + */ +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; +/** @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 === '' ? undefined : collection; + } + toString() { + return this.collection ? `${this.db}.${this.collection}` : this.db; + } + withCollection(collection) { + return new MongoDBNamespace(this.db, collection); + } + static fromString(namespace) { + if (typeof namespace !== 'string' || namespace === '') { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new error_1.MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + const [db, ...collectionParts] = namespace.split('.'); + const collection = collectionParts.join('.'); + return new MongoDBNamespace(db, collection === '' ? undefined : collection); + } +} +exports.MongoDBNamespace = MongoDBNamespace; +/** @internal */ +function* makeCounter(seed = 0) { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} +exports.makeCounter = makeCounter; +function maybeCallback(promiseFn, callback) { + const promise = promiseFn(); + if (callback == null) { + return promise; + } + promise.then(result => callback(undefined, result), error => callback(error)); + return; +} +exports.maybeCallback = maybeCallback; +/** @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 available 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; +/** + * 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 ?? {}; + 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; +/** @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) { + 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?.session; + if (!session?.inTransaction()) { + const readConcern = read_concern_1.ReadConcern.fromOptions(options) ?? parent?.readConcern; + if (readConcern) { + result.readConcern = readConcern; + } + const writeConcern = write_concern_1.WriteConcern.fromOptions(options) ?? parent?.writeConcern; + if (writeConcern) { + result.writeConcern = writeConcern; + } + } + const readPreference = read_preference_1.ReadPreference.fromOptions(options) ?? 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; +/** + * A sequential list of items in a circularly linked list + * @remarks + * The head node is special, it is always defined and has a value of null. + * It is never "included" in the list, in that, it is not returned by pop/shift or yielded by the iterator. + * The circular linkage and always defined head node are to reduce checks for null next/prev references to zero. + * New nodes are declared as object literals with keys always in the same order: next, prev, value. + * @internal + */ +class List { + get length() { + return this.count; + } + get [Symbol.toStringTag]() { + return 'List'; + } + constructor() { + this.count = 0; + // this is carefully crafted: + // declaring a complete and consistently key ordered + // object is beneficial to the runtime optimizations + this.head = { + next: null, + prev: null, + value: null + }; + this.head.next = this.head; + this.head.prev = this.head; + } + toArray() { + return Array.from(this); + } + toString() { + return `head <=> ${this.toArray().join(' <=> ')} <=> head`; + } + *[Symbol.iterator]() { + for (const node of this.nodes()) { + yield node.value; + } + } + *nodes() { + let ptr = this.head.next; + while (ptr !== this.head) { + // Save next before yielding so that we make removing within iteration safe + const { next } = ptr; + yield ptr; + ptr = next; + } + } + /** Insert at end of list */ + push(value) { + this.count += 1; + const newNode = { + next: this.head, + prev: this.head.prev, + value + }; + this.head.prev.next = newNode; + this.head.prev = newNode; + } + /** Inserts every item inside an iterable instead of the iterable itself */ + pushMany(iterable) { + for (const value of iterable) { + this.push(value); + } + } + /** Insert at front of list */ + unshift(value) { + this.count += 1; + const newNode = { + next: this.head.next, + prev: this.head, + value + }; + this.head.next.prev = newNode; + this.head.next = newNode; + } + remove(node) { + if (node === this.head || this.length === 0) { + return null; + } + this.count -= 1; + const prevNode = node.prev; + const nextNode = node.next; + prevNode.next = nextNode; + nextNode.prev = prevNode; + return node.value; + } + /** Removes the first node at the front of the list */ + shift() { + return this.remove(this.head.next); + } + /** Removes the last node at the end of the list */ + pop() { + return this.remove(this.head.prev); + } + /** Iterates through the list and removes nodes where filter returns true */ + prune(filter) { + for (const node of this.nodes()) { + if (filter(node.value)) { + this.remove(node); + } + } + } + clear() { + this.count = 0; + this.head.next = this.head; + this.head.prev = this.head; + } + /** Returns the first item in the list, does not remove */ + first() { + // If the list is empty, value will be the head's null + return this.head.next.value; + } + /** Returns the last item in the list, does not remove */ + last() { + // If the list is empty, value will be the head's null + return this.head.prev.value; + } +} +exports.List = List; +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +class BufferPool { + constructor() { + this.buffers = new List(); + this.totalByteLength = 0; + } + get length() { + return this.totalByteLength; + } + /** Adds a buffer to the internal buffer pool list */ + append(buffer) { + this.buffers.push(buffer); + this.totalByteLength += buffer.length; + } + /** + * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes, + * otherwise return null. Size can be negative, caller should error check. + */ + getInt32() { + if (this.totalByteLength < 4) { + return null; + } + const firstBuffer = this.buffers.first(); + if (firstBuffer != null && firstBuffer.byteLength >= 4) { + return firstBuffer.readInt32LE(0); + } + // Unlikely case: an int32 is split across buffers. + // Use read and put the returned buffer back on top + const top4Bytes = this.read(4); + const value = top4Bytes.readInt32LE(0); + // Put it back. + this.totalByteLength += 4; + this.buffers.unshift(top4Bytes); + return value; + } + /** Reads the requested number of bytes, optionally consuming them */ + read(size) { + if (typeof size !== 'number' || size < 0) { + throw new error_1.MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + // oversized request returns empty buffer + if (size > this.totalByteLength) { + return Buffer.alloc(0); + } + // We know we have enough, we just don't know how it is spread across chunks + // TODO(NODE-4732): alloc API should change based on raw option + const result = Buffer.allocUnsafe(size); + for (let bytesRead = 0; bytesRead < size;) { + const buffer = this.buffers.shift(); + if (buffer == null) { + break; + } + const bytesRemaining = size - bytesRead; + const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); + const bytes = buffer.subarray(0, bytesReadable); + result.set(bytes, bytesRead); + bytesRead += bytesReadable; + this.totalByteLength -= bytesReadable; + if (bytesReadable < buffer.byteLength) { + this.buffers.unshift(buffer.subarray(bytesReadable)); + } + } + return result; + } +} +exports.BufferPool = BufferPool; +/** @public */ +class HostAddress { + constructor(hostString) { + this.host = undefined; + this.port = undefined; + this.socketPath = undefined; + this.isIPv6 = false; + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + if (escapedHost.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(escapedHost); + return; + } + const urlString = `iLoveJS://${escapedHost}`; + let url; + try { + url = new url_1.URL(urlString); + } + catch (urlError) { + const runtimeError = new error_1.MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); + runtimeError.cause = urlError; + throw runtimeError; + } + const hostname = url.hostname; + const port = url.port; + 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'); + } + Object.freeze(this); + } + [Symbol.for('nodejs.util.inspect.custom')]() { + return this.inspect(); + } + inspect() { + return `new HostAddress('${this.toString()}')`; + } + toString() { + if (typeof this.host === 'string') { + if (this.isIPv6) { + 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 + * ```ts + * 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; +/** + * 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(NODE-4936): read concern eligibility for commands 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. */ +function getMongoDBClientEncryption() { + let mongodbClientEncryption = null; + // 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) { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require(process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE); + } + catch { + // ignore + } + } + else { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require('mongodb-client-encryption'); + } + catch { + // ignore + } + } + return mongodbClientEncryption; +} +exports.getMongoDBClientEncryption = getMongoDBClientEncryption; +/** + * Compare objectIds. `null` is always less + * - `+1 = oid1 is greater than oid2` + * - `-1 = oid1 is less than oid2` + * - `+0 = oid1 is equal oid2` + */ +function compareObjectId(oid1, oid2) { + if (oid1 == null && oid2 == null) { + return 0; + } + if (oid1 == null) { + return -1; + } + if (oid2 == null) { + return 1; + } + return exports.ByteUtils.compare(oid1.id, oid2.id); +} +exports.compareObjectId = compareObjectId; +function parseInteger(value) { + if (typeof value === 'number') + return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + return Number.isNaN(parsedValue) ? null : parsedValue; +} +exports.parseInteger = parseInteger; +function parseUnsignedInteger(value) { + const parsedInt = parseInteger(value); + return parsedInt != null && parsedInt >= 0 ? parsedInt : null; +} +exports.parseUnsignedInteger = parseUnsignedInteger; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/utils.js.map b/2_PAC/node_modules/mongodb/lib/utils.js.map new file mode 100644 index 00000000..0447c4df --- /dev/null +++ b/2_PAC/node_modules/mongodb/lib/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;AAAA,iCAAiC;AAEjC,yBAAyB;AACzB,6BAA0B;AAE1B,iCAAgE;AAEhE,8DAA4E;AAE5E,2CAAmD;AAInD,mCAOiB;AAKjB,iDAA6C;AAC7C,uDAAmD;AACnD,0CAA2C;AAI3C,mDAAuE;AAU1D,QAAA,SAAS,GAAG;IACvB,iBAAiB,CAAa,MAA2B;QACvD,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC;YAC5B,CAAC,CAAC,MAAM;YACR,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,CAAC;IACvE,CAAC;IAED,MAAM,CAAa,IAAgB,EAAE,IAAgB;QACnD,OAAO,iBAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,C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,EAAE,IAAsB;IAC5E,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,EAAE;QAChC,OAAO,CAAC,CAAC;KACV;IAED,IAAI,IAAI,IAAI,IAAI,EAAE;QAChB,OAAO,CAAC,CAAC,CAAC;KACX;IAED,IAAI,IAAI,IAAI,IAAI,EAAE;QAChB,OAAO,CAAC,CAAC;KACV;IAED,OAAO,iBAAS,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,IAAI,CAAC,EAAE,CAAC,CAAC;AAC7C,CAAC;AAdD,0CAcC;AAED,SAAgB,YAAY,CAAC,KAAc;IACzC,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACxD,MAAM,WAAW,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC;IAEvD,OAAO,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,WAAW,CAAC;AACxD,CAAC;AALD,oCAKC;AAED,SAAgB,oBAAoB,CAAC,KAAc;IACjD,MAAM,SAAS,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;IAEtC,OAAO,SAAS,IAAI,IAAI,IAAI,SAAS,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;AAChE,CAAC;AAJD,oDAIC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/write_concern.js b/2_PAC/node_modules/mongodb/lib/write_concern.js new file mode 100644 index 00000000..43cdeec8 --- /dev/null +++ b/2_PAC/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 ?? {}; + 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 ?? wtimeoutMS, j ?? journal, fsync); + } + return undefined; + } +} +exports.WriteConcern = WriteConcern; +//# sourceMappingURL=write_concern.js.map \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/lib/write_concern.js.map b/2_PAC/node_modules/mongodb/lib/write_concern.js.map new file mode 100644 index 00000000..039f92b0 --- /dev/null +++ b/2_PAC/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,G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,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,IAAI,UAAU,EAAE,CAAC,IAAI,OAAO,EAAE,KAAK,CAAC,CAAC;SACzE;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA7ED,oCA6EC"} \ No newline at end of file diff --git a/2_PAC/node_modules/mongodb/mongodb.d.ts b/2_PAC/node_modules/mongodb/mongodb.d.ts new file mode 100644 index 00000000..69de74ab --- /dev/null +++ b/2_PAC/node_modules/mongodb/mongodb.d.ts @@ -0,0 +1,6203 @@ +/// + +import { Binary } from 'bson'; +import { BSON } from 'bson'; +import { BSONRegExp } from 'bson'; +import { BSONSymbol } from 'bson'; +import { BSONType } from 'bson'; +import { Code } from 'bson'; +import type { ConnectionOptions as ConnectionOptions_2 } from 'tls'; +import { DBRef } from 'bson'; +import { Decimal128 } from 'bson'; +import { deserialize } 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 { MaxKey } from 'bson'; +import { MinKey } from 'bson'; +import { ObjectId } from 'bson'; +import type { ObjectIdLike } from 'bson'; +import { Readable } from 'stream'; +import { serialize } 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](): AsyncGenerator; + stream(options?: CursorStreamOptions): Readable & AsyncIterable; + hasNext(): Promise; + /** Get the next available document from the cursor, returns null if no more documents are available. */ + next(): Promise; + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + */ + forEach(iterator: (doc: TSchema) => boolean | void): Promise; + close(): Promise; + /** + * 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. + */ + toArray(): Promise; + /** + * 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** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **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; + /** + * Specifies the number of documents to return in each response from MongoDB + */ + batchSize?: number; + /** + * When applicable `maxTimeMS` controls the amount of time the initial command + * that constructs a cursor should take. (ex. find, aggregate, listCollections) + */ + maxTimeMS?: number; + /** + * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores + * that a cursor uses to fetch more data should take. (ex. cursor.next()) + */ + 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; + /** + * By default, MongoDB will automatically close a cursor when the + * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections) + * you may use a Tailable Cursor that remains open after the client exhausts + * the results in the initial cursor. + */ + tailable?: boolean; + /** + * If awaitData is set to true, when the cursor reaches the end of the capped collection, + * MongoDB blocks the query thread for a period of time waiting for new data to arrive. + * When new data is inserted into the capped collection, the blocked thread is signaled + * to wake up and return the next batch to the client. + */ + 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 { + /** 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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +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 + */ + command(command: Document, options?: RunCommandOptions): Promise; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + buildInfo(options?: CommandOperationOptions): Promise; + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + serverInfo(options?: CommandOperationOptions): Promise; + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + serverStatus(options?: CommandOperationOptions): Promise; + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + ping(options?: CommandOperationOptions): Promise; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + addUser(username: string, passwordOrOptions?: string | AddUserOptions, options?: AddUserOptions): Promise; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + removeUser(username: string, options?: RemoveUserOptions): Promise; + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + validateCollection(collectionName: string, options?: ValidateCollectionOptions): Promise; + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + listDatabases(options?: ListDatabasesOptions): Promise; + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + replSetGetStatus(options?: CommandOperationOptions): Promise; +} + +/* 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(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; + /** 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: 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 Field Level 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 { BSON } + +export { BSONRegExp } + +/** + * BSON Serialization options. + * @public + */ +export declare interface BSONSerializeOptions extends Omit, Omit { + /** + * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html) + * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize). + * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe) + * for more detail about what "unsafe" refers to in this context. + * If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate + * your own buffer and clone the contents: + * + * @example + * ```ts + * const raw = await collection.findOne({}, { raw: true }); + * const myBuffer = Buffer.alloc(raw.byteLength); + * myBuffer.set(raw, 0); + * // Only save and use `myBuffer` beyond this point + * ``` + * + * @remarks + * Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)). + * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work. + */ + raw?: boolean; + /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */ + enableUtf8Validation?: boolean; +} + +export { BSONSymbol } + +export { 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 + * ```ts + * 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 + * ```ts + * 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; + /* Excluded from this release type: handleWriteError */ + abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/* Excluded from this release type: BulkOperationPrivate */ + +/* Excluded from this release type: BulkResult */ + +/** @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; + /** 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 { + private readonly result; + /** Number of documents inserted. */ + readonly insertedCount: number; + /** Number of documents matched for update. */ + readonly matchedCount: number; + /** Number of documents modified. */ + readonly modifiedCount: number; + /** Number of documents deleted. */ + readonly deletedCount: number; + /** Number of documents upserted. */ + readonly upsertedCount: number; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + readonly upsertedIds: { + [key: number]: any; + }; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + readonly insertedIds: { + [key: number]: any; + }; + private static generateIdMap; + /* Excluded from this release type: __constructor */ + /** 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 the write concern error if one exists */ + getWriteConcernError(): WriteConcernError | undefined; + 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; + /** Get the next available document from the Change Stream. */ + next(): Promise; + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + tryNext(): Promise; + [Symbol.asyncIterator](): AsyncGenerator; + /** Is the cursor closed */ + get closed(): boolean; + /** Close the Change Stream */ + close(): Promise; + /** + * 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: 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 occurred 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. + * + * @sinceServerVersion 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. + * + * @sinceServerVersion 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 occurred 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 occurred 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 occurred 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 occurred 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 occurred 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 + */ + endSession(options?: EndSessionOptions): Promise; + /** + * 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. + */ + commitTransaction(): Promise; + /** + * Aborts the currently active transaction in this session. + */ + abortTransaction(): Promise; + /** + * 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 + * @see https://www.mongodb.com/docs/manual/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/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +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 + */ + insertOne(doc: OptionalUnlessRequiredId, options?: InsertOneOptions): Promise>; + /** + * 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 + */ + insertMany(docs: OptionalUnlessRequiredId[], options?: BulkWriteOptions): Promise>; + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * 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 + * @throws MongoDriverError if operations is not an array + */ + bulkWrite(operations: AnyBulkWriteOperation[], options?: BulkWriteOptions): Promise; + /** + * 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 + */ + updateOne(filter: Filter, update: UpdateFilter | Partial, options?: UpdateOptions): Promise; + /** + * 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 + */ + replaceOne(filter: Filter, replacement: WithoutId, options?: ReplaceOptions): Promise; + /** + * 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 + */ + updateMany(filter: Filter, update: UpdateFilter, options?: UpdateOptions): Promise; + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + deleteOne(filter?: Filter, options?: DeleteOptions): Promise; + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + deleteMany(filter?: Filter, options?: DeleteOptions): Promise; + /** + * 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 + */ + rename(newName: string, options?: RenameOptions): Promise; + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + drop(options?: DropCollectionOptions): Promise; + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + */ + findOne(): Promise | null>; + findOne(filter: Filter): Promise | null>; + findOne(filter: Filter, options: FindOptions): Promise | null>; + findOne(): Promise; + findOne(filter: Filter): Promise; + findOne(filter: Filter, options?: FindOptions): Promise; + /** + * 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 + */ + options(options?: OperationOptions): Promise; + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + isCapped(options?: OperationOptions): Promise; + /** + * 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 + * + * @example + * ```ts + * 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, options?: CreateIndexesOptions): Promise; + /** + * 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 + * + * @example + * ```ts + * 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[], options?: CreateIndexesOptions): Promise; + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + dropIndex(indexName: string, options?: DropIndexesOptions): Promise; + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + dropIndexes(options?: DropIndexesOptions): Promise; + /** + * 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 + */ + indexExists(indexes: string | string[], options?: IndexInformationOptions): Promise; + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + indexInformation(options?: IndexInformationOptions): Promise; + /** + * 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 + */ + estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise; + /** + * 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 + * + * @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(filter?: Document, options?: CountDocumentsOptions): Promise; + /** + * 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 + */ + distinct>(key: Key): Promise[Key]>>>; + distinct>(key: Key, filter: Filter): Promise[Key]>>>; + distinct>(key: Key, filter: Filter, options: DistinctOptions): Promise[Key]>>>; + distinct(key: string): Promise; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + indexes(options?: IndexInformationOptions): Promise; + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + */ + stats(options?: CollStatsOptions): Promise; + /** + * 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 + */ + findOneAndDelete(filter: Filter, options?: FindOneAndDeleteOptions): Promise>; + /** + * 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 + */ + findOneAndReplace(filter: Filter, replacement: WithoutId, options?: FindOneAndReplaceOptions): Promise>; + /** + * 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 + */ + findOneAndUpdate(filter: Filter, update: UpdateFilter, options?: FindOneAndUpdateOptions): Promise>; + /** + * 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 use cases: + * - 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; + /** + * 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 implementation. + * 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 implementation. + * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting. + */ + initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation; + /** + * 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 + */ + count(filter?: Filter, options?: CountOptions): Promise; +} + +/** @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 { + /** 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 { + /** 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 */ + interruptInUseConnections?: boolean; + /* 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; + connectionPoolReady(event: ConnectionPoolReadyEvent): 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; + /* Excluded from this release type: minPoolSizeCheckFrequencyMS */ +} + +/** + * An event published when a connection pool is ready + * @public + * @category Event + */ +export declare class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /* Excluded from this release type: __constructor */ +} + +/** + * 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. This option is deprecated in MongoDB 3.2+ and will be removed once no longer supported by the server. */ + 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 */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection */ + 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) */ + 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 */ + 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 */ +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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +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; + /** + * 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 + */ + createCollection(name: string, options?: CreateCollectionOptions): Promise>; + /** + * 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 + */ + command(command: Document, options?: RunCommandOptions): Promise; + /** + * 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 + */ + stats(options?: DbStatsOptions): Promise; + /** + * 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 + */ + renameCollection(fromCollection: string, toCollection: string, options?: RenameOptions): Promise>; + /** + * 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 + */ + dropCollection(name: string, options?: DropCollectionOptions): Promise; + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + dropDatabase(options?: DropDatabaseOptions): Promise; + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + collections(options?: ListCollectionsOptions): Promise; + /** + * 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 + */ + createIndex(name: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise; + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + addUser(username: string, passwordOrOptions?: string | AddUserOptions, options?: AddUserOptions): Promise; + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + removeUser(username: string, options?: RemoveUserOptions): Promise; + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + setProfilingLevel(level: ProfilingLevel, options?: SetProfilingLevelOptions): Promise; + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + profilingLevel(options?: ProfilingLevelOptions): Promise; + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + indexInformation(name: string, options?: IndexInformationOptions): Promise; + /** + * 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 use cases: + * - 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; +} + +/* Excluded from this release type: DB_AGGREGATE_COLLECTION */ + +/** @public */ +export declare interface DbOptions extends BSONSerializeOptions, WriteConcernOptions { + /** 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; +} + +/** @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; +} + +export { deserialize } + +/* Excluded from this release type: DestroyOptions */ + +/** @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 = { + [P in keyof WithId]?: Condition[P]>; +} & 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 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(options?: CountOptions): Promise; + /** Execute the explain for the cursor */ + 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 | Document[]): BulkOperationBase; + /** Add a single update operation to the bulk operation */ + updateOne(updateDocument: Document | 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; + /** Specifies hint for the bulk operation. */ + hint(hint: Hint): 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; + /** + * Option to enable an optimized code path for queries looking for a particular range of `ts` values in the oplog. Requires `tailable` to be true. + * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored. + */ + oplogReplay?: boolean; +} + +/** @public */ +export declare type Flatten = Type extends ReadonlyArray ? Item : Type; + +/** @public */ +export declare type GenericListener = (...args: any[]) => void; + +/** + * 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; + /** 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; + /** Removes this bucket's files collection, followed by its chunks collection. */ + drop(): Promise; +} + +/** @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. + */ + abort(): Promise; +} + +/** @public */ +export declare interface GridFSBucketReadStreamOptions { + sort?: Sort; + skip?: number; + /** + * 0-indexed non-negative byte offset from the beginning of the file + */ + start?: number; + /** + * 0-indexed non-negative byte offset to the end of the file contents + * to be returned by the stream. `end` is non-inclusive + */ + 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. + */ + abort(): Promise; + /** + * 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; + constructor(hostString: string); + inspect(): string; + toString(): 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: { + [key: string]: IndexDirection; + } | Map; +} + +/** @public */ +export declare type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | 'hashed' | 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 */ + +/** @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: 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: 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: 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: 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: kPoolState */ + +/* 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: kServer_3 */ + +/* 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"]; + +/* Excluded from this release type: List */ + +/** @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; +} + +export { Long } + +/** @public */ +export declare type MatchKeysAndValues = Readonly> & Record; + +export { MaxKey } + +/* Excluded from this release type: MessageHeader */ + +/* Excluded from this release type: MessageStream */ + +/* Excluded from this release type: MessageStreamOptions */ +export { MinKey } + +/** + * @public + * @deprecated This type will be completely removed in 5.0 and findOneAndUpdate, + * findOneAndDelete, and findOneAndReplace will then return the + * actual result document. + */ +export declare interface ModifyResult { + value: WithId | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export declare const MONGO_CLIENT_EVENTS: readonly ["connectionPoolCreated", "connectionPoolReady", "connectionPoolCleared", "connectionPoolClosed", "connectionCreated", "connectionReady", "connectionClosed", "connectionCheckOutStarted", "connectionCheckOutFailed", "connectionCheckedOut", "connectionCheckedIn", "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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +export declare class MongoClient extends TypedEventEmitter { + /* Excluded from this release type: s */ + /* Excluded from this release type: topology */ + /* Excluded from this release type: mongoLogger */ + /* 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; + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + connect(): Promise; + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + close(force?: boolean): Promise; + /** + * 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, options?: MongoClientOptions): Promise; + /** Starts a new session on the server */ + 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 use cases: + * - 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; +} + +/** @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 + * @deprecated Please use the `writeConcern` option instead + */ + w?: W; + /** + * The write concern timeout + * @deprecated Please use the `writeConcern` option instead + */ + wtimeoutMS?: number; + /** + * The journal write concern + * @deprecated Please use the `writeConcern` option instead + */ + journal?: boolean; + /** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + writeConcern?: WriteConcern | WriteConcernSettings; + /** 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; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable in-use 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 | undefined; + /** + * 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 + * mongodb-client-encryption 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; + connectionGeneration?: number; + cause?: Error; + 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"; + readonly ResetPool: "ResetPool"; + readonly InterruptInUseConnections: "InterruptInUseConnections"; + readonly NoWritesPerformed: "NoWritesPerformed"; +}>; + +/** @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; +} + +/* Excluded from this release type: MongoLoggableComponent */ + +/* Excluded from this release type: MongoLogger */ + +/* Excluded from this release type: MongoLoggerEnvOptions */ + +/* Excluded from this release type: MongoLoggerMongoClientOptions */ + +/* Excluded from this release type: MongoLoggerOptions */ + +/** + * 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 + * mongodb-client-encryption 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 */ + /* Excluded from this release type: mongoLoggerOptions */ +} + +/** + * 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?: MongoError): void; + resetConnectionPool(): void; + close(): void; +} & EventEmitterWithState; + +/* Excluded from this release type: MonitorInterval */ + +/* Excluded from this release type: MonitorIntervalOptions */ + +/** @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/ + * + * @remarks + * Through testing we determined that a depth of 8 is safe for the typescript compiler + * and provides reasonable compilation times. This number is otherwise not special and + * should be changed if issues are found with this level of checking. Beyond this + * depth any helpers that make use of NestedPaths should devolve to not asserting any + * type safety on the input. + */ +export declare type NestedPaths = Depth['length'] extends 8 ? [] : 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 + ] : // child is not structured the same as the parent + [ + Key, + ...NestedPaths + ] | [Key]; +}[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; + +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: 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 required 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 { + /* Excluded from this release type: __constructor */ + addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this; +} + +/** @public */ +export declare interface PkFactory { + createPk(): any; +} + +/* Excluded from this release type: PoolState */ + +/** @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 */ +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 */ + +/** + * 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 + * @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 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; +} + +export { 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 { + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error: MongoError | null; + topologyVersion: TopologyVersion | null; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me: string | null; + primary: string | null; + setName: string | null; + setVersion: number | null; + electionId: ObjectId | null; + logicalSessionTimeoutMinutes: number | null; + $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 | null): 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 */ +} + +/* Excluded from this release type: ServerOptions */ + +/* Excluded from this release type: ServerPrivate */ + +/* Excluded from this release type: ServerSelectionCallback */ + +/* Excluded from this release type: ServerSelectionRequest */ + +/* Excluded from this release type: ServerSelector */ + +/** + * 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; + +/* Excluded from this release type: SeverityLevel */ + +/** @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 + * @experimental + */ +export declare type StrictFilter = Partial | ({ + [Property in Join, []>, '.'>]?: Condition, Property>>; +} & RootFilterOperators>); + +/** + * @public + * @experimental + */ +export declare type StrictMatchKeysAndValues = Readonly<{ + [Property in Join, '.'>]?: PropertyType; +} & { + [Property in `${NestedPathsOfType}.$${`[${string}]` | ''}`]?: ArrayElement>; +} & { + [Property in `${NestedPathsOfType[]>}.$${`[${string}]` | ''}.${string}`]?: any; +} & Document>; + +/** + * @public + * @experimental + */ +export declare type StrictUpdateFilter = { + $currentDate?: OnlyFieldsOfType; + $inc?: OnlyFieldsOfType; + $min?: StrictMatchKeysAndValues; + $max?: StrictMatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: StrictMatchKeysAndValues; + $setOnInsert?: StrictMatchKeysAndValues; + $unset?: OnlyFieldsOfType; + $addToSet?: SetFields; + $pop?: OnlyFieldsOfType, 1 | -1>; + $pull?: PullOperator; + $push?: PushOperator; + $pullAll?: PullAllOperator; + $bit?: OnlyFieldsOfType; +} & Document; + +/** @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 | null; + maxSetVersion: number | null; + maxElectionId: ObjectId | null; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes: number | null; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion: number; + /** + * Create a TopologyDescription + */ + constructor(topologyType: TopologyType, serverDescriptions?: Map | null, setName?: string | null, maxSetVersion?: number | null, maxElectionId?: ObjectId | null, commonWireVersion?: number | null, options?: TopologyDescriptionOptions | null); + /* Excluded from this release type: updateFromSrvPollingEvent */ + /* Excluded from this release type: update */ + get error(): MongoServerError | null; + /** + * 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 */ +} + +/* Excluded from this release type: TopologyOptions */ + +/* 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?: ReadPreferenceLike; + /** 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 { + /* Excluded from this release type: __constructor */ + 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; + }>; + /** + * A document containing additional information about any ambiguous update paths from the update event. The document + * maps the full ambiguous update path to an array containing the actual resolved components of the path. For example, + * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like + * the following: + * + * ``` + * { + * 'a.0': ['a', '0'] + * } + * ``` + * + * This field is only present when there are ambiguous paths that are updated as a part of the update event and `showExpandedEvents` + * is enabled for the change stream. + * @sinceServerVersion 6.1.0 + */ + disambiguatedPaths?: Document; +} + +/** @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?: Hint; + /** 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; + 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/2_PAC/node_modules/mongodb/package.json b/2_PAC/node_modules/mongodb/package.json new file mode 100644 index 00000000..ae0dfa21 --- /dev/null +++ b/2_PAC/node_modules/mongodb/package.json @@ -0,0 +1,155 @@ +{ + "name": "mongodb", + "version": "5.0.1", + "description": "The official MongoDB driver for Node.js", + "main": "lib/index.js", + "files": [ + "lib", + "src", + "etc/prepare.js", + "mongodb.d.ts", + "tsconfig.json" + ], + "types": "mongodb.d.ts", + "repository": { + "type": "git", + "url": "git@github.com:mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "official" + ], + "author": { + "name": "The MongoDB NodeJS Team", + "email": "dbx-node@mongodb.com" + }, + "dependencies": { + "bson": "^5.0.0", + "mongodb-connection-string-url": "^2.6.0", + "socks": "^2.7.1" + }, + "optionalDependencies": { + "saslprep": "^1.0.3" + }, + "peerDependencies": { + "@aws-sdk/credential-providers": "^3.201.0", + "mongodb-client-encryption": "^2.3.0", + "snappy": "^7.2.2" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-providers": { + "optional": true + }, + "snappy": { + "optional": true + }, + "mongodb-client-encryption": { + "optional": true + } + }, + "devDependencies": { + "@aws-sdk/credential-providers": "^3.201.0", + "@iarna/toml": "^2.2.5", + "@istanbuljs/nyc-config-typescript": "^1.0.2", + "@microsoft/api-extractor": "^7.33.7", + "@microsoft/tsdoc-config": "^0.16.2", + "@mongodb-js/zstd": "^1.0.0", + "@types/chai": "^4.3.3", + "@types/chai-subset": "^1.3.3", + "@types/express": "^4.17.14", + "@types/kerberos": "^1.1.1", + "@types/mocha": "^10.0.0", + "@types/node": "^18.11.0", + "@types/saslprep": "^1.0.1", + "@types/semver": "^7.3.12", + "@types/sinon": "^10.0.13", + "@types/sinon-chai": "^3.2.8", + "@types/whatwg-url": "^11.0.0", + "@typescript-eslint/eslint-plugin": "^5.48.0", + "@typescript-eslint/parser": "^5.48.0", + "chai": "^4.3.6", + "chai-subset": "^1.6.0", + "chalk": "^4.1.2", + "eslint": "^8.31.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-prettier": "^4.2.1", + "eslint-plugin-simple-import-sort": "^8.0.0", + "eslint-plugin-tsdoc": "^0.2.17", + "express": "^4.18.2", + "js-yaml": "^4.1.0", + "mocha": "^9.2.2", + "mocha-sinon": "^2.1.2", + "mongodb-legacy": "^4.0.0", + "nyc": "^15.1.0", + "prettier": "^2.7.1", + "rimraf": "^3.0.2", + "semver": "^7.3.8", + "sinon": "^13.0.1", + "sinon-chai": "^3.7.0", + "snappy": "^7.2.2", + "source-map-support": "^0.5.21", + "standard-version": "^9.5.0", + "ts-node": "^10.9.1", + "tsd": "^0.25.0", + "typescript": "^4.9.4", + "typescript-cached-transpile": "^0.0.6", + "xml2js": "^0.4.23", + "yargs": "^17.6.0" + }, + "license": "Apache-2.0", + "engines": { + "node": ">=14.20.1" + }, + "bugs": { + "url": "https://jira.mongodb.org/projects/NODE/issues/" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "scripts": { + "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:lambda": "mocha --config test/mocha_lambda.json test/integration/node-specific/examples/handler.test.js", + "check:lambda:aws": "mocha --config test/mocha_lambda.json test/integration/node-specific/examples/aws_handler.test.js", + "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:dependencies": "mocha test/action/dependency.test.ts", + "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.ts", + "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": "bash etc/check-remote.sh && 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" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "strict": true, + "target": "esnext", + "module": "commonjs", + "moduleResolution": "node" + } + } +} diff --git a/2_PAC/node_modules/mongodb/src/admin.ts b/2_PAC/node_modules/mongodb/src/admin.ts new file mode 100644 index 00000000..9e9a64e0 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/admin.ts @@ -0,0 +1,174 @@ +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'; + +/** @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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const admin = client.db().admin(); + * const dbInfo = await admin.listDatabases(); + * for (const db of dbInfo.databases) { + * console.log(db.name); + * } + * ``` + */ +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 + */ + async command(command: Document, options?: RunCommandOptions): Promise { + return executeOperation( + this.s.db.s.client, + new RunCommandOperation(this.s.db, command, { dbName: 'admin', ...options }) + ); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async buildInfo(options?: CommandOperationOptions): Promise { + return this.command({ buildinfo: 1 }, options); + } + + /** + * Retrieve the server build information + * + * @param options - Optional settings for the command + */ + async serverInfo(options?: CommandOperationOptions): Promise { + return this.command({ buildinfo: 1 }, options); + } + + /** + * Retrieve this db's server status. + * + * @param options - Optional settings for the command + */ + async serverStatus(options?: CommandOperationOptions): Promise { + return this.command({ serverStatus: 1 }, options); + } + + /** + * Ping the MongoDB server and retrieve results + * + * @param options - Optional settings for the command + */ + async ping(options?: CommandOperationOptions): Promise { + return this.command({ ping: 1 }, options); + } + + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + async addUser( + username: string, + passwordOrOptions?: string | AddUserOptions, + options?: AddUserOptions + ): Promise { + options = + options != null && typeof options === 'object' + ? options + : passwordOrOptions != null && typeof passwordOrOptions === 'object' + ? passwordOrOptions + : undefined; + const password = typeof passwordOrOptions === 'string' ? passwordOrOptions : undefined; + return executeOperation( + this.s.db.s.client, + new AddUserOperation(this.s.db, username, password, { dbName: 'admin', ...options }) + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username: string, options?: RemoveUserOptions): Promise { + return executeOperation( + this.s.db.s.client, + new RemoveUserOperation(this.s.db, username, { dbName: 'admin', ...options }) + ); + } + + /** + * Validate an existing collection + * + * @param collectionName - The name of the collection to validate. + * @param options - Optional settings for the command + */ + async validateCollection( + collectionName: string, + options: ValidateCollectionOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new ValidateCollectionOperation(this, collectionName, options) + ); + } + + /** + * List the available databases + * + * @param options - Optional settings for the command + */ + async listDatabases(options?: ListDatabasesOptions): Promise { + return executeOperation(this.s.db.s.client, new ListDatabasesOperation(this.s.db, options)); + } + + /** + * Get ReplicaSet status + * + * @param options - Optional settings for the command + */ + async replSetGetStatus(options?: CommandOperationOptions): Promise { + return this.command({ replSetGetStatus: 1 }, options); + } +} diff --git a/2_PAC/node_modules/mongodb/src/bson.ts b/2_PAC/node_modules/mongodb/src/bson.ts new file mode 100644 index 00000000..8ef9bc2a --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/bson.ts @@ -0,0 +1,115 @@ +import type { DeserializeOptions, SerializeOptions } from 'bson'; + +export { + Binary, + BSON, + BSONRegExp, + BSONSymbol, + BSONType, + calculateObjectSize, + Code, + DBRef, + Decimal128, + deserialize, + Document, + Double, + Int32, + Long, + MaxKey, + MinKey, + ObjectId, + serialize, + Timestamp +} from 'bson'; + +/** + * BSON Serialization options. + * @public + */ +export interface BSONSerializeOptions + extends Omit, + Omit< + DeserializeOptions, + | 'evalFunctions' + | 'cacheFunctions' + | 'cacheFunctionsCrc32' + | 'allowObjectSmallerThanBufferSize' + | 'index' + | 'validation' + | 'useBigInt64' + > { + /** + * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html) + * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize). + * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe) + * for more detail about what "unsafe" refers to in this context. + * If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate + * your own buffer and clone the contents: + * + * @example + * ```ts + * const raw = await collection.findOne({}, { raw: true }); + * const myBuffer = Buffer.alloc(raw.byteLength); + * myBuffer.set(raw, 0); + * // Only save and use `myBuffer` beyond this point + * ``` + * + * @remarks + * Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)). + * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work. + */ + 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/2_PAC/node_modules/mongodb/src/bulk/common.ts b/2_PAC/node_modules/mongodb/src/bulk/common.ts new file mode 100644 index 00000000..566c2464 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/bulk/common.ts @@ -0,0 +1,1282 @@ +import { BSONSerializeOptions, Document, ObjectId, resolveBSONOptions } 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 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 }; + +/** @internal */ +export interface BulkResult { + ok: number; + writeErrors: WriteError[]; + writeConcernErrors: WriteConcernError[]; + insertedIds: Document[]; + nInserted: number; + nUpserted: number; + nMatched: number; + nModified: number; + nRemoved: number; + upserted: 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 { + private readonly result: BulkResult; + /** Number of documents inserted. */ + readonly insertedCount: number; + /** Number of documents matched for update. */ + readonly matchedCount: number; + /** Number of documents modified. */ + readonly modifiedCount: number; + /** Number of documents deleted. */ + readonly deletedCount: number; + /** Number of documents upserted. */ + readonly upsertedCount: number; + /** Upserted document generated Id's, hash key is the index of the originating operation */ + readonly upsertedIds: { [key: number]: any }; + /** Inserted document generated Id's, hash key is the index of the originating operation */ + readonly insertedIds: { [key: number]: any }; + + private static generateIdMap(ids: Document[]): { [key: number]: any } { + const idMap: { [index: number]: any } = {}; + for (const doc of ids) { + idMap[doc.index] = doc._id; + } + return idMap; + } + + /** + * Create a new BulkWriteResult instance + * @internal + */ + constructor(bulkResult: BulkResult) { + this.result = bulkResult; + this.insertedCount = this.result.nInserted ?? 0; + this.matchedCount = this.result.nMatched ?? 0; + this.modifiedCount = this.result.nModified ?? 0; + this.deletedCount = this.result.nRemoved ?? 0; + this.upsertedCount = this.result.upserted.length ?? 0; + this.upsertedIds = BulkWriteResult.generateIdMap(this.result.upserted); + this.insertedIds = BulkWriteResult.generateIdMap(this.result.insertedIds); + Object.defineProperty(this, 'result', { value: this.result, enumerable: false }); + } + + /** 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 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 }); + } + } + + toString(): string { + return `BulkWriteResult(${this.result})`; + } + + 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; + } + + 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())})`; + } +} + +/** 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; + } + + // 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 + mergeBatchResults(batch, bulkOperation.s.bulkResult, err, result); + const writeResult = new BulkWriteResult(bulkOperation.s.bulkResult); + 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 | 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 | 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; + } + + /** Specifies hint for the bulk operation. */ + hint(hint: Hint): this { + if (!this.bulkOperation.s.currentOp) { + this.bulkOperation.s.currentOp = {}; + } + + this.bulkOperation.s.currentOp.hint = hint; + 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; + /** 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 + * ```ts + * 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 + * ```ts + * 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; + } + + async execute(options: BulkWriteOptions = {}): Promise { + if (this.s.executed) { + throw new MongoBatchReExecutionError(); + } + + 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) { + throw new MongoInvalidArgumentError('Invalid BulkOperation, Batch cannot be empty'); + } + + 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); + } + + /** + * 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; + } +}); + +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/2_PAC/node_modules/mongodb/src/bulk/ordered.ts b/2_PAC/node_modules/mongodb/src/bulk/ordered.ts new file mode 100644 index 00000000..97ee6444 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/bulk/ordered.ts @@ -0,0 +1,83 @@ +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 { + /** @internal */ + 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/2_PAC/node_modules/mongodb/src/bulk/unordered.ts b/2_PAC/node_modules/mongodb/src/bulk/unordered.ts new file mode 100644 index 00000000..5f2e562f --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/bulk/unordered.ts @@ -0,0 +1,110 @@ +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 { + /** @internal */ + 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/2_PAC/node_modules/mongodb/src/change_stream.ts b/2_PAC/node_modules/mongodb/src/change_stream.ts new file mode 100644 index 00000000..ee6876ac --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/change_stream.ts @@ -0,0 +1,950 @@ +import type { Readable } from 'stream'; + +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 { filterOptions, getTopology, 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; + +/** + * 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. + * + * @sinceServerVersion 6.1.0 + */ + collectionUUID: Binary; +} + +/** @public */ +export interface ChangeStreamDocumentOperationDescription { + /** + * An description of the operation. + * + * Only present when the `showExpandedEvents` flag is enabled. + * + * @sinceServerVersion 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 occurred 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 occurred 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 occurred 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 occurred 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 occurred 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 occurred 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; + }>; + + /** + * A document containing additional information about any ambiguous update paths from the update event. The document + * maps the full ambiguous update path to an array containing the actual resolved components of the path. For example, + * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like + * the following: + * + * ``` + * { + * 'a.0': ['a', '0'] + * } + * ``` + * + * This field is only present when there are ambiguous paths that are updated as a part of the update event and `showExpandedEvents` + * is enabled for the change stream. + * @sinceServerVersion 6.1.0 + */ + disambiguatedPaths?: Document; +} + +/** @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 */ + async hasNext(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const hasNext = await this.cursor.hasNext(); + return hasNext; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + /** Get the next available document from the Change Stream. */ + async next(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.next(); + const processedChange = this._processChange(change ?? null); + return processedChange; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + /** + * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned + */ + async tryNext(): Promise { + this._setIsIterator(); + // Change streams must resume indefinitely while each resume event succeeds. + // This loop continues until either a change event is received or until a resume attempt + // fails. + // eslint-disable-next-line no-constant-condition + while (true) { + try { + const change = await this.cursor.tryNext(); + return change ?? null; + } catch (error) { + try { + await this._processErrorIteratorMode(error); + } catch (error) { + try { + await this.close(); + } catch { + // We are not concerned with errors from close() + } + throw error; + } + } + } + } + + async *[Symbol.asyncIterator](): AsyncGenerator { + if (this.closed) { + return; + } + + try { + // Change streams run indefinitely as long as errors are resumable + // So the only loop breaking condition is if `next()` throws + while (true) { + yield await this.next(); + } + } finally { + try { + await this.close(); + } catch { + // we're not concerned with errors from close() + } + } + } + + /** Is the cursor closed */ + get closed(): boolean { + return this[kClosed] || this.cursor.closed; + } + + /** Close the Change Stream */ + async close(): Promise { + this[kClosed] = true; + + const cursor = this.cursor; + try { + await cursor.close(); + } finally { + this._endStream(); + } + } + + /** + * 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().catch(() => null); + } + + /** @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 */ + private async _processErrorIteratorMode(changeStreamError: AnyError) { + if (this[kClosed]) { + // TODO(NODE-3485): Replace with MongoChangeStreamClosedError + throw new MongoAPIError(CHANGESTREAM_CLOSED_ERROR); + } + + if (!isResumableError(changeStreamError, this.cursor.maxWireVersion)) { + try { + await this.close(); + } catch { + // ignore errors from close + } + throw changeStreamError; + } + + await this.cursor.close().catch(() => null); + const topology = getTopology(this.parent); + try { + await topology.selectServerAsync(this.cursor.readPreference, {}); + this.cursor = this._createChangeStreamCursor(this.cursor.resumeOptions); + } catch { + // if the topology can't reconnect, close the stream + await this.close(); + throw changeStreamError; + } + } +} diff --git a/2_PAC/node_modules/mongodb/src/cmap/auth/auth_provider.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/auth_provider.ts new file mode 100644 index 00000000..2a38abe9 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cmap/auth/gssapi.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/gssapi.ts new file mode 100644 index 00000000..924fbde6 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/auth/gssapi.ts @@ -0,0 +1,239 @@ +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 = { + 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/2_PAC/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts new file mode 100644 index 00000000..fa461006 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/auth/mongo_credentials.ts @@ -0,0 +1,181 @@ +// Resolves the default auth mechanism according to +import type { Document } from '../../bson'; +import { MongoAPIError, MongoMissingCredentialsError } from '../../error'; +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 + }; + } + } + + 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/2_PAC/node_modules/mongodb/src/cmap/auth/mongocr.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/mongocr.ts new file mode 100644 index 00000000..232378f0 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts new file mode 100644 index 00000000..c932da6a --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/auth/mongodb_aws.ts @@ -0,0 +1,335 @@ +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, getAwsCredentialProvider } from '../../deps'; +import { + MongoAWSError, + MongoCompatibilityError, + MongoMissingCredentialsError, + MongoRuntimeError +} from '../../error'; +import { ByteUtils, 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 (!ByteUtils.equals(serverNonce.subarray(0, nonce.byteLength), nonce)) { + // throw because the serverNonce's leading 32 bytes must equal the client nonce's 32 bytes + // https://github.com/mongodb/specifications/blob/875446db44aade414011731840831f38a6c668df/source/auth/auth.rst#id11 + + // 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': ByteUtils.toBase64(serverNonce), + '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; +} + +/* @internal */ +export interface AWSCredentials { + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: 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 + } + }) + ); + } + + const credentialProvider = getAwsCredentialProvider(); + + // Check if the AWS credential provider from the SDK is present. If not, + // use the old method. + if ('kModuleError' in credentialProvider) { + // 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); + } + ); + } + ); + } + ); + } else { + /* + * Creates a credential provider that will attempt to find credentials from the + * following sources (listed in order of precedence): + * + * - Environment variables exposed via process.env + * - SSO credentials from token cache + * - Web identity token credentials + * - Shared credentials and config ini files + * - The EC2/ECS Instance Metadata Service + */ + const { fromNodeProviderChain } = credentialProvider; + const provider = fromNodeProviderChain(); + provider() + .then((creds: AWSCredentials) => { + done({ + AccessKeyId: creds.accessKeyId, + SecretAccessKey: creds.secretAccessKey, + Token: creds.sessionToken, + Expiration: creds.expiration + }); + }) + .catch((error: Error) => { + callback(new MongoAWSError(error.message)); + }); + } +} + +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/2_PAC/node_modules/mongodb/src/cmap/auth/plain.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/plain.ts new file mode 100644 index 00000000..94b19a52 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cmap/auth/providers.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/providers.ts new file mode 100644 index 00000000..9c7b1f4b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cmap/auth/scram.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/scram.ts new file mode 100644 index 00000000..7a339151 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cmap/auth/x509.ts b/2_PAC/node_modules/mongodb/src/cmap/auth/x509.ts new file mode 100644 index 00000000..a12e6f9d --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cmap/command_monitoring_events.ts b/2_PAC/node_modules/mongodb/src/cmap/command_monitoring_events.ts new file mode 100644 index 00000000..40c3419a --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/command_monitoring_events.ts @@ -0,0 +1,301 @@ +import type { Document, ObjectId } from '../bson'; +import { LEGACY_HELLO_COMMAND, LEGACY_HELLO_COMMAND_CAMEL_CASE } from '../constants'; +import { calculateDurationInMs, deepCopy } from '../utils'; +import { 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 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 (!reply) { + return reply; + } + + 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/2_PAC/node_modules/mongodb/src/cmap/commands.ts b/2_PAC/node_modules/mongodb/src/cmap/commands.ts new file mode 100644 index 00000000..fa822aaa --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/commands.ts @@ -0,0 +1,702 @@ +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_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; + +/** @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(): Uint8Array[] { + 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 MessageHeader { + length: number; + requestId: number; + responseTo: number; + opCode: number; + fromCompressed?: boolean; +} + +/** @internal */ +export interface OpResponseOptions extends BSONSerializeOptions { + 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: Uint8Array[], 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): Uint8Array { + 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/2_PAC/node_modules/mongodb/src/cmap/connect.ts b/2_PAC/node_modules/mongodb/src/cmap/connect.ts new file mode 100644 index 00000000..e3f44cc9 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/connect.ts @@ -0,0 +1,523 @@ +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; +} + +/** + * @internal + * + * This function is only exposed for testing purposes. + */ +export 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]: 1, + helloOk: true, + client: options.metadata || makeClientMetadata(options), + compression: compressors + }; + + if (options.loadBalanced === true) { + handshakeDoc.loadBalanced = true; + } + + 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/2_PAC/node_modules/mongodb/src/cmap/connection.ts b/2_PAC/node_modules/mongodb/src/cmap/connection.ts new file mode 100644 index 00000000..b3155239 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/connection.ts @@ -0,0 +1,753 @@ +import { clearTimeout, setTimeout } from 'timers'; + +import type { BSONSerializeOptions, Document, ObjectId } 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 { 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, Msg, Query, Response, WriteProtocolMessageType } from './commands'; +import type { Stream } from './connect'; +import { MessageStream, OperationDescription } from './message_stream'; +import { StreamDescription, StreamDescriptionOptions } from './stream_description'; +import { 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 kDelayedTimeoutId = Symbol('delayedTimeoutId'); + +const INVALID_QUEUE_SIZE = 'Connection internal queue contains more than 1 operation description'; + +/** @internal */ +export interface CommandOptions extends BSONSerializeOptions { + command?: boolean; + secondaryOk?: boolean; + /** Specify read preference if command supports it */ + readPreference?: ReadPreferenceLike; + monitoring?: 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; +} + +/** @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; +} + +/** @internal */ +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); + let operationDescription = this[kQueue].get(message.responseTo); + + if (!operationDescription && this.isMonitoringConnection) { + // This is how we recover when the initial hello's requestId is not + // the responseTo when hello responses have been skipped: + + // First check if the map is of invalid size + if (this[kQueue].size > 1) { + this.onError(new MongoRuntimeError(INVALID_QUEUE_SIZE)); + } else { + // Get the first orphaned operation description. + const entry = this[kQueue].entries().next(); + if (entry.value != null) { + const [requestId, orphaned]: [number, OperationDescription] = entry.value; + // If the orphaned operation description exists then set it. + operationDescription = orphaned; + // Remove the entry with the bad request id from the queue. + this[kQueue].delete(requestId); + } + } + } + + 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) { + // If the operation description check above does find an orphaned + // description and sets the operationDescription then this line will put one + // back in the queue with the correct requestId and will resolve not being able + // to find the next one via the responseTo of the next streaming hello. + 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), 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, 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 { + 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); + } + } +} + +/** @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; + } + + // Save sort or indexKeys based on the command being run + // the encrypt API serializes our JS objects to BSON to pass to the native code layer + // and then deserializes the encrypted result, the protocol level components + // of the command (ex. sort) are then converted to JS objects potentially losing + // import key order information. These fields are never encrypted so we can save the values + // from before the encryption and replace them after encryption has been performed + const sort: Map | null = cmd.find || cmd.findAndModify ? cmd.sort : null; + const indexKeys: Map[] | null = cmd.createIndexes + ? cmd.indexes.map((index: { key: Map }) => index.key) + : null; + + autoEncrypter.encrypt(ns.toString(), cmd, options, (err, encrypted) => { + if (err || encrypted == null) { + callback(err, null); + return; + } + + // Replace the saved values + if (sort != null && (cmd.find || cmd.findAndModify)) { + encrypted.sort = sort; + } + if (indexKeys != null && cmd.createIndexes) { + for (const [offset, index] of indexKeys.entries()) { + encrypted.indexes[offset].key = index; + } + } + + 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(); + } + + const { remoteAddress, remotePort } = stream; + if (typeof remoteAddress === 'string' && typeof remotePort === 'number') { + return HostAddress.fromHostPort(remoteAddress, remotePort).toString(); + } + + return uuidV4().toString('hex'); +} + +function write( + conn: Connection, + command: WriteProtocolMessageType, + options: CommandOptions, + callback: Callback +) { + options = options ?? {}; + const operationDescription: OperationDescription = { + requestId: command.requestId, + cb: callback, + session: options.session, + 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) => { + // Command monitoring spec states that if ok is 1, then we must always emit + // a command suceeded event, even if there's an error. Write concern errors + // will have an ok: 1 in their reply. + if (err && reply?.ok !== 1) { + 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') { + // Since we're passing through the reply with the write concern error now, we + // need it not to be provided to the original callback in this case so + // retryability does not get tricked into thinking the command actually + // succeeded. + callback(err, err instanceof MongoWriteConcernError ? undefined : 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/2_PAC/node_modules/mongodb/src/cmap/connection_pool.ts b/2_PAC/node_modules/mongodb/src/cmap/connection_pool.ts new file mode 100644 index 00000000..e52fc908 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/connection_pool.ts @@ -0,0 +1,841 @@ +import { clearTimeout, 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_POOL_READY, + CONNECTION_READY +} from '../constants'; +import { + MongoError, + MongoInvalidArgumentError, + MongoNetworkError, + MongoRuntimeError, + MongoServerError +} from '../error'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import type { Server } from '../sdam/server'; +import { Callback, eachAsync, List, makeCounter } from '../utils'; +import { connect } from './connect'; +import { Connection, ConnectionEvents, ConnectionOptions } from './connection'; +import { + ConnectionCheckedInEvent, + ConnectionCheckedOutEvent, + ConnectionCheckOutFailedEvent, + ConnectionCheckOutStartedEvent, + ConnectionClosedEvent, + ConnectionCreatedEvent, + ConnectionPoolClearedEvent, + ConnectionPoolClosedEvent, + ConnectionPoolCreatedEvent, + ConnectionPoolReadyEvent, + ConnectionReadyEvent +} from './connection_pool_events'; +import { + PoolClearedError, + PoolClearedOnNetworkError, + PoolClosedError, + WaitQueueTimeoutError +} from './errors'; +import { ConnectionPoolMetrics } from './metrics'; + +/** @internal */ +const kServer = Symbol('server'); +/** @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'); +/** @internal */ +const kPoolState = Symbol('poolState'); + +/** @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 */ + minPoolSizeCheckFrequencyMS?: number; +} + +/** @internal */ +export interface WaitQueueMember { + callback: Callback; + timer?: NodeJS.Timeout; + [kCancelled]?: boolean; +} + +/** @internal */ +export const PoolState = Object.freeze({ + paused: 'paused', + ready: 'ready', + closed: 'closed' +} as const); + +/** @public */ +export interface CloseOptions { + force?: boolean; +} + +/** @public */ +export type ConnectionPoolEvents = { + connectionPoolCreated(event: ConnectionPoolCreatedEvent): void; + connectionPoolReady(event: ConnectionPoolReadyEvent): 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 { + options: Readonly; + [kPoolState]: typeof PoolState[keyof typeof PoolState]; + [kServer]: Server; + [kConnections]: List; + [kPending]: number; + [kCheckedOut]: Set; + [kMinPoolSizeTimer]?: NodeJS.Timeout; + /** + * An integer representing the SDAM generation of the pool + */ + [kGeneration]: number; + /** + * A map of generations to service ids + */ + [kServiceGenerations]: Map; + [kConnectionCounter]: Generator; + [kCancellationToken]: CancellationToken; + [kWaitQueue]: List; + [kMetrics]: ConnectionPoolMetrics; + [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 each time the connection pool is marked ready + * @event + */ + static readonly CONNECTION_POOL_READY = CONNECTION_POOL_READY; + /** + * 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; + + constructor(server: Server, options: ConnectionPoolOptions) { + super(); + + 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, + minPoolSizeCheckFrequencyMS: options.minPoolSizeCheckFrequencyMS ?? 100, + 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[kPoolState] = PoolState.paused; + this[kServer] = server; + this[kConnections] = new List(); + this[kPending] = 0; + this[kCheckedOut] = new Set(); + 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 List(); + this[kMetrics] = new ConnectionPoolMetrics(); + this[kProcessingWaitQueue] = false; + + process.nextTick(() => { + this.emit(ConnectionPool.CONNECTION_POOL_CREATED, new ConnectionPoolCreatedEvent(this)); + }); + } + + /** The address of the endpoint the pool is connected to */ + get address(): string { + return this.options.hostAddress.toString(); + } + + /** + * Check if the pool has been closed + * + * TODO(NODE-3263): We can remove this property once shell no longer needs it + */ + get closed(): boolean { + return this[kPoolState] === PoolState.closed; + } + + /** 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].size; + } + + get waitQueueSize(): number { + return this[kWaitQueue].length; + } + + get loadBalanced(): boolean { + return this.options.loadBalanced; + } + + get serviceGenerations(): Map { + return this[kServiceGenerations]; + } + + get serverError() { + return this[kServer].description.error; + } + + /** + * This is exposed ONLY for use in mongosh, to enable + * killing all connections if a user quits the shell with + * operations in progress. + * + * This property may be removed as a part of NODE-3263. + */ + get checkedOutConnections() { + return this[kCheckedOut]; + } + + /** + * Get the metrics information for the pool when a wait queue timeout occurs. + */ + private waitQueueErrorMetrics(): string { + return this[kMetrics].info(this.options.maxPoolSize); + } + + /** + * Set the pool state to "ready" + */ + ready(): void { + if (this[kPoolState] !== PoolState.paused) { + return; + } + this[kPoolState] = PoolState.ready; + this.emit(ConnectionPool.CONNECTION_POOL_READY, new ConnectionPoolReadyEvent(this)); + clearTimeout(this[kMinPoolSizeTimer]); + this.ensureMinPoolSize(); + } + + /** + * 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) + ); + + 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(() => this.processWaitQueue()); + } + + /** + * Check a connection into the pool. + * + * @param connection - The connection to check in + */ + checkIn(connection: Connection): void { + if (!this[kCheckedOut].has(connection)) { + return; + } + const poolClosed = this.closed; + const stale = this.connectionIsStale(connection); + const willDestroy = !!(poolClosed || stale || connection.closed); + + if (!willDestroy) { + connection.markAvailable(); + this[kConnections].unshift(connection); + } + + this[kCheckedOut].delete(connection); + this.emit(ConnectionPool.CONNECTION_CHECKED_IN, new ConnectionCheckedInEvent(this, connection)); + + if (willDestroy) { + const reason = connection.closed ? 'error' : poolClosed ? 'poolClosed' : 'stale'; + this.destroyConnection(connection, reason); + } + + process.nextTick(() => this.processWaitQueue()); + } + + /** + * 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(options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {}): void { + if (this.closed) { + return; + } + + // handle load balanced case + if (this.loadBalanced) { + const { serviceId } = options; + if (!serviceId) { + throw new MongoRuntimeError( + 'ConnectionPool.clear() called in load balanced mode with no 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) { + 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); + } + this.emit( + ConnectionPool.CONNECTION_POOL_CLEARED, + new ConnectionPoolClearedEvent(this, { serviceId }) + ); + return; + } + // handle non load-balanced case + const interruptInUseConnections = options.interruptInUseConnections ?? false; + const oldGeneration = this[kGeneration]; + this[kGeneration] += 1; + const alreadyPaused = this[kPoolState] === PoolState.paused; + this[kPoolState] = PoolState.paused; + + this.clearMinPoolSizeTimer(); + if (!alreadyPaused) { + this.emit( + ConnectionPool.CONNECTION_POOL_CLEARED, + new ConnectionPoolClearedEvent(this, { interruptInUseConnections }) + ); + } + + if (interruptInUseConnections) { + process.nextTick(() => this.interruptInUseConnections(oldGeneration)); + } + + this.processWaitQueue(); + } + + /** + * Closes all stale in-use connections in the pool with a resumable PoolClearedOnNetworkError. + * + * Only connections where `connection.generation <= minGeneration` are killed. + */ + private interruptInUseConnections(minGeneration: number) { + for (const connection of this[kCheckedOut]) { + if (connection.generation <= minGeneration) { + this.checkIn(connection); + connection.onError(new PoolClearedOnNetworkError(this)); + } + } + } + + /** 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'); + + // end the connection counter + if (typeof this[kConnectionCounter].return === 'function') { + this[kConnectionCounter].return(undefined); + } + + this[kPoolState] = PoolState.closed; + this.clearMinPoolSizeTimer(); + this.processWaitQueue(); + + 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); + } + }); + }); + } + + /** Clear the min pool size timer */ + private clearMinPoolSizeTimer(): void { + const minPoolSizeTimer = this[kMinPoolSizeTimer]; + if (minPoolSizeTimer) { + clearTimeout(minPoolSizeTimer); + } + } + + private destroyConnection(connection: Connection, reason: string) { + this.emit( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, connection, reason) + ); + // destroy the connection + process.nextTick(() => connection.destroy()); + } + + private connectionIsStale(connection: Connection) { + const serviceId = connection.serviceId; + if (this.loadBalanced && serviceId) { + const sid = serviceId.toHexString(); + const generation = this.serviceGenerations.get(sid); + return connection.generation !== generation; + } + + return connection.generation !== this[kGeneration]; + } + + private connectionIsIdle(connection: Connection) { + return !!(this.options.maxIdleTimeMS && connection.idleTime > this.options.maxIdleTimeMS); + } + + /** + * Destroys a connection if the connection is perished. + * + * @returns `true` if the connection was destroyed, `false` otherwise. + */ + private destroyConnectionIfPerished(connection: Connection): boolean { + const isStale = this.connectionIsStale(connection); + const isIdle = this.connectionIsIdle(connection); + if (!isStale && !isIdle && !connection.closed) { + return false; + } + const reason = connection.closed ? 'error' : isStale ? 'stale' : 'idle'; + this.destroyConnection(connection, reason); + return true; + } + + private createConnection(callback: Callback) { + const connectOptions: ConnectionOptions = { + ...this.options, + id: this[kConnectionCounter].next().value, + generation: this[kGeneration], + cancellationToken: this[kCancellationToken] + }; + + this[kPending]++; + // This is our version of a "virtual" no-I/O connection as the spec requires + this.emit( + ConnectionPool.CONNECTION_CREATED, + new ConnectionCreatedEvent(this, { id: connectOptions.id }) + ); + + connect(connectOptions, (err, connection) => { + if (err || !connection) { + this[kPending]--; + this.emit( + ConnectionPool.CONNECTION_CLOSED, + new ConnectionClosedEvent(this, { id: connectOptions.id, serviceId: undefined }, 'error') + ); + if (err instanceof MongoNetworkError || err instanceof MongoServerError) { + err.connectionGeneration = connectOptions.generation; + } + callback(err ?? new MongoRuntimeError('Connection creation failed without error')); + return; + } + + // The pool might have closed since we started trying to create a connection + if (this[kPoolState] !== PoolState.ready) { + this[kPending]--; + connection.destroy({ force: true }); + callback(this.closed ? new PoolClosedError(this) : new PoolClearedError(this)); + 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) => this.emit(event, e)); + } + + if (this.loadBalanced) { + connection.on(Connection.PINNED, pinType => this[kMetrics].markPinned(pinType)); + connection.on(Connection.UNPINNED, pinType => this[kMetrics].markUnpinned(pinType)); + + const serviceId = connection.serviceId; + if (serviceId) { + let generation; + const sid = serviceId.toHexString(); + if ((generation = this.serviceGenerations.get(sid))) { + connection.generation = generation; + } else { + this.serviceGenerations.set(sid, 0); + connection.generation = 0; + } + } + } + + connection.markAvailable(); + this.emit(ConnectionPool.CONNECTION_READY, new ConnectionReadyEvent(this, connection)); + + this[kPending]--; + callback(undefined, connection); + return; + }); + } + + private ensureMinPoolSize() { + const minPoolSize = this.options.minPoolSize; + if (this[kPoolState] !== PoolState.ready || minPoolSize === 0) { + return; + } + + this[kConnections].prune(connection => this.destroyConnectionIfPerished(connection)); + + if ( + this.totalConnectionCount < minPoolSize && + this.pendingConnectionCount < this.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 + this.createConnection((err, connection) => { + if (err) { + this[kServer].handleError(err); + } + if (!err && connection) { + this[kConnections].push(connection); + process.nextTick(() => this.processWaitQueue()); + } + if (this[kPoolState] === PoolState.ready) { + clearTimeout(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = setTimeout( + () => this.ensureMinPoolSize(), + this.options.minPoolSizeCheckFrequencyMS + ); + } + }); + } else { + clearTimeout(this[kMinPoolSizeTimer]); + this[kMinPoolSizeTimer] = setTimeout( + () => this.ensureMinPoolSize(), + this.options.minPoolSizeCheckFrequencyMS + ); + } + } + + private processWaitQueue() { + if (this[kProcessingWaitQueue]) { + return; + } + this[kProcessingWaitQueue] = true; + + while (this.waitQueueSize) { + const waitQueueMember = this[kWaitQueue].first(); + if (!waitQueueMember) { + this[kWaitQueue].shift(); + continue; + } + + if (waitQueueMember[kCancelled]) { + this[kWaitQueue].shift(); + continue; + } + + if (this[kPoolState] !== PoolState.ready) { + const reason = this.closed ? 'poolClosed' : 'connectionError'; + const error = this.closed ? new PoolClosedError(this) : new PoolClearedError(this); + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, reason) + ); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + this[kWaitQueue].shift(); + waitQueueMember.callback(error); + continue; + } + + if (!this.availableConnectionCount) { + break; + } + + const connection = this[kConnections].shift(); + if (!connection) { + break; + } + + if (!this.destroyConnectionIfPerished(connection)) { + this[kCheckedOut].add(connection); + this.emit( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(this, connection) + ); + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + + this[kWaitQueue].shift(); + waitQueueMember.callback(undefined, connection); + } + } + + const { maxPoolSize, maxConnecting } = this.options; + while ( + this.waitQueueSize > 0 && + this.pendingConnectionCount < maxConnecting && + (maxPoolSize === 0 || this.totalConnectionCount < maxPoolSize) + ) { + const waitQueueMember = this[kWaitQueue].shift(); + if (!waitQueueMember || waitQueueMember[kCancelled]) { + continue; + } + this.createConnection((err, connection) => { + if (waitQueueMember[kCancelled]) { + if (!err && connection) { + this[kConnections].push(connection); + } + } else { + if (err) { + this.emit( + ConnectionPool.CONNECTION_CHECK_OUT_FAILED, + new ConnectionCheckOutFailedEvent(this, 'connectionError') + ); + } else if (connection) { + this[kCheckedOut].add(connection); + this.emit( + ConnectionPool.CONNECTION_CHECKED_OUT, + new ConnectionCheckedOutEvent(this, connection) + ); + } + + if (waitQueueMember.timer) { + clearTimeout(waitQueueMember.timer); + } + waitQueueMember.callback(err, connection); + } + process.nextTick(() => this.processWaitQueue()); + }); + } + this[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/2_PAC/node_modules/mongodb/src/cmap/connection_pool_events.ts b/2_PAC/node_modules/mongodb/src/cmap/connection_pool_events.ts new file mode 100644 index 00000000..0f56bf6b --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/connection_pool_events.ts @@ -0,0 +1,201 @@ +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 ready + * @public + * @category Event + */ +export class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent { + /** @internal */ + constructor(pool: ConnectionPool) { + super(pool); + } +} + +/** + * 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: Pick, + 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; + + interruptInUseConnections?: boolean; + + /** @internal */ + constructor( + pool: ConnectionPool, + options: { serviceId?: ObjectId; interruptInUseConnections?: boolean } = {} + ) { + super(pool); + this.serviceId = options.serviceId; + this.interruptInUseConnections = options.interruptInUseConnections; + } +} diff --git a/2_PAC/node_modules/mongodb/src/cmap/errors.ts b/2_PAC/node_modules/mongodb/src/cmap/errors.ts new file mode 100644 index 00000000..f6d2ed58 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/errors.ts @@ -0,0 +1,75 @@ +import { MongoDriverError, MongoErrorLabel, MongoNetworkError } 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 indicating a connection pool is currently paused + * @category Error + */ +export class PoolClearedError extends MongoNetworkError { + /** The address of the connection pool */ + address: string; + + constructor(pool: ConnectionPool, message?: string) { + const errorMessage = message + ? message + : `Connection pool for ${pool.address} was cleared because another operation failed with: "${pool.serverError?.message}"`; + super(errorMessage); + this.address = pool.address; + + this.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + + override get name(): string { + return 'MongoPoolClearedError'; + } +} + +/** + * An error indicating that a connection pool has been cleared after the monitor for that server timed out. + * @category Error + */ +export class PoolClearedOnNetworkError extends PoolClearedError { + constructor(pool: ConnectionPool) { + super(pool, `Connection to ${pool.address} interrupted due to server monitor timeout`); + } + + override get name(): string { + return 'PoolClearedOnNetworkError'; + } +} + +/** + * 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/2_PAC/node_modules/mongodb/src/cmap/message_stream.ts b/2_PAC/node_modules/mongodb/src/cmap/message_stream.ts new file mode 100644 index 00000000..409e9997 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/message_stream.ts @@ -0,0 +1,230 @@ +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, 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; + 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 { + const agreedCompressor = operationDescription.agreedCompressor ?? 'none'; + if (agreedCompressor === '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); + + const options = { + agreedCompressor, + zlibCompressionLevel: operationDescription.zlibCompressionLevel ?? 0 + }; + // Compress the message body + compress(options, messageToBeCompressed).then( + compressedMessage => { + // 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[agreedCompressor], 8); // compressorID + this.push(Buffer.concat([msgHeader, compressionDetails, compressedMessage])); + }, + error => { + operationDescription.cb(error); + } + ); + } +} + +// 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.query; + const commandName = Object.keys(commandDoc)[0]; + return !uncompressibleCommands.has(commandName); +} + +function processIncomingData(stream: MessageStream, callback: Callback): void { + const buffer = stream[kBuffer]; + const sizeOfMessage = buffer.getInt32(); + + if (sizeOfMessage == null) { + return callback(); + } + + if (sizeOfMessage < 0) { + return callback(new MongoParseError(`Invalid message size: ${sizeOfMessage}`)); + } + + if (sizeOfMessage > stream.maxBsonMessageSize) { + return callback( + new MongoParseError( + `Invalid message size: ${sizeOfMessage}, max allowed: ${stream.maxBsonMessageSize}` + ) + ); + } + + if (sizeOfMessage > buffer.length) { + return callback(); + } + + 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? + const sizeOfMessage = buffer.getInt32(); + if (sizeOfMessage != null && sizeOfMessage <= buffer.length) { + return true; + } + } + return false; + }; + + let ResponseType = messageHeader.opCode === OP_MSG ? BinMsg : Response; + if (messageHeader.opCode !== OP_COMPRESSED) { + const messageBody = message.subarray(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()) { + return processIncomingData(stream, callback); + } + + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + + if (buffer.length >= 4) { + return processIncomingData(stream, callback); + } + return callback(); + } + + 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 === OP_MSG ? BinMsg : Response; + decompress(compressorID, compressedBuffer).then( + messageBody => { + if (messageBody.length !== messageHeader.length) { + return callback( + new MongoDecompressionError('Message body and message header must be the same length') + ); + } + + // 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()) { + return processIncomingData(stream, callback); + } + stream.emit('message', new ResponseType(message, messageHeader, messageBody)); + + if (buffer.length >= 4) { + return processIncomingData(stream, callback); + } + return callback(); + }, + error => { + return callback(error); + } + ); +} diff --git a/2_PAC/node_modules/mongodb/src/cmap/metrics.ts b/2_PAC/node_modules/mongodb/src/cmap/metrics.ts new file mode 100644 index 00000000..b825b539 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cmap/stream_description.ts b/2_PAC/node_modules/mongodb/src/cmap/stream_description.ts new file mode 100644 index 00000000..c5fbec0f --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cmap/wire_protocol/compression.ts b/2_PAC/node_modules/mongodb/src/cmap/wire_protocol/compression.ts new file mode 100644 index 00000000..090c42e9 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/wire_protocol/compression.ts @@ -0,0 +1,104 @@ +import { promisify } from 'util'; +import * as zlib from 'zlib'; + +import { LEGACY_HELLO_COMMAND } from '../../constants'; +import { Snappy, ZStandard } from '../../deps'; +import { MongoDecompressionError, MongoInvalidArgumentError } from '../../error'; + +/** @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 ZSTD_COMPRESSION_LEVEL = 3; + +const zlibInflate = promisify(zlib.inflate.bind(zlib)); +const zlibDeflate = promisify(zlib.deflate.bind(zlib)); + +// Facilitate compressing a message using an agreed compressor +export async function compress( + options: { zlibCompressionLevel: number; agreedCompressor: CompressorName }, + dataToBeCompressed: Buffer +): Promise { + const zlibOptions = {} as zlib.ZlibOptions; + switch (options.agreedCompressor) { + case 'snappy': + if ('kModuleError' in Snappy) { + throw Snappy['kModuleError']; + } + return Snappy.compress(dataToBeCompressed); + + case 'zstd': + if ('kModuleError' in ZStandard) { + throw ZStandard['kModuleError']; + } + return ZStandard.compress(dataToBeCompressed, ZSTD_COMPRESSION_LEVEL); + + case 'zlib': + if (options.zlibCompressionLevel) { + zlibOptions.level = options.zlibCompressionLevel; + } + return zlibDeflate(dataToBeCompressed, zlibOptions); + + default: + throw new MongoInvalidArgumentError( + `Unknown compressor ${options.agreedCompressor} failed to compress` + ); + } +} + +// Decompress a message using the given compressor +export async function decompress(compressorID: number, compressedData: Buffer): Promise { + if ( + compressorID !== Compressor.snappy && + compressorID !== Compressor.zstd && + compressorID !== Compressor.zlib && + compressorID !== Compressor.none + ) { + throw new MongoDecompressionError( + `Server sent message compressed using an unsupported compressor. (Received compressor ID ${compressorID})` + ); + } + + switch (compressorID) { + case Compressor.snappy: + if ('kModuleError' in Snappy) { + throw Snappy['kModuleError']; + } + return Snappy.uncompress(compressedData, { asBuffer: true }); + + case Compressor.zstd: + if ('kModuleError' in ZStandard) { + throw ZStandard['kModuleError']; + } + return ZStandard.decompress(compressedData); + + case Compressor.zlib: + return zlibInflate(compressedData); + + default: + return compressedData; + } +} diff --git a/2_PAC/node_modules/mongodb/src/cmap/wire_protocol/constants.ts b/2_PAC/node_modules/mongodb/src/cmap/wire_protocol/constants.ts new file mode 100644 index 00000000..75c26d7f --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cmap/wire_protocol/constants.ts @@ -0,0 +1,11 @@ +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_DELETE = 2006; +export const OP_COMPRESSED = 2012; +export const OP_MSG = 2013; diff --git a/2_PAC/node_modules/mongodb/src/cmap/wire_protocol/shared.ts b/2_PAC/node_modules/mongodb/src/cmap/wire_protocol/shared.ts new file mode 100644 index 00000000..bc13ff6d --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/collection.ts b/2_PAC/node_modules/mongodb/src/collection.ts new file mode 100644 index 00000000..afd15e5a --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/collection.ts @@ -0,0 +1,983 @@ +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 { 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 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 { + checkCollectionName, + DEFAULT_PK_FACTORY, + MongoDBNamespace, + normalizeHintField, + resolveOptions +} from './utils'; +import { WriteConcern, WriteConcernOptions } from './write_concern'; + +/** + * @public + * @deprecated This type will be completely removed in 5.0 and findOneAndUpdate, + * findOneAndDelete, and findOneAndReplace will then return the + * actual result document. + */ +export interface ModifyResult { + value: WithId | null; + lastErrorObject?: Document; + ok: 0 | 1; +} + +/** @public */ +export interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions { + /** 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/find/update/delete and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @public + * + * @example + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const pets = client.db().collection('pets'); + * + * const petCursor = pets.find(); + * + * for await (const pet of petCursor) { + * console.log(`${pet.name} is a ${pet.kind}!`); + * } + * ``` + */ +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 + */ + async insertOne( + doc: OptionalUnlessRequiredId, + options?: InsertOneOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new InsertOneOperation( + this as TODO_NODE_3286, + doc, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async insertMany( + docs: OptionalUnlessRequiredId[], + options?: BulkWriteOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new InsertManyOperation( + this as TODO_NODE_3286, + docs, + resolveOptions(this, options ?? { ordered: true }) + ) as TODO_NODE_3286 + ); + } + + /** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * - `insertOne` + * - `replaceOne` + * - `updateOne` + * - `updateMany` + * - `deleteOne` + * - `deleteMany` + * + * 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 + * @throws MongoDriverError if operations is not an array + */ + async bulkWrite( + operations: AnyBulkWriteOperation[], + options?: BulkWriteOptions + ): Promise { + 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 ?? { ordered: true }) + ) + ); + } + + /** + * 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 + */ + async updateOne( + filter: Filter, + update: UpdateFilter | Partial, + options?: UpdateOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new UpdateOneOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async replaceOne( + filter: Filter, + replacement: WithoutId, + options?: ReplaceOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new ReplaceOneOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ) + ); + } + + /** + * 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 + */ + async updateMany( + filter: Filter, + update: UpdateFilter, + options?: UpdateOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new UpdateManyOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * Delete a document from a collection + * + * @param filter - The filter used to select the document to remove + * @param options - Optional settings for the command + */ + async deleteOne( + filter: Filter = {}, + options: DeleteOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new DeleteOneOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * Delete multiple documents from a collection + * + * @param filter - The filter used to select the documents to remove + * @param options - Optional settings for the command + */ + async deleteMany( + filter: Filter = {}, + options: DeleteOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new DeleteManyOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async rename(newName: string, options?: RenameOptions): Promise { + // 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 + }) as TODO_NODE_3286 + ); + } + + /** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @param options - Optional settings for the command + */ + async drop(options?: DropCollectionOptions): Promise { + return executeOperation( + this.s.db.s.client, + new DropCollectionOperation(this.s.db, this.collectionName, options) + ); + } + + /** + * Fetches the first document that matches the filter + * + * @param filter - Query for find Operation + * @param options - Optional settings for the command + */ + async findOne(): Promise | null>; + async findOne(filter: Filter): Promise | null>; + async findOne(filter: Filter, options: FindOptions): Promise | null>; + + // allow an override of the schema. + async findOne(): Promise; + async findOne(filter: Filter): Promise; + async findOne(filter: Filter, options?: FindOptions): Promise; + + async findOne( + filter: Filter = {}, + options: FindOptions = {} + ): Promise | null> { + return this.find(filter, options).limit(-1).batchSize(1).next(); + } + + /** + * 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> { + 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 + */ + async options(options?: OperationOptions): Promise { + return executeOperation( + this.s.db.s.client, + new OptionsOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * Returns if the collection is a capped collection + * + * @param options - Optional settings for the command + */ + async isCapped(options?: OperationOptions): Promise { + return executeOperation( + this.s.db.s.client, + new IsCappedOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * 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 + * + * @example + * ```ts + * 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' }]) + * ``` + */ + async createIndex( + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new CreateIndexOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpec, + resolveOptions(this, options) + ) + ); + } + + /** + * 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 + * + * @example + * ```ts + * 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' + * } + * ]); + * ``` + */ + async createIndexes( + indexSpecs: IndexDescription[], + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new CreateIndexesOperation( + this as TODO_NODE_3286, + this.collectionName, + indexSpecs, + resolveOptions(this, { ...options, maxTimeMS: undefined }) + ) + ); + } + + /** + * Drops an index from this collection. + * + * @param indexName - Name of the index to drop. + * @param options - Optional settings for the command + */ + async dropIndex(indexName: string, options?: DropIndexesOptions): Promise { + return executeOperation( + this.s.db.s.client, + new DropIndexOperation(this as TODO_NODE_3286, indexName, { + ...resolveOptions(this, options), + readPreference: ReadPreference.primary + }) + ); + } + + /** + * Drops all indexes from this collection. + * + * @param options - Optional settings for the command + */ + async dropIndexes(options?: DropIndexesOptions): Promise { + return executeOperation( + this.s.db.s.client, + new DropIndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async indexExists( + indexes: string | string[], + options?: IndexInformationOptions + ): Promise { + return executeOperation( + this.s.db.s.client, + new IndexExistsOperation(this as TODO_NODE_3286, indexes, resolveOptions(this, options)) + ); + } + + /** + * Retrieves this collections index info. + * + * @param options - Optional settings for the command + */ + async indexInformation(options?: IndexInformationOptions): Promise { + return executeOperation( + this.s.db.s.client, + new IndexInformationOperation(this.s.db, this.collectionName, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise { + return executeOperation( + this.s.db.s.client, + new EstimatedDocumentCountOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * 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 + * + * @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 + */ + async countDocuments( + filter: Document = {}, + options: CountDocumentsOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new CountDocumentsOperation(this as TODO_NODE_3286, filter, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + distinct>( + key: Key + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter + ): Promise[Key]>>>; + distinct>( + key: Key, + filter: Filter, + options: DistinctOptions + ): Promise[Key]>>>; + + // Embedded documents overload + distinct(key: string): Promise; + distinct(key: string, filter: Filter): Promise; + distinct(key: string, filter: Filter, options: DistinctOptions): Promise; + + async distinct>( + key: Key, + filter: Filter = {}, + options: DistinctOptions = {} + ): Promise { + return executeOperation( + this.s.db.s.client, + new DistinctOperation( + this as TODO_NODE_3286, + key as TODO_NODE_3286, + filter, + resolveOptions(this, options) + ) + ); + } + + /** + * Retrieve all the indexes on the collection. + * + * @param options - Optional settings for the command + */ + async indexes(options?: IndexInformationOptions): Promise { + return executeOperation( + this.s.db.s.client, + new IndexesOperation(this as TODO_NODE_3286, resolveOptions(this, options)) + ); + } + + /** + * Get all the collection statistics. + * + * @param options - Optional settings for the command + */ + async stats(options?: CollStatsOptions): Promise { + return executeOperation( + this.s.db.s.client, + new CollStatsOperation(this as TODO_NODE_3286, options) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async findOneAndDelete( + filter: Filter, + options?: FindOneAndDeleteOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new FindOneAndDeleteOperation( + this as TODO_NODE_3286, + filter, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async findOneAndReplace( + filter: Filter, + replacement: WithoutId, + options?: FindOneAndReplaceOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new FindOneAndReplaceOperation( + this as TODO_NODE_3286, + filter, + replacement, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async findOneAndUpdate( + filter: Filter, + update: UpdateFilter, + options?: FindOneAndUpdateOptions + ): Promise> { + return executeOperation( + this.s.db.s.client, + new FindOneAndUpdateOperation( + this as TODO_NODE_3286, + filter, + update, + resolveOptions(this, options) + ) as TODO_NODE_3286 + ); + } + + /** + * 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 (!Array.isArray(pipeline)) { + throw new MongoInvalidArgumentError( + 'Argument "pipeline" must be an array of aggregation stages' + ); + } + + 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 use cases: + * - 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)); + } + + /** + * 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 implementation. + * 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 implementation. + * 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)); + } + + /** + * 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 + */ + async count(filter: Filter = {}, options: CountOptions = {}): Promise { + return executeOperation( + this.s.db.s.client, + new CountOperation( + MongoDBNamespace.fromString(this.namespace), + filter, + resolveOptions(this, options) + ) + ); + } +} diff --git a/2_PAC/node_modules/mongodb/src/connection_string.ts b/2_PAC/node_modules/mongodb/src/connection_string.ts new file mode 100644 index 00000000..d18bbf0e --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/connection_string.ts @@ -0,0 +1,1279 @@ +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, + MongoMissingCredentialsError, + MongoParseError +} from './error'; +import { + DriverInfo, + MongoClient, + MongoClientOptions, + MongoOptions, + PkFactory, + ServerApi, + ServerApiVersion +} from './mongo_client'; +import { MongoLogger, MongoLoggerEnvOptions, MongoLoggerMongoClientOptions } from './mongo_logger'; +import { ReadConcern, ReadConcernLevel } from './read_concern'; +import { ReadPreference, ReadPreferenceMode } from './read_preference'; +import type { TagSet } from './sdam/server_description'; +import { + DEFAULT_PK_FACTORY, + emitWarning, + emitWarningOnce, + HostAddress, + isRecord, + makeClientMetadata, + parseInteger, + 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 async function resolveSRVRecord(options: MongoOptions): Promise { + if (typeof options.srvHost !== 'string') { + throw new MongoAPIError('Option "srvHost" must not be empty'); + } + + if (options.srvHost.split('.').length < 3) { + // TODO(NODE-3484): Replace with MongoConnectionStringError + throw 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; + const addresses = await dns.promises.resolveSrv( + `_${options.srvServiceName}._tcp.${lookupAddress}` + ); + + if (addresses.length === 0) { + throw new MongoAPIError('No addresses found at host'); + } + + for (const { name } of addresses) { + if (!matchesParentDomain(name, lookupAddress)) { + throw new MongoAPIError('Server record does not share hostname with parent URI'); + } + } + + const hostAddresses = addresses.map(r => HostAddress.fromString(`${r.name}:${r.port ?? 27017}`)); + + validateLoadBalancedOptions(hostAddresses, options, true); + + // Resolve TXT record and add options from there if they exist. + let record; + try { + record = await dns.promises.resolveTxt(lookupAddress); + } catch (error) { + if (error.code !== 'ENODATA' && error.code !== 'ENOTFOUND') { + throw error; + } + return hostAddresses; + } + + if (record.length > 1) { + throw 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))) { + throw new MongoParseError(`Text record may only set any of: ${VALID_TXT_RECORDS.join(', ')}`); + } + + if (VALID_TXT_RECORDS.some(option => txtRecordOptions.get(option) === '')) { + throw 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) { + throw new MongoParseError('Cannot combine replicaSet option with srvMaxHosts'); + } + + validateLoadBalancedOptions(hostAddresses, options, true); + + return hostAddresses; +} + +/** + * Checks if TLS options are valid + * + * @param allOptions - All options provided by user or included in default options map + * @throws MongoAPIError if TLS options are invalid + */ +function checkTLSOptions(allOptions: CaseInsensitiveMap): void { + if (!allOptions) return; + const check = (a: string, b: string) => { + if (allOptions.has(a) && allOptions.has(b)) { + throw new MongoAPIError(`The '${a}' option cannot be used with the '${b}' option`); + } + }; + 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 getIntFromOptions(name: string, value: unknown): number { + const parsedInt = parseInteger(value); + if (parsedInt != null) { + return parsedInt; + } + throw new MongoParseError(`Expected ${name} to be stringified int value, got: ${value}`); +} + +function getUIntFromOptions(name: string, value: unknown): number { + const parsedValue = getIntFromOptions(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.'); + } + } + + checkTLSOptions(allOptions); + + 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 + }); + } + + if (isAws && mongoOptions.credentials.username && !mongoOptions.credentials.password) { + throw new MongoMissingCredentialsError( + `When using ${mongoOptions.credentials.mechanism} password must be set when a username is specified` + ); + } + + 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'; + } + + validateLoadBalancedOptions(hosts, mongoOptions, isSRV); + + 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' + ); + } + + const loggerFeatureFlag = Symbol.for('@@mdb.enableMongoLogger'); + mongoOptions[loggerFeatureFlag] = mongoOptions[loggerFeatureFlag] ?? false; + + let loggerEnvOptions: MongoLoggerEnvOptions = {}; + let loggerClientOptions: MongoLoggerMongoClientOptions = {}; + if (mongoOptions[loggerFeatureFlag]) { + loggerEnvOptions = { + MONGODB_LOG_COMMAND: process.env.MONGODB_LOG_COMMAND, + MONGODB_LOG_TOPOLOGY: process.env.MONGODB_LOG_TOPOLOGY, + MONGODB_LOG_SERVER_SELECTION: process.env.MONGODB_LOG_SERVER_SELECTION, + MONGODB_LOG_CONNECTION: process.env.MONGODB_LOG_CONNECTION, + MONGODB_LOG_ALL: process.env.MONGODB_LOG_ALL, + MONGODB_LOG_MAX_DOCUMENT_LENGTH: process.env.MONGODB_LOG_MAX_DOCUMENT_LENGTH, + MONGODB_LOG_PATH: process.env.MONGODB_LOG_PATH + }; + loggerClientOptions = { + mongodbLogPath: mongoOptions.mongodbLogPath + }; + } + mongoOptions.mongoLoggerOptions = MongoLogger.resolveOptions( + loggerEnvOptions, + loggerClientOptions + ); + + return mongoOptions; +} + +/** + * #### Throws if LB mode is true: + * - hosts contains more than one host + * - there is a replicaSet name set + * - directConnection is set + * - if srvMaxHosts is used when an srv connection string is passed in + * + * @throws MongoParseError + */ +function validateLoadBalancedOptions( + hosts: HostAddress[] | string[], + mongoOptions: MongoOptions, + isSrv: boolean +): void { + if (mongoOptions.loadBalanced) { + if (hosts.length > 1) { + throw new MongoParseError(LB_SINGLE_HOST_ERROR); + } + if (mongoOptions.replicaSet) { + throw new MongoParseError(LB_REPLICA_SET_ERROR); + } + if (mongoOptions.directConnection) { + throw new MongoParseError(LB_DIRECT_CONNECTION_ERROR); + } + + if (isSrv && mongoOptions.srvMaxHosts > 0) { + throw 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] = getIntFromOptions(name, values[0]); + break; + case 'uint': + mongoOptions[name] = getUIntFromOptions(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 = getIntFromOptions(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' + }, + maxConnecting: { + default: 2, + transform({ name, values: [value] }): number { + const maxConnecting = getUIntFromOptions(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 = getUIntFromOptions(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}` + ); + } + }, + 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)}`); + } + }, + wtimeout: { + deprecated: 'Please use wtimeoutMS instead', + target: 'writeConcern', + transform({ values: [value], options }) { + const wc = WriteConcern.fromOptions({ + writeConcern: { + ...options.writeConcern, + wtimeout: getUIntFromOptions('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: getUIntFromOptions('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'), + Symbol.for('@@mdb.enableMongoLogger') +]); diff --git a/2_PAC/node_modules/mongodb/src/constants.ts b/2_PAC/node_modules/mongodb/src/constants.ts new file mode 100644 index 00000000..eec4b075 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/constants.ts @@ -0,0 +1,136 @@ +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_POOL_READY = 'connectionPoolReady' 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_READY, + CONNECTION_POOL_CLEARED, + CONNECTION_POOL_CLOSED, + CONNECTION_CREATED, + CONNECTION_READY, + CONNECTION_CLOSED, + CONNECTION_CHECK_OUT_STARTED, + CONNECTION_CHECK_OUT_FAILED, + CONNECTION_CHECKED_OUT, + CONNECTION_CHECKED_IN +] 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/2_PAC/node_modules/mongodb/src/cursor/abstract_cursor.ts b/2_PAC/node_modules/mongodb/src/cursor/abstract_cursor.ts new file mode 100644 index 00000000..2d9ec01a --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cursor/abstract_cursor.ts @@ -0,0 +1,920 @@ +import { Readable, Transform } from 'stream'; +import { promisify } from 'util'; + +import { BSONSerializeOptions, Document, Long, pluckBSONSerializeOptions } from '../bson'; +import { + AnyError, + MongoAPIError, + 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, List, 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 */ +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; + /** + * Specifies the number of documents to return in each response from MongoDB + */ + batchSize?: number; + /** + * When applicable `maxTimeMS` controls the amount of time the initial command + * that constructs a cursor should take. (ex. find, aggregate, listCollections) + */ + maxTimeMS?: number; + /** + * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores + * that a cursor uses to fetch more data should take. (ex. cursor.next()) + */ + 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; + /** + * By default, MongoDB will automatically close a cursor when the + * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections) + * you may use a Tailable Cursor that remains open after the client exhausts + * the results in the initial cursor. + */ + tailable?: boolean; + /** + * If awaitData is set to true, when the cursor reaches the end of the capped collection, + * MongoDB blocks the query thread for a period of time waiting for new data to arrive. + * When new data is inserted into the capped collection, the blocked thread is signaled + * to wake up and return the next batch to the client. + */ + 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 | null; + /** @internal */ + [kSession]: ClientSession; + /** @internal */ + [kServer]?: Server; + /** @internal */ + [kNamespace]: MongoDBNamespace; + /** @internal */ + [kDocuments]: List; + /** @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[kId] = null; + this[kDocuments] = new List(); + 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 (typeof options.maxAwaitTimeMS === 'number') { + this[kOptions].maxAwaitTimeMS = options.maxAwaitTimeMS; + } + + 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] ?? undefined; + } + + /** @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[] { + const bufferedDocs: TSchema[] = []; + const documentsToRead = Math.min(number ?? this[kDocuments].length, this[kDocuments].length); + + for (let count = 0; count < documentsToRead; count++) { + const document = this[kDocuments].shift(); + if (document != null) { + bufferedDocs.push(document); + } + } + + return bufferedDocs; + } + + async *[Symbol.asyncIterator](): AsyncGenerator { + if (this.closed) { + return; + } + + try { + while (true) { + const document = await this.next(); + + // Intentional strict null check, because users can map cursors to falsey values. + // We allow mapping to all values except for null. + // eslint-disable-next-line no-restricted-syntax + if (document === null) { + if (!this.closed) { + const message = + 'Cursor returned a `null` document, but the cursor is not exhausted. Mapping documents to `null` is not supported in the cursor transform.'; + + await cleanupCursorAsync(this, { needsToEmitClosed: true }).catch(() => null); + + throw new MongoAPIError(message); + } + break; + } + + yield document; + + if (this[kId] === Long.ZERO) { + // Cursor exhausted + break; + } + } + } finally { + // Only close the cursor if it has not already been closed. This finally clause handles + // the case when a user would break out of a for await of loop early. + if (!this.closed) { + await this.close().catch(() => null); + } + } + } + + 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); + } + + async hasNext(): Promise { + if (this[kId] === Long.ZERO) { + return false; + } + + if (this[kDocuments].length !== 0) { + return true; + } + + const doc = await nextAsync(this, true); + + if (doc) { + this[kDocuments].unshift(doc); + return true; + } + + return false; + } + + /** Get the next available document from the cursor, returns null if no more documents are available. */ + async next(): Promise { + if (this[kId] === Long.ZERO) { + throw new MongoCursorExhaustedError(); + } + + return nextAsync(this, true); + } + + /** + * Try to get the next available document from the cursor or `null` if an empty batch is returned + */ + async tryNext(): Promise { + if (this[kId] === Long.ZERO) { + throw new MongoCursorExhaustedError(); + } + + return nextAsync(this, false); + } + + /** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * + * If the iterator returns `false`, iteration will stop. + * + * @param iterator - The iteration callback. + */ + async forEach(iterator: (doc: TSchema) => boolean | void): Promise { + if (typeof iterator !== 'function') { + throw new MongoInvalidArgumentError('Argument "iterator" must be a function'); + } + for await (const document of this) { + const result = iterator(document); + if (result === false) { + break; + } + } + } + + async close(): Promise { + const needsToEmitClosed = !this[kClosed]; + this[kClosed] = true; + await cleanupCursorAsync(this, { needsToEmitClosed }); + } + + /** + * 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. + */ + async toArray(): Promise { + const array = []; + for await (const document of this) { + array.push(document); + } + return array; + } + + /** + * 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** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping + * function that maps values to `null` will result in the cursor closing itself before it has finished iterating + * all documents. This will **not** result in a memory leak, just surprising behavior. For example: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => null); + * + * const documents = await cursor.toArray(); + * // documents is always [], regardless of how many documents are in the collection. + * ``` + * + * Other falsey values are allowed: + * + * ```typescript + * const cursor = collection.find({}); + * cursor.map(() => ''); + * + * const documents = await cursor.toArray(); + * // documents is now an array of empty strings + * ``` + * + * **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] = null; + this[kDocuments].clear(); + 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 { + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + const getMoreOperation = new GetMoreOperation(this[kNamespace], this[kId]!, this[kServer]!, { + ...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], (error, state) => { + if (state) { + const response = state.response; + this[kServer] = state.server; + + if (response.cursor) { + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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].pushMany(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].push(state.response as TODO_NODE_3286); + } + } + + // the cursor is now initialized, even if an error occurred or it is dead + this[kInitialized] = true; + + if (error) { + return cleanupCursor(this, { error }, () => callback(error, undefined)); + } + + if (cursorIsDead(this)) { + return cleanupCursor(this, undefined, () => callback()); + } + + callback(); + }); + } +} + +function nextDocument(cursor: AbstractCursor): T | null { + const doc = cursor[kDocuments].shift(); + + if (doc && cursor[kTransform]) { + return cursor[kTransform](doc) as T; + } + + return doc; +} + +const nextAsync = promisify( + next as ( + cursor: AbstractCursor, + blocking: boolean, + callback: (e: Error, r: T | null) => void + ) => void +); + +/** + * @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].length !== 0) { + 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 => { + if (err) return callback(err); + 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, (error, response) => { + if (response) { + const cursorId = + typeof response.cursor.id === 'number' + ? Long.fromNumber(response.cursor.id) + : response.cursor.id; + + cursor[kDocuments].pushMany(response.cursor.nextBatch); + cursor[kId] = cursorId; + } + + if (error || cursorIsDead(cursor)) { + return cleanupCursor(cursor, { error }, () => callback(error, 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(); +} + +const cleanupCursorAsync = promisify(cleanupCursor); + +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) { + session.endSession({ error }).finally(() => { + callback(); + }); + return; + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + return callback(); + } + + function completeCleanup() { + if (session) { + if (session.owner === cursor) { + session.endSession({ error }).finally(() => { + cursor.emit(AbstractCursor.CLOSE); + callback(); + }); + return; + } + + if (!session.inTransaction()) { + maybeClearPinnedConnection(session, { error }); + } + } + + cursor.emit(AbstractCursor.CLOSE); + return callback(); + } + + cursor[kKilled] = true; + + executeOperation( + cursor[kClient], + new KillCursorsOperation(cursorId, cursorNs, server, { session }) + ).finally(() => { + completeCleanup(); + }); + return; +} + +/** @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().then( + () => callback(error), + closeError => callback(closeError) + ); + } + + 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 was 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(/operation was interrupted/)) { + return this.push(null); + } + + // NOTE: The two above checks on the message of the error will cause a null to be pushed + // to the stream, thus closing the stream before the destroy call happens. This means + // that either of those error messages on a change stream will not get a proper + // 'error' event to be emitted (the error passed to destroy). Change stream resumability + // relies on that error event to be emitted to create its new cursor and thus was not + // working on 4.4 servers because the error emitted on failover was "interrupted at + // shutdown" while on 5.0+ it is "The server is in quiesce mode and will shut down". + // See NODE-4475. + 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/2_PAC/node_modules/mongodb/src/cursor/aggregation_cursor.ts b/2_PAC/node_modules/mongodb/src/cursor/aggregation_cursor.ts new file mode 100644 index 00000000..f57969d3 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cursor/aggregation_cursor.ts @@ -0,0 +1,208 @@ +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 */ + async explain(verbosity?: ExplainVerbosityLike): Promise { + 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 ?? true + }) + ); + } + + /** 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; + } + + /** Add a geoNear stage to the aggregation pipeline */ + geoNear($geoNear: Document): this { + assertUninitialized(this); + this[kPipeline].push({ $geoNear }); + return this; + } +} diff --git a/2_PAC/node_modules/mongodb/src/cursor/change_stream_cursor.ts b/2_PAC/node_modules/mongodb/src/cursor/change_stream_cursor.ts new file mode 100644 index 00000000..b5a4ae46 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cursor/find_cursor.ts b/2_PAC/node_modules/mongodb/src/cursor/find_cursor.ts new file mode 100644 index 00000000..ff4cd6dd --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/cursor/find_cursor.ts @@ -0,0 +1,456 @@ +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 = {}, + 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) { + this.close().finally(() => callback()); + return; + } + } + + 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 + */ + async count(options?: CountOptions): Promise { + 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'); + } + 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 + }) + ); + } + + /** Execute the explain for the cursor */ + async explain(verbosity?: ExplainVerbosityLike): Promise { + 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 ?? true + }) + ); + } + + /** 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 behavior. + 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/2_PAC/node_modules/mongodb/src/cursor/list_collections_cursor.ts b/2_PAC/node_modules/mongodb/src/cursor/list_collections_cursor.ts new file mode 100644 index 00000000..460126be --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/cursor/list_indexes_cursor.ts b/2_PAC/node_modules/mongodb/src/cursor/list_indexes_cursor.ts new file mode 100644 index 00000000..25336d84 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/db.ts b/2_PAC/node_modules/mongodb/src/db.ts new file mode 100644 index 00000000..67c49dd9 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/db.ts @@ -0,0 +1,523 @@ +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 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 { DEFAULT_PK_FACTORY, filterOptions, 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', + 'promoteBuffers', + 'promoteLongs', + 'bsonRegExp', + 'enableUtf8Validation', + 'promoteValues', + 'compression', + 'retryWrites' +]; + +/** @internal */ +export interface DbPrivate { + client: MongoClient; + options?: DbOptions; + readPreference?: ReadPreference; + pkFactory: PkFactory; + readConcern?: ReadConcern; + bsonOptions: BSONSerializeOptions; + writeConcern?: WriteConcern; + namespace: MongoDBNamespace; +} + +/** @public */ +export interface DbOptions extends BSONSerializeOptions, WriteConcernOptions { + /** 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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * interface Pet { + * name: string; + * kind: 'dog' | 'cat' | 'fish'; + * } + * + * const client = new MongoClient('mongodb://localhost:27017'); + * const db = client.db(); + * + * // Create a collection that validates our union + * await db.createCollection('pets', { + * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } } + * }) + * ``` + */ +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, + // 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; + } + + /** + * 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 + */ + async createCollection( + name: string, + options?: CreateCollectionOptions + ): Promise> { + return executeOperation( + this.s.client, + new CreateCollectionOperation(this, name, resolveOptions(this, options)) 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 + */ + async command(command: Document, options?: RunCommandOptions): Promise { + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation(this.s.client, new RunCommandOperation(this, command, options)); + } + + /** + * 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 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.'); + } + return new Collection(this, name, resolveOptions(this, options)); + } + + /** + * Get all the db statistics. + * + * @param options - Optional settings for the command + */ + async stats(options?: DbStatsOptions): Promise { + return executeOperation( + this.s.client, + new DbStatsOperation(this, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async renameCollection( + fromCollection: string, + toCollection: string, + options?: RenameOptions + ): Promise> { + // Intentionally, we do not inherit options from parent for this operation. + return executeOperation( + this.s.client, + new RenameOperation( + this.collection(fromCollection) as TODO_NODE_3286, + toCollection, + { ...options, new_collection: true, readPreference: ReadPreference.primary } + ) as TODO_NODE_3286 + ); + } + + /** + * 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 + */ + async dropCollection(name: string, options?: DropCollectionOptions): Promise { + return executeOperation( + this.s.client, + new DropCollectionOperation(this, name, resolveOptions(this, options)) + ); + } + + /** + * Drop a database, removing it permanently from the server. + * + * @param options - Optional settings for the command + */ + async dropDatabase(options?: DropDatabaseOptions): Promise { + return executeOperation( + this.s.client, + new DropDatabaseOperation(this, resolveOptions(this, options)) + ); + } + + /** + * Fetch all collections for the current db. + * + * @param options - Optional settings for the command + */ + async collections(options?: ListCollectionsOptions): Promise { + return executeOperation( + this.s.client, + new CollectionsOperation(this, resolveOptions(this, options)) + ); + } + + /** + * 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 + */ + async createIndex( + name: string, + indexSpec: IndexSpecification, + options?: CreateIndexesOptions + ): Promise { + return executeOperation( + this.s.client, + new CreateIndexOperation(this, name, indexSpec, resolveOptions(this, options)) + ); + } + + /** + * Add a user to the database + * + * @param username - The username for the new user + * @param passwordOrOptions - An optional password for the new user, or the options for the command + * @param options - Optional settings for the command + */ + async addUser( + username: string, + passwordOrOptions?: string | AddUserOptions, + options?: AddUserOptions + ): Promise { + options = + options != null && typeof options === 'object' + ? options + : passwordOrOptions != null && typeof passwordOrOptions === 'object' + ? passwordOrOptions + : undefined; + const password = typeof passwordOrOptions === 'string' ? passwordOrOptions : undefined; + return executeOperation( + this.s.client, + new AddUserOperation(this, username, password, resolveOptions(this, options)) + ); + } + + /** + * Remove a user from a database + * + * @param username - The username to remove + * @param options - Optional settings for the command + */ + async removeUser(username: string, options?: RemoveUserOptions): Promise { + return executeOperation( + this.s.client, + new RemoveUserOperation(this, username, resolveOptions(this, options)) + ); + } + + /** + * Set the current profiling level of MongoDB + * + * @param level - The new profiling level (off, slow_only, all). + * @param options - Optional settings for the command + */ + async setProfilingLevel( + level: ProfilingLevel, + options?: SetProfilingLevelOptions + ): Promise { + return executeOperation( + this.s.client, + new SetProfilingLevelOperation(this, level, resolveOptions(this, options)) + ); + } + + /** + * Retrieve the current profiling Level for MongoDB + * + * @param options - Optional settings for the command + */ + async profilingLevel(options?: ProfilingLevelOptions): Promise { + return executeOperation( + this.s.client, + new ProfilingLevelOperation(this, resolveOptions(this, options)) + ); + } + + /** + * Retrieves this collections index info. + * + * @param name - The name of the collection. + * @param options - Optional settings for the command + */ + async indexInformation(name: string, options?: IndexInformationOptions): Promise { + return executeOperation( + this.s.client, + new IndexInformationOperation(this, name, resolveOptions(this, options)) + ); + } + + /** + * 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 use cases: + * - 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)); + } +} + +// 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/2_PAC/node_modules/mongodb/src/deps.ts b/2_PAC/node_modules/mongodb/src/deps.ts new file mode 100644 index 00000000..bb675baa --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/deps.ts @@ -0,0 +1,377 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ +import type { Document } from './bson'; +import type { AWSCredentials } from './cmap/auth/mongodb_aws'; +import type { ProxyOptions } from './cmap/connection'; +import { MongoMissingDependencyError } from './error'; +import type { MongoClient } from './mongo_client'; +import type { Callback } from './utils'; + +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 CredentialProvider = { + fromNodeProviderChain(this: void): () => Promise; +}; + +export function getAwsCredentialProvider(): + | CredentialProvider + | { kModuleError: MongoMissingDependencyError } { + try { + // Ensure you always wrap an optional require in the try block NODE-3199 + const credentialProvider = require('@aws-sdk/credential-providers'); + return credentialProvider; + } catch { + return makeErrorModule( + new MongoMissingDependencyError( + 'Optional module `@aws-sdk/credential-providers` not found.' + + ' Please install it to enable getting aws credentials via the official sdk.' + ) + ); + } +} + +type SnappyLib = { + /** + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + */ + compress(buf: Buffer): Promise; + + /** + * In order to support both we must check the return value of the function + * @param buf - Buffer to be compressed + */ + uncompress(buf: Buffer, opt: { asBuffer: true }): Promise; +}; + +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'); +} 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 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 Field Level 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/2_PAC/node_modules/mongodb/src/encrypter.ts b/2_PAC/node_modules/mongodb/src/encrypter.ts new file mode 100644 index 00000000..d24e0de2 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/encrypter.ts @@ -0,0 +1,131 @@ +/* eslint-disable @typescript-eslint/no-var-requires */ + +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: { new (...args: ConstructorParameters): 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 + }; + } + + 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; + } + + async connectInternalClient(): Promise { + // TODO(NODE-4144): Remove new variable for type narrowing + const internalClient = this[kInternalClient]; + if (this.needsConnecting && internalClient != null) { + this.needsConnecting = false; + await internalClient.connect(); + } + } + + close(client: MongoClient, force: boolean, callback: Callback): void { + this.autoEncrypter.teardown(!!force, e => { + const internalClient = this[kInternalClient]; + if (internalClient != null && client !== internalClient) { + internalClient.close(force).then( + () => callback(), + error => callback(error) + ); + return; + } + callback(e); + }); + } + + static checkForMongoCrypt(): void { + const mongodbClientEncryption = getMongoDBClientEncryption(); + if (mongodbClientEncryption == null) { + throw new MongoMissingDependencyError( + 'Auto-encryption requested, but the module is not installed. ' + + 'Please add `mongodb-client-encryption` as a dependency of your project' + ); + } + AutoEncrypterClass = mongodbClientEncryption.extension(require('../lib/index')).AutoEncrypter; + } +} diff --git a/2_PAC/node_modules/mongodb/src/error.ts b/2_PAC/node_modules/mongodb/src/error.ts new file mode 100644 index 00000000..1dd426cb --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/error.ts @@ -0,0 +1,932 @@ +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', + ResetPool: 'ResetPool', + InterruptInUseConnections: 'InterruptInUseConnections', + NoWritesPerformed: 'NoWritesPerformed' +} 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 + * mongodb-client-encryption 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; + connectionGeneration?: number; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + cause?: Error; // depending on the node version, this may or may not exist on the base + + constructor(message: string | Error) { + if (message instanceof Error) { + super(message.message); + this.cause = 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 + * mongodb-client-encryption 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/2_PAC/node_modules/mongodb/src/explain.ts b/2_PAC/node_modules/mongodb/src/explain.ts new file mode 100644 index 00000000..0d08e694 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/gridfs/download.ts b/2_PAC/node_modules/mongodb/src/gridfs/download.ts new file mode 100644 index 00000000..0053ecc9 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/gridfs/download.ts @@ -0,0 +1,474 @@ +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-indexed non-negative byte offset from the beginning of the file + */ + start?: number; + /** + * 0-indexed non-negative byte offset to the end of the file contents + * to be returned by the stream. `end` is non-inclusive + */ + 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; + + /** + * @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 + * @internal + */ + 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. + */ + async abort(): Promise { + this.push(null); + this.destroyed = true; + if (this.s.cursor) { + try { + await this.s.cursor.close(); + } finally { + this.emit(GridFSBucketReadStream.CLOSE); + } + } else { + if (!this.s.init) { + // If not initialized, fire close event because we will never + // get a cursor + this.emit(GridFSBucketReadStream.CLOSE); + } + } + } +} + +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; + + const handleReadResult = ({ + error, + doc + }: { error: Error; doc: null } | { error: null; doc: any }) => { + if (stream.destroyed) { + return; + } + if (error) { + stream.emit(GridFSBucketReadStream.ERROR, error); + return; + } + if (!doc) { + stream.push(null); + + stream.s.cursor?.close().then( + () => { + stream.emit(GridFSBucketReadStream.CLOSE); + }, + error => { + stream.emit(GridFSBucketReadStream.ERROR, error); + } + ); + 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; + }; + + stream.s.cursor.next().then( + doc => handleReadResult({ error: null, doc }), + error => handleReadResult({ error, doc: null }) + ); +} + +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; + } + + const handleReadResult = ({ + error, + doc + }: { error: Error; doc: null } | { error: null; doc: any }) => { + 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; + }; + + stream.s.files.findOne(stream.s.filter, findOneOptions).then( + doc => handleReadResult({ error: null, doc }), + error => handleReadResult({ error, doc: null }) + ); +} + +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/2_PAC/node_modules/mongodb/src/gridfs/index.ts b/2_PAC/node_modules/mongodb/src/gridfs/index.ts new file mode 100644 index 00000000..8471859a --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/gridfs/index.ts @@ -0,0 +1,209 @@ +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 { Filter, TypedEventEmitter } from '../mongo_types'; +import type { ReadPreference } from '../read_preference'; +import type { Sort } from '../sort'; +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 + */ + async delete(id: ObjectId): Promise { + const { deletedCount } = await this.s._filesCollection.deleteOne({ _id: id }); + + // Delete orphaned chunks before returning FileNotFound + await this.s._chunksCollection.deleteMany({ files_id: id }); + + if (deletedCount === 0) { + // TODO(NODE-3483): Replace with more appropriate error + // Consider creating new error MongoGridFSFileNotFoundError + throw new MongoRuntimeError(`File not found for id ${id}`); + } + } + + /** Convenience wrapper around find on the files collection */ + find(filter: Filter = {}, options: FindOptions = {}): FindCursor { + 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 + */ + async rename(id: ObjectId, filename: string): Promise { + const filter = { _id: id }; + const update = { $set: { filename } }; + const { matchedCount } = await this.s._filesCollection.updateOne(filter, update); + if (matchedCount === 0) { + throw new MongoRuntimeError(`File with id ${id} not found`); + } + } + + /** Removes this bucket's files collection, followed by its chunks collection. */ + async drop(): Promise { + await this.s._filesCollection.drop(); + await this.s._chunksCollection.drop(); + } +} diff --git a/2_PAC/node_modules/mongodb/src/gridfs/upload.ts b/2_PAC/node_modules/mongodb/src/gridfs/upload.ts new file mode 100644 index 00000000..a5dabc56 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/gridfs/upload.ts @@ -0,0 +1,523 @@ +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 type { Callback } 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'; + + /** + * @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. + * @internal + */ + 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).then( + () => { + this.bucket.s.checkedIndexes = true; + this.bucket.emit('index'); + }, + () => null + ); + } + } + + /** + * 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)); + } + + /** + * Places this write stream into an aborted state (all future writes fail) + * and deletes all chunks that have already been written. + */ + async abort(): Promise { + if (this.state.streamEnd) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new MongoAPIError('Cannot abort a stream that has already completed'); + } + + if (this.state.aborted) { + // TODO(NODE-3485): Replace with MongoGridFSStreamClosed + throw new MongoAPIError('Cannot call abort() on a stream twice'); + } + + this.state.aborted = true; + await this.chunks.deleteMany({ files_id: this.id }); + } + + /** + * 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 + }; +} + +async function checkChunksIndex(stream: GridFSBucketWriteStream): Promise { + const index = { files_id: 1, n: 1 }; + + let indexes; + try { + indexes = await stream.chunks.listIndexes().toArray(); + } catch (error) { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } else { + throw error; + } + } + + const hasChunksIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.files_id === 1 && index.key.n === 1) { + return true; + } + return false; + }); + + if (!hasChunksIndex) { + const writeConcernOptions = getWriteOptions(stream); + await stream.chunks.createIndex(index, { + ...writeConcernOptions, + background: true, + unique: true + }); + } +} + +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)).then( + () => { + stream.emit(GridFSBucketWriteStream.FINISH, filesDoc); + stream.emit(GridFSBucketWriteStream.CLOSE); + }, + error => { + return __handleError(stream, error, callback); + } + ); + + return true; + } + + return false; +} + +async function checkIndexes(stream: GridFSBucketWriteStream): Promise { + const doc = await stream.files.findOne({}, { projection: { _id: 1 } }); + if (doc != null) { + // If at least one document exists assume the collection has the required index + return; + } + + const index = { filename: 1, uploadDate: 1 }; + + let indexes; + try { + indexes = await stream.files.listIndexes().toArray(); + } catch (error) { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + indexes = []; + } else { + throw error; + } + } + + const hasFileIndex = !!indexes.find(index => { + const keys = Object.keys(index.key); + if (keys.length === 2 && index.key.filename === 1 && index.key.uploadDate === 1) { + return true; + } + return false; + }); + + if (!hasFileIndex) { + await stream.files.createIndex(index, { background: false }); + } + + await checkChunksIndex(stream); +} + +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)).then( + () => { + --stream.state.outstandingRequests; + --outstandingRequests; + + if (!outstandingRequests) { + stream.emit('drain', doc); + callback && callback(); + checkDone(stream); + } + }, + error => { + return __handleError(stream, error); + } + ); + + 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)).then( + () => { + --stream.state.outstandingRequests; + checkDone(stream); + }, + error => { + return __handleError(stream, error); + } + ); + 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/2_PAC/node_modules/mongodb/src/index.ts b/2_PAC/node_modules/mongodb/src/index.ts new file mode 100644 index 00000000..ad382f49 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/index.ts @@ -0,0 +1,466 @@ +import { Admin } from './admin'; +import { OrderedBulkOperation } from './bulk/ordered'; +import { UnorderedBulkOperation } from './bulk/unordered'; +import { ChangeStream } from './change_stream'; +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 { GridFSBucketReadStream } from './gridfs/download'; +import { GridFSBucketWriteStream } from './gridfs/upload'; +import { MongoClient } from './mongo_client'; +import { CancellationToken } from './mongo_types'; +import { ClientSession } from './sessions'; + +/** @public */ +export { BSON } from './bson'; +export { + Binary, + BSONRegExp, + BSONSymbol, + BSONType, + Code, + DBRef, + Decimal128, + Double, + Int32, + Long, + MaxKey, + MinKey, + ObjectId, + Timestamp +} from './bson'; +export { AnyBulkWriteOperation, BulkWriteOptions, MongoBulkWriteError } from './bulk/common'; +export { ChangeStreamCursor } from './cursor/change_stream_cursor'; +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, + ChangeStream, + ClientSession, + Collection, + Db, + FindCursor, + GridFSBucket, + GridFSBucketReadStream, + GridFSBucketWriteStream, + ListCollectionsCursor, + ListIndexesCursor, + MongoClient, + OrderedBulkOperation, + UnorderedBulkOperation +}; + +// 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 { ServerApiVersion } from './mongo_client'; +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, + ConnectionPoolReadyEvent, + 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 { + ChangeStreamCollModDocument, + ChangeStreamCreateDocument, + ChangeStreamCreateIndexDocument, + ChangeStreamDeleteDocument, + ChangeStreamDocument, + ChangeStreamDocumentCollectionUUID, + ChangeStreamDocumentCommon, + ChangeStreamDocumentKey, + ChangeStreamDocumentOperationDescription, + ChangeStreamDropDatabaseDocument, + ChangeStreamDropDocument, + ChangeStreamDropIndexDocument, + ChangeStreamEvents, + ChangeStreamInsertDocument, + ChangeStreamInvalidateDocument, + ChangeStreamNameSpace, + ChangeStreamOptions, + ChangeStreamRefineCollectionShardKeyDocument, + ChangeStreamRenameDocument, + ChangeStreamReplaceDocument, + ChangeStreamReshardCollectionDocument, + ChangeStreamShardCollectionDocument, + ChangeStreamUpdateDocument, + OperationTime, + ResumeOptions, + ResumeToken, + UpdateDescription +} from './change_stream'; +export type { + AuthMechanismProperties, + MongoCredentials, + MongoCredentialsOptions +} from './cmap/auth/mongo_credentials'; +export type { + BinMsg, + MessageHeader, + Msg, + 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, + ProxyOptions +} from './cmap/connection'; +export type { + CloseOptions, + ConnectionPool, + ConnectionPoolEvents, + ConnectionPoolOptions, + PoolState, + 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, + 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 { + GridFSBucketReadStreamOptions, + GridFSBucketReadStreamOptionsWithRevision, + GridFSBucketReadStreamPrivate, + GridFSFile +} from './gridfs/download'; +export type { GridFSBucketEvents, GridFSBucketOptions, GridFSBucketPrivate } from './gridfs/index'; +export type { GridFSBucketWriteStreamOptions, GridFSChunk } from './gridfs/upload'; +export type { + Auth, + DriverInfo, + MongoClientEvents, + MongoClientOptions, + MongoClientPrivate, + MongoOptions, + PkFactory, + ServerApi, + SupportedNodeConnectionOptions, + SupportedSocketOptions, + SupportedTLSConnectionOptions, + SupportedTLSSocketOptions, + WithSessionCallback +} from './mongo_client'; +export type { + MongoLoggableComponent, + MongoLogger, + MongoLoggerEnvOptions, + MongoLoggerMongoClientOptions, + MongoLoggerOptions, + SeverityLevel +} from './mongo_logger'; +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, + PropertyType, + PullAllOperator, + PullOperator, + PushOperator, + RegExpOrString, + RootFilterOperators, + SchemaMember, + SetFields, + StrictFilter, + StrictMatchKeysAndValues, + StrictUpdateFilter, + 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 { 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, + MonitorInterval, + MonitorIntervalOptions, + 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 { + 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, + List, + MongoDBNamespace +} from './utils'; +export type { W, WriteConcernOptions, WriteConcernSettings } from './write_concern'; diff --git a/2_PAC/node_modules/mongodb/src/mongo_client.ts b/2_PAC/node_modules/mongodb/src/mongo_client.ts new file mode 100644 index 00000000..391ab395 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/mongo_client.ts @@ -0,0 +1,729 @@ +import type { TcpNetConnectOpts } from 'net'; +import type { ConnectionOptions as TLSConnectionOptions, TLSSocketOptions } from 'tls'; +import { promisify } from 'util'; + +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, resolveSRVRecord } from './connection_string'; +import { 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 { MongoLogger, MongoLoggerOptions } from './mongo_logger'; +import { TypedEventEmitter } from './mongo_types'; +import type { ReadConcern, ReadConcernLevel, ReadConcernLike } from './read_concern'; +import { ReadPreference, ReadPreferenceMode } from './read_preference'; +import type { TagSet } from './sdam/server_description'; +import { readPreferenceServerSelector } from './sdam/server_selection'; +import type { SrvPoller } from './sdam/srv_polling'; +import { Topology, TopologyEvents } from './sdam/topology'; +import { ClientSession, ClientSessionOptions, ServerSessionPool } from './sessions'; +import { ClientMetadata, HostAddress, MongoDBNamespace, ns, resolveOptions } from './utils'; +import type { W, WriteConcern, WriteConcernSettings } 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 + * @deprecated Please use the `writeConcern` option instead + */ + w?: W; + /** + * The write concern timeout + * @deprecated Please use the `writeConcern` option instead + */ + wtimeoutMS?: number; + /** + * The journal write concern + * @deprecated Please use the `writeConcern` option instead + */ + journal?: boolean; + /** + * A MongoDB WriteConcern, which describes the level of acknowledgement + * requested from MongoDB for write operations. + * + * @see https://docs.mongodb.com/manual/reference/write-concern/ + */ + writeConcern?: WriteConcern | WriteConcernSettings; + /** 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; + /** A primary key factory function for generation of custom `_id` keys */ + pkFactory?: PkFactory; + /** Enable command monitoring for this client */ + monitorCommands?: boolean; + /** Server API version */ + serverApi?: ServerApi | ServerApiVersion; + /** + * Optionally enable in-use 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 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 + * ```ts + * import { MongoClient } from 'mongodb'; + * + * // Enable command monitoring for debugging + * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true }); + * + * client.on('commandStarted', started => console.log(started)); + * client.db().collection('pets'); + * await client.insertOne({ name: 'spot', kind: 'dog' }); + * ``` + */ +export class MongoClient extends TypedEventEmitter { + /** @internal */ + s: MongoClientPrivate; + /** @internal */ + topology?: Topology; + /** @internal */ + readonly mongoLogger: MongoLogger; + + /** + * The consolidate, parsed, transformed and merged options. + * @internal + */ + [kOptions]: MongoOptions; + + constructor(url: string, options?: MongoClientOptions) { + super(); + + this[kOptions] = parseOptions(url, this, options); + this.mongoLogger = new MongoLogger(this[kOptions].mongoLoggerOptions); + + // 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 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; + } + + /** + * Connect to MongoDB using a url + * + * @see docs.mongodb.org/manual/reference/connection-string/ + */ + async connect(): Promise { + if (this.topology && this.topology.isConnected()) { + return this; + } + + const options = this[kOptions]; + + if (typeof options.srvHost === 'string') { + const hosts = await resolveSRVRecord(options); + + for (const [index, host] of hosts.entries()) { + options.hosts[index] = host; + } + } + + 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 + this.topology = topology; + topology.client = this; + + topology.once(Topology.OPEN, () => this.emit('open', this)); + + for (const event of MONGO_CLIENT_EVENTS) { + topology.on(event, (...args: any[]) => this.emit(event, ...(args as any))); + } + + const topologyConnect = async () => { + try { + await promisify(callback => topology.connect(options, callback))(); + } catch (error) { + topology.close({ force: true }); + throw error; + } + }; + + if (this.autoEncrypter) { + const initAutoEncrypter = promisify(callback => this.autoEncrypter?.init(callback)); + await initAutoEncrypter(); + await topologyConnect(); + await options.encrypter.connectInternalClient(); + } else { + await topologyConnect(); + } + + return this; + } + + /** + * Close the client and its underlying connections + * + * @param force - Force close, emitting no events + */ + async close(force = false): Promise { + // There's no way to set hasBeenClosed back to false + Object.defineProperty(this.s, 'hasBeenClosed', { + value: true, + enumerable: true, + configurable: false, + writable: false + }); + + const activeSessionEnds = Array.from(this.s.activeSessions, session => session.endSession()); + this.s.activeSessions.clear(); + + await Promise.all(activeSessionEnds); + + if (this.topology == null) { + return; + } + + // If we would attempt to select a server and get nothing back we short circuit + // to avoid the server selection timeout. + const selector = readPreferenceServerSelector(ReadPreference.primaryPreferred); + const topologyDescription = this.topology.description; + const serverDescriptions = Array.from(topologyDescription.servers.values()); + const servers = selector(topologyDescription, serverDescriptions); + if (servers.length !== 0) { + const endSessions = Array.from(this.s.sessionPool.sessions, ({ id }) => id); + if (endSessions.length !== 0) { + await this.db('admin') + .command( + { endSessions }, + { readPreference: ReadPreference.primaryPreferred, noResponse: true } + ) + .catch(() => null); // outcome does not matter + } + } + + // clear out references to old topology + const topology = this.topology; + this.topology = undefined; + + await 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(); + }); + }); + } + + /** + * 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 async connect(url: string, options?: MongoClientOptions): Promise { + const client = new this(url, options); + return client.connect(); + } + + /** Starts a new session on the server */ + 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 + */ + async withSession(callback: WithSessionCallback): Promise; + async withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise; + async 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); + + try { + await withSessionCallback(session); + } finally { + try { + await session.endSession(); + } catch { + // We are not concerned with errors from endSession() + } + } + } + + /** + * 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 use cases: + * - 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)); + } +} + +/** + * Mongo Client Options + * @public + */ +export interface MongoOptions + extends Required< + Pick< + MongoClientOptions, + | 'autoEncryption' + | 'connectTimeoutMS' + | 'directConnection' + | 'driverInfo' + | 'forceServerObjectId' + | 'minHeartbeatFrequencyMS' + | 'heartbeatFrequencyMS' + | 'keepAlive' + | 'keepAliveInitialDelay' + | 'localThresholdMS' + | 'maxConnecting' + | 'maxIdleTimeMS' + | 'maxPoolSize' + | 'minPoolSize' + | 'monitorCommands' + | 'noDelay' + | 'pkFactory' + | '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; + + /** @internal */ + mongoLoggerOptions: MongoLoggerOptions; +} diff --git a/2_PAC/node_modules/mongodb/src/mongo_logger.ts b/2_PAC/node_modules/mongodb/src/mongo_logger.ts new file mode 100644 index 00000000..81acd2af --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/mongo_logger.ts @@ -0,0 +1,201 @@ +import { Writable } from 'stream'; + +import { parseUnsignedInteger } from './utils'; + +/** @internal */ +export const SeverityLevel = Object.freeze({ + EMERGENCY: 'emergency', + ALERT: 'alert', + CRITICAL: 'critical', + ERROR: 'error', + WARNING: 'warn', + NOTICE: 'notice', + INFORMATIONAL: 'info', + DEBUG: 'debug', + TRACE: 'trace', + OFF: 'off' +} as const); + +/** @internal */ +export type SeverityLevel = typeof SeverityLevel[keyof typeof SeverityLevel]; + +/** @internal */ +export const MongoLoggableComponent = Object.freeze({ + COMMAND: 'command', + TOPOLOGY: 'topology', + SERVER_SELECTION: 'serverSelection', + CONNECTION: 'connection' +} as const); + +/** @internal */ +export type MongoLoggableComponent = + typeof MongoLoggableComponent[keyof typeof MongoLoggableComponent]; + +/** @internal */ +export interface MongoLoggerEnvOptions { + /** Severity level for command component */ + MONGODB_LOG_COMMAND?: string; + /** Severity level for topology component */ + MONGODB_LOG_TOPOLOGY?: string; + /** Severity level for server selection component */ + MONGODB_LOG_SERVER_SELECTION?: string; + /** Severity level for CMAP */ + MONGODB_LOG_CONNECTION?: string; + /** Default severity level to be if any of the above are unset */ + MONGODB_LOG_ALL?: string; + /** Max length of embedded EJSON docs. Setting to 0 disables truncation. Defaults to 1000. */ + MONGODB_LOG_MAX_DOCUMENT_LENGTH?: string; + /** Destination for log messages. Must be 'stderr', 'stdout'. Defaults to 'stderr'. */ + MONGODB_LOG_PATH?: string; +} + +/** @internal */ +export interface MongoLoggerMongoClientOptions { + /** Destination for log messages */ + mongodbLogPath?: 'stdout' | 'stderr' | Writable; +} + +/** @internal */ +export interface MongoLoggerOptions { + componentSeverities: { + /** Severity level for command component */ + command: SeverityLevel; + /** Severity level for topology component */ + topology: SeverityLevel; + /** Severity level for server selection component */ + serverSelection: SeverityLevel; + /** Severity level for connection component */ + connection: SeverityLevel; + /** Default severity level to be used if any of the above are unset */ + default: SeverityLevel; + }; + + /** Max length of embedded EJSON docs. Setting to 0 disables truncation. Defaults to 1000. */ + maxDocumentLength: number; + /** Destination for log messages. */ + logDestination: Writable; +} + +/** + * Parses a string as one of SeverityLevel + * + * @param s - the value to be parsed + * @returns one of SeverityLevel if value can be parsed as such, otherwise null + */ +function parseSeverityFromString(s?: string): SeverityLevel | null { + const validSeverities: string[] = Object.values(SeverityLevel); + const lowerSeverity = s?.toLowerCase(); + + if (lowerSeverity != null && validSeverities.includes(lowerSeverity)) { + return lowerSeverity as SeverityLevel; + } + + return null; +} + +/** + * resolves the MONGODB_LOG_PATH and mongodbLogPath options from the environment and the + * mongo client options respectively. + * + * @returns the Writable stream to write logs to + */ +function resolveLogPath( + { MONGODB_LOG_PATH }: MongoLoggerEnvOptions, + { + mongodbLogPath + }: { + mongodbLogPath?: unknown; + } +): Writable { + const isValidLogDestinationString = (destination: string) => + ['stdout', 'stderr'].includes(destination.toLowerCase()); + if (typeof mongodbLogPath === 'string' && isValidLogDestinationString(mongodbLogPath)) { + return mongodbLogPath.toLowerCase() === 'stderr' ? process.stderr : process.stdout; + } + + // TODO(NODE-4813): check for minimal interface instead of instanceof Writable + if (typeof mongodbLogPath === 'object' && mongodbLogPath instanceof Writable) { + return mongodbLogPath; + } + + if (typeof MONGODB_LOG_PATH === 'string' && isValidLogDestinationString(MONGODB_LOG_PATH)) { + return MONGODB_LOG_PATH.toLowerCase() === 'stderr' ? process.stderr : process.stdout; + } + + return process.stderr; +} + +/** @internal */ +export class MongoLogger { + componentSeverities: Record; + maxDocumentLength: number; + logDestination: Writable; + + constructor(options: MongoLoggerOptions) { + this.componentSeverities = options.componentSeverities; + this.maxDocumentLength = options.maxDocumentLength; + this.logDestination = options.logDestination; + } + + /* eslint-disable @typescript-eslint/no-unused-vars */ + /* eslint-disable @typescript-eslint/no-empty-function */ + emergency(component: any, message: any): void {} + + alert(component: any, message: any): void {} + + critical(component: any, message: any): void {} + + error(component: any, message: any): void {} + + warn(component: any, message: any): void {} + + notice(component: any, message: any): void {} + + info(component: any, message: any): void {} + + debug(component: any, message: any): void {} + + trace(component: any, message: any): void {} + + /** + * Merges options set through environment variables and the MongoClient, preferring environment + * variables when both are set, and substituting defaults for values not set. Options set in + * constructor take precedence over both environment variables and MongoClient options. + * + * @remarks + * When parsing component severity levels, invalid values are treated as unset and replaced with + * the default severity. + * + * @param envOptions - options set for the logger from the environment + * @param clientOptions - options set for the logger in the MongoClient options + * @returns a MongoLoggerOptions object to be used when instantiating a new MongoLogger + */ + static resolveOptions( + envOptions: MongoLoggerEnvOptions, + clientOptions: MongoLoggerMongoClientOptions + ): MongoLoggerOptions { + // client options take precedence over env options + const combinedOptions = { + ...envOptions, + ...clientOptions, + mongodbLogPath: resolveLogPath(envOptions, clientOptions) + }; + const defaultSeverity = + parseSeverityFromString(combinedOptions.MONGODB_LOG_ALL) ?? SeverityLevel.OFF; + + return { + componentSeverities: { + command: parseSeverityFromString(combinedOptions.MONGODB_LOG_COMMAND) ?? defaultSeverity, + topology: parseSeverityFromString(combinedOptions.MONGODB_LOG_TOPOLOGY) ?? defaultSeverity, + serverSelection: + parseSeverityFromString(combinedOptions.MONGODB_LOG_SERVER_SELECTION) ?? defaultSeverity, + connection: + parseSeverityFromString(combinedOptions.MONGODB_LOG_CONNECTION) ?? defaultSeverity, + default: defaultSeverity + }, + maxDocumentLength: + parseUnsignedInteger(combinedOptions.MONGODB_LOG_MAX_DOCUMENT_LENGTH) ?? 1000, + logDestination: combinedOptions.mongodbLogPath + }; + } +} diff --git a/2_PAC/node_modules/mongodb/src/mongo_types.ts b/2_PAC/node_modules/mongodb/src/mongo_types.ts new file mode 100644 index 00000000..0676a31c --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/mongo_types.ts @@ -0,0 +1,560 @@ +import type { BSONType, 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 required 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 = { + [P in keyof WithId]?: Condition[P]>; +} & 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 type BSONTypeAlias = keyof typeof BSONType; + +/** @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> & Record; + +/** @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/ + * + * @remarks + * Through testing we determined that a depth of 8 is safe for the typescript compiler + * and provides reasonable compilation times. This number is otherwise not special and + * should be changed if issues are found with this level of checking. Beyond this + * depth any helpers that make use of NestedPaths should devolve to not asserting any + * type safety on the input. + */ +export type NestedPaths = Depth['length'] extends 8 + ? [] + : 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] | [Key]; + }[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 +>; + +/** + * @public + * @experimental + */ +export type StrictFilter = + | Partial + | ({ + [Property in Join, []>, '.'>]?: Condition< + PropertyType, Property> + >; + } & RootFilterOperators>); + +/** + * @public + * @experimental + */ +export type StrictUpdateFilter = { + $currentDate?: OnlyFieldsOfType< + TSchema, + Date | Timestamp, + true | { $type: 'date' | 'timestamp' } + >; + $inc?: OnlyFieldsOfType; + $min?: StrictMatchKeysAndValues; + $max?: StrictMatchKeysAndValues; + $mul?: OnlyFieldsOfType; + $rename?: Record; + $set?: StrictMatchKeysAndValues; + $setOnInsert?: StrictMatchKeysAndValues; + $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 + * @experimental + */ +export type StrictMatchKeysAndValues = Readonly< + { + [Property in Join, '.'>]?: PropertyType; + } & { + [Property in `${NestedPathsOfType}.$${`[${string}]` | ''}`]?: ArrayElement< + PropertyType + >; + } & { + [Property in `${NestedPathsOfType[]>}.$${ + | `[${string}]` + | ''}.${string}`]?: any; // Could be further narrowed + } & Document +>; diff --git a/2_PAC/node_modules/mongodb/src/operations/add_user.ts b/2_PAC/node_modules/mongodb/src/operations/add_user.ts new file mode 100644 index 00000000..be5982a4 --- /dev/null +++ b/2_PAC/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 { + /** 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 + // v5 removed the digestPassword option from AddUserOptions but we still want to throw + // an error when digestPassword is provided. + if ('digestPassword' in options && 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/2_PAC/node_modules/mongodb/src/operations/aggregate.ts b/2_PAC/node_modules/mongodb/src/operations/aggregate.ts new file mode 100644 index 00000000..a48a89ca --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/aggregate.ts @@ -0,0 +1,142 @@ +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 (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/2_PAC/node_modules/mongodb/src/operations/bulk_write.ts b/2_PAC/node_modules/mongodb/src/operations/bulk_write.ts new file mode 100644 index 00000000..f56fd8c5 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/bulk_write.ts @@ -0,0 +1,62 @@ +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 }).then( + result => callback(undefined, result), + error => callback(error) + ); + } +} + +defineAspects(BulkWriteOperation, [Aspect.WRITE_OPERATION]); diff --git a/2_PAC/node_modules/mongodb/src/operations/collections.ts b/2_PAC/node_modules/mongodb/src/operations/collections.ts new file mode 100644 index 00000000..14a1ccbb --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/collections.ts @@ -0,0 +1,50 @@ +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 { + // Let's get the collection names + this.db + .listCollections( + {}, + { ...this.options, nameOnly: true, readPreference: this.readPreference, session } + ) + .toArray() + .then( + documents => { + const collections = []; + for (const { name } of documents) { + if (!name.includes('$')) { + // Filter collections removing any illegal ones + collections.push(new Collection(this.db, name, this.db.s.options)); + } + } + // Return the collection objects + callback(undefined, collections); + }, + error => callback(error) + ); + } +} diff --git a/2_PAC/node_modules/mongodb/src/operations/command.ts b/2_PAC/node_modules/mongodb/src/operations/command.ts new file mode 100644 index 00000000..0aa1a69e --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/command.ts @@ -0,0 +1,159 @@ +import type { BSONSerializeOptions, Document } from '../bson'; +import { MongoInvalidArgumentError } from '../error'; +import { Explain, ExplainOptions } from '../explain'; +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'; + +/** @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 { + /** 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; + bsonOptions?: BSONSerializeOptions; +} + +/** @internal */ +export abstract class CommandOperation extends AbstractOperation { + override options: CommandOperationOptions; + readConcern?: ReadConcern; + writeConcern?: WriteConcern; + explain?: Explain; + + 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); + + 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; + } + + 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 (this.writeConcern && this.hasAspect(Aspect.WRITE_OPERATION) && !inTransaction) { + Object.assign(cmd, { writeConcern: this.writeConcern }); + } + + 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) { + cmd = decorateWithExplain(cmd, this.explain); + } + + server.command(this.ns, cmd, options, callback); + } +} diff --git a/2_PAC/node_modules/mongodb/src/operations/common_functions.ts b/2_PAC/node_modules/mongodb/src/operations/common_functions.ts new file mode 100644 index 00000000..63f7e1f2 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/common_functions.ts @@ -0,0 +1,105 @@ +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() + .then( + indexes => { + if (!Array.isArray(indexes)) return callback(undefined, []); + if (full) return callback(undefined, indexes); + callback(undefined, processResults(indexes)); + }, + error => callback(error) + ); +} + +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/2_PAC/node_modules/mongodb/src/operations/count.ts b/2_PAC/node_modules/mongodb/src/operations/count.ts new file mode 100644 index 00000000..8d94b84e --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/count_documents.ts b/2_PAC/node_modules/mongodb/src/operations/count_documents.ts new file mode 100644 index 00000000..c781329f --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/create_collection.ts b/2_PAC/node_modules/mongodb/src/operations/create_collection.ts new file mode 100644 index 00000000..1b324227 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/create_collection.ts @@ -0,0 +1,200 @@ +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 + * @see https://www.mongodb.com/docs/manual/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. This option is deprecated in MongoDB 3.2+ and will be removed once no longer supported by the server. */ + 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 */ + storageEngine?: Document; + /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */ + validator?: Document; + /** Determines how strictly MongoDB applies the validation rules to existing documents during an update */ + validationLevel?: string; + /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */ + validationAction?: string; + /** Allows users to specify a default configuration for indexes when creating a collection */ + 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) */ + 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 */ + 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/2_PAC/node_modules/mongodb/src/operations/delete.ts b/2_PAC/node_modules/mongodb/src/operations/delete.ts new file mode 100644 index 00000000..f4234ef4 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/delete.ts @@ -0,0 +1,174 @@ +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 type { Callback, 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; +} + +/** @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; + } + + const unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o: Document) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + callback(new MongoCompatibilityError(`hint is not supported with unacknowledged writes`)); + 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.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/2_PAC/node_modules/mongodb/src/operations/distinct.ts b/2_PAC/node_modules/mongodb/src/operations/distinct.ts new file mode 100644 index 00000000..5fe8585e --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/distinct.ts @@ -0,0 +1,90 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Server } from '../sdam/server'; +import type { ClientSession } from '../sessions'; +import { Callback, decorateWithCollation, decorateWithReadConcern } 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; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (typeof options.comment !== 'undefined') { + cmd.comment = options.comment; + } + + // Do we have a readConcern specified + decorateWithReadConcern(cmd, coll, options); + + // Have we specified collation + try { + decorateWithCollation(cmd, coll, options); + } catch (err) { + return callback(err); + } + + 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/2_PAC/node_modules/mongodb/src/operations/drop.ts b/2_PAC/node_modules/mongodb/src/operations/drop.ts new file mode 100644 index 00000000..2fd1569d --- /dev/null +++ b/2_PAC/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 configured 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 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/2_PAC/node_modules/mongodb/src/operations/estimated_document_count.ts b/2_PAC/node_modules/mongodb/src/operations/estimated_document_count.ts new file mode 100644 index 00000000..22b29deb --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/eval.ts b/2_PAC/node_modules/mongodb/src/operations/eval.ts new file mode 100644 index 00000000..3c34c59d --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/execute_operation.ts b/2_PAC/node_modules/mongodb/src/operations/execute_operation.ts new file mode 100644 index 00000000..f8619de7 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/execute_operation.ts @@ -0,0 +1,287 @@ +import type { Document } from '../bson'; +import { + isRetryableReadError, + isRetryableWriteError, + MongoCompatibilityError, + MONGODB_ERROR_CODES, + MongoError, + MongoErrorLabel, + 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, maybeCallback, 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 { + return maybeCallback(() => executeOperationAsync(client, operation), callback); +} + +async function executeOperationAsync< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>(client: MongoClient, operation: T): Promise { + if (!(operation instanceof AbstractOperation)) { + // TODO(NODE-3483): Extend MongoRuntimeError + throw new MongoRuntimeError('This method requires a valid operation instance'); + } + + if (client.topology == null) { + // Auto connect on operation + if (client.s.hasBeenClosed) { + throw new MongoNotConnectedError('Client must be connected before running operations'); + } + client.s.options[Symbol.for('@@mdb.skipPingOnConnect')] = true; + try { + await client.connect(); + } finally { + delete client.s.options[Symbol.for('@@mdb.skipPingOnConnect')]; + } + } + + const { topology } = client; + if (topology == null) { + throw new MongoRuntimeError('client.connect did not create a topology but also did not throw'); + } + + if (topology.shouldCheckForSessionSupport()) { + await topology.selectServerAsync(ReadPreference.primaryPreferred, {}); + } + + // 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) { + throw new MongoExpiredSessionError('Use of expired sessions is not permitted'); + } else if (session.snapshotEnabled && !topology.capabilities.supportsSnapshotReads) { + throw 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. + throw 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; + } + } + + const readPreference = operation.readPreference ?? ReadPreference.primary; + const inTransaction = !!session?.inTransaction(); + + if (inTransaction && !readPreference.equals(ReadPreference.primary)) { + throw 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 server = await topology.selectServerAsync(selector, { session }); + + if (session == null) { + // No session also means it is not retryable, early exit + return operation.executeAsync(server, undefined); + } + + if (!operation.hasAspect(Aspect.RETRYABLE)) { + // non-retryable operation, early exit + try { + return await operation.executeAsync(server, session); + } finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } + } + + 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); + const willRetry = (hasReadAspect && willRetryRead) || (hasWriteAspect && willRetryWrite); + + if (hasWriteAspect && willRetryWrite) { + operation.options.willRetryWrite = true; + session.incrementTransactionNumber(); + } + + try { + return await operation.executeAsync(server, session); + } catch (operationError) { + if (willRetry && operationError instanceof MongoError) { + return await retryOperation(operation, operationError, { + session, + topology, + selector + }); + } + throw operationError; + } finally { + if (session?.owner != null && session.owner === owner) { + await session.endSession().catch(() => null); + } + } +} + +/** @internal */ +type RetryOptions = { + session: ClientSession; + topology: Topology; + selector: ReadPreference | ServerSelector; +}; + +async function retryOperation< + T extends AbstractOperation, + TResult = ResultTypeFromOperation +>( + operation: T, + originalError: MongoError, + { session, topology, selector }: RetryOptions +): Promise { + const isWriteOperation = operation.hasAspect(Aspect.WRITE_OPERATION); + const isReadOperation = operation.hasAspect(Aspect.READ_OPERATION); + + if (isWriteOperation && originalError.code === MMAPv1_RETRY_WRITES_ERROR_CODE) { + throw new MongoServerError({ + message: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + errmsg: MMAPv1_RETRY_WRITES_ERROR_MESSAGE, + originalError + }); + } + + if (isWriteOperation && !isRetryableWriteError(originalError)) { + throw originalError; + } + + if (isReadOperation && !isRetryableReadError(originalError)) { + throw 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 + const server = await topology.selectServerAsync(selector, { session }); + + if (isWriteOperation && !supportsRetryableWrites(server)) { + throw new MongoUnexpectedServerResponseError( + 'Selected server does not support retryable writes' + ); + } + + try { + return await operation.executeAsync(server, session); + } catch (retryError) { + if ( + retryError instanceof MongoError && + retryError.hasErrorLabel(MongoErrorLabel.NoWritesPerformed) + ) { + throw originalError; + } + throw retryError; + } +} diff --git a/2_PAC/node_modules/mongodb/src/operations/find.ts b/2_PAC/node_modules/mongodb/src/operations/find.ts new file mode 100644 index 00000000..33aedd6b --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/find.ts @@ -0,0 +1,263 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import { 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, 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; + /** + * Option to enable an optimized code path for queries looking for a particular range of `ts` values in the oplog. Requires `tailable` to be true. + * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored. + */ + oplogReplay?: boolean; +} + +/** @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 options = this.options; + + 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.oplogReplay === 'boolean') { + findCommand.oplogReplay = options.oplogReplay; + } + + 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/2_PAC/node_modules/mongodb/src/operations/find_and_modify.ts b/2_PAC/node_modules/mongodb/src/operations/find_and_modify.ts new file mode 100644 index 00000000..d292c423 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/find_and_modify.ts @@ -0,0 +1,286 @@ +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; + } + + // 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/2_PAC/node_modules/mongodb/src/operations/get_more.ts b/2_PAC/node_modules/mongodb/src/operations/get_more.ts new file mode 100644 index 00000000..c86c3f36 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/get_more.ts @@ -0,0 +1,106 @@ +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'; + +/** @internal */ +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; + /** TODO(NODE-4413): Address bug with maxAwaitTimeMS not being passed in from the cursor correctly */ + maxAwaitTimeMS?: number; +} + +/** + * GetMore command: https://www.mongodb.com/docs/manual/reference/command/getMore/ + * @internal + */ +export interface GetMoreCommand { + getMore: Long; + collection: string; + batchSize?: number; + maxTimeMS?: number; + /** Only supported on wire versions 10 or greater */ + comment?: unknown; +} + +/** @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; + 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') + ); + } + + if (this.cursorId == null || this.cursorId.isZero()) { + return callback(new MongoRuntimeError('Unable to iterate cursor with no id')); + } + + const collection = this.ns.collection; + if (collection == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + return callback(new MongoRuntimeError('A collection name must be determined before getMore')); + } + + const getMoreCmd: GetMoreCommand = { + getMore: this.cursorId, + collection + }; + + if (typeof this.options.batchSize === 'number') { + getMoreCmd.batchSize = Math.abs(this.options.batchSize); + } + + if (typeof this.options.maxAwaitTimeMS === 'number') { + getMoreCmd.maxTimeMS = this.options.maxAwaitTimeMS; + } + + // we check for undefined specifically here to allow falsy values + // eslint-disable-next-line no-restricted-syntax + if (this.options.comment !== undefined && maxWireVersion(server) >= 9) { + getMoreCmd.comment = this.options.comment; + } + + const commandOptions = { + returnFieldSelector: null, + documentsReturnedIn: 'nextBatch', + ...this.options + }; + + server.command(this.ns, getMoreCmd, commandOptions, callback); + } +} + +defineAspects(GetMoreOperation, [Aspect.READ_OPERATION, Aspect.MUST_SELECT_SAME_SERVER]); diff --git a/2_PAC/node_modules/mongodb/src/operations/indexes.ts b/2_PAC/node_modules/mongodb/src/operations/indexes.ts new file mode 100644 index 00000000..8d095e16 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/indexes.ts @@ -0,0 +1,510 @@ +import type { Document } from '../bson'; +import type { Collection } from '../collection'; +import type { Db } from '../db'; +import { MongoCompatibilityError, MONGODB_ERROR_CODES, MongoError } 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, isObject, maxWireVersion, MongoDBNamespace } 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' + | 'hashed' + | number; + +function isIndexDirection(x: unknown): x is IndexDirection { + return ( + typeof x === 'number' || x === '2d' || x === '2dsphere' || x === 'text' || x === 'geoHaystack' + ); +} +/** @public */ +export type IndexSpecification = OneOrMore< + | string + | [string, IndexDirection] + | { [key: string]: IndexDirection } + | Map +>; + +/** @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: { [key: string]: IndexDirection } | Map; +} + +/** @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 isSingleIndexTuple(t: unknown): t is [string, IndexDirection] { + return Array.isArray(t) && t.length === 2 && isIndexDirection(t[1]); +} + +function makeIndexSpec( + indexSpec: IndexSpecification, + options?: CreateIndexesOptions +): IndexDescription { + const key: Map = new Map(); + + const indexSpecs = + !Array.isArray(indexSpec) || isSingleIndexTuple(indexSpec) ? [indexSpec] : indexSpec; + + // Iterate through array and handle different types + for (const spec of indexSpecs) { + if (typeof spec === 'string') { + key.set(spec, 1); + } else if (Array.isArray(spec)) { + key.set(spec[0], spec[1] ?? 1); + } else if (spec instanceof Map) { + for (const [property, value] of spec) { + key.set(property, value); + } + } else if (isObject(spec)) { + for (const [property, value] of Object.entries(spec)) { + key.set(property, value); + } + } + } + + return { ...options, key }; +} + +/** @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: ReadonlyArray & { key: Map }>; + + constructor( + parent: OperationParent, + collectionName: string, + indexes: IndexDescription[], + options?: CreateIndexesOptions + ) { + super(parent, options); + + this.options = options ?? {}; + this.collectionName = collectionName; + this.indexes = indexes.map(userIndex => { + // Ensure the key is a Map to preserve index key ordering + const key = + userIndex.key instanceof Map ? userIndex.key : new Map(Object.entries(userIndex.key)); + const name = userIndex.name != null ? userIndex.name : Array.from(key).flat().join('_'); + const validIndexOptions = Object.fromEntries( + Object.entries({ ...userIndex }).filter(([optionName]) => + VALID_INDEX_OPTIONS.has(optionName) + ) + ); + return { + ...validIndexOptions, + name, + key + }; + }); + } + + override execute( + server: Server, + session: ClientSession | undefined, + callback: Callback + ): void { + const options = this.options; + const indexes = this.indexes; + + const serverWireVersion = maxWireVersion(server); + + 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 + ) { + 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().then( + indexes => { + indexes = Array.isArray(indexes) ? indexes : [indexes]; + if (indexes.some(index => index.name === indexName)) { + callback(undefined, indexName); + return; + } + super.execute(server, session, callback); + }, + error => { + if (error instanceof MongoError && error.code === MONGODB_ERROR_CODES.NamespaceNotFound) { + // ignore "NamespaceNotFound" errors + return super.execute(server, session, callback); + } + return callback(error); + } + ); + } +} + +/** @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/2_PAC/node_modules/mongodb/src/operations/insert.ts b/2_PAC/node_modules/mongodb/src/operations/insert.ts new file mode 100644 index 00000000..6475a5cf --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/is_capped.ts b/2_PAC/node_modules/mongodb/src/operations/is_capped.ts new file mode 100644 index 00000000..1219e79c --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/is_capped.ts @@ -0,0 +1,44 @@ +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() + .then( + collections => { + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new MongoAPIError(`collection ${coll.namespace} not found`)); + } + + callback(undefined, !!collections[0].options?.capped); + }, + error => callback(error) + ); + } +} diff --git a/2_PAC/node_modules/mongodb/src/operations/kill_cursors.ts b/2_PAC/node_modules/mongodb/src/operations/kill_cursors.ts new file mode 100644 index 00000000..59c78c15 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/kill_cursors.ts @@ -0,0 +1,53 @@ +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'; + +/** + * https://www.mongodb.com/docs/manual/reference/command/killCursors/ + * @internal + */ +interface KillCursorsCommand { + killCursors: string; + cursors: Long[]; + comment?: unknown; +} + +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') + ); + } + + const killCursors = this.ns.collection; + if (killCursors == null) { + // Cursors should have adopted the namespace returned by MongoDB + // which should always defined a collection name (even a pseudo one, ex. db.aggregate()) + return callback( + new MongoRuntimeError('A collection name must be determined before killCursors') + ); + } + + const killCursorsCommand: KillCursorsCommand = { + killCursors, + cursors: [this.cursorId] + }; + + server.command(this.ns, killCursorsCommand, { session }, () => callback()); + } +} + +defineAspects(KillCursorsOperation, [Aspect.MUST_SELECT_SAME_SERVER]); diff --git a/2_PAC/node_modules/mongodb/src/operations/list_collections.ts b/2_PAC/node_modules/mongodb/src/operations/list_collections.ts new file mode 100644 index 00000000..ae1c15ec --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/list_databases.ts b/2_PAC/node_modules/mongodb/src/operations/list_databases.ts new file mode 100644 index 00000000..537c9529 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/operation.ts b/2_PAC/node_modules/mongodb/src/operations/operation.ts new file mode 100644 index 00000000..573a896b --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/operation.ts @@ -0,0 +1,139 @@ +import { promisify } from 'util'; + +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; + + executeAsync: (server: Server, session: ClientSession | undefined) => Promise; + + constructor(options: OperationOptions = {}) { + this.executeAsync = promisify( + ( + server: Server, + session: ClientSession | undefined, + callback: (e: Error, r: TResult) => void + ) => { + this.execute(server, session, callback as any); + } + ); + + 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/2_PAC/node_modules/mongodb/src/operations/options_operation.ts b/2_PAC/node_modules/mongodb/src/operations/options_operation.ts new file mode 100644 index 00000000..9c053938 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/options_operation.ts @@ -0,0 +1,45 @@ +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() + .then( + collections => { + if (collections.length === 0) { + // TODO(NODE-3485) + return callback(new MongoAPIError(`collection ${coll.namespace} not found`)); + } + + callback(undefined, collections[0].options); + }, + error => callback(error) + ); + } +} diff --git a/2_PAC/node_modules/mongodb/src/operations/profiling_level.ts b/2_PAC/node_modules/mongodb/src/operations/profiling_level.ts new file mode 100644 index 00000000..defe6b0d --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/remove_user.ts b/2_PAC/node_modules/mongodb/src/operations/remove_user.ts new file mode 100644 index 00000000..f32c19c2 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/rename.ts b/2_PAC/node_modules/mongodb/src/operations/rename.ts new file mode 100644 index 00000000..02e27a5b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/run_command.ts b/2_PAC/node_modules/mongodb/src/operations/run_command.ts new file mode 100644 index 00000000..b92237a9 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/set_profiling_level.ts b/2_PAC/node_modules/mongodb/src/operations/set_profiling_level.ts new file mode 100644 index 00000000..6fc8502d --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/stats.ts b/2_PAC/node_modules/mongodb/src/operations/stats.ts new file mode 100644 index 00000000..b63a70de --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/operations/update.ts b/2_PAC/node_modules/mongodb/src/operations/update.ts new file mode 100644 index 00000000..278a0b34 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/operations/update.ts @@ -0,0 +1,306 @@ +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, hasAtomicOperators, 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?: Hint; + /** 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 unacknowledgedWrite = this.writeConcern && this.writeConcern.w === 0; + if (unacknowledgedWrite) { + if (this.statements.find((o: Document) => o.hint)) { + // TODO(NODE-3541): fix error for hint with unacknowledged writes + callback(new MongoCompatibilityError(`hint is not supported with unacknowledged writes`)); + 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 | 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/2_PAC/node_modules/mongodb/src/operations/validate_collection.ts b/2_PAC/node_modules/mongodb/src/operations/validate_collection.ts new file mode 100644 index 00000000..ba6c85fa --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/read_concern.ts b/2_PAC/node_modules/mongodb/src/read_concern.ts new file mode 100644 index 00000000..09e39be5 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/read_preference.ts b/2_PAC/node_modules/mongodb/src/read_preference.ts new file mode 100644 index 00000000..1f3d2d0c --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/read_preference.ts @@ -0,0 +1,262 @@ +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, 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); + } 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 + * @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/2_PAC/node_modules/mongodb/src/sdam/common.ts b/2_PAC/node_modules/mongodb/src/sdam/common.ts new file mode 100644 index 00000000..a2ffd894 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/sdam/common.ts @@ -0,0 +1,79 @@ +import { clearTimeout } from 'timers'; + +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/2_PAC/node_modules/mongodb/src/sdam/events.ts b/2_PAC/node_modules/mongodb/src/sdam/events.ts new file mode 100644 index 00000000..c55eb095 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/sdam/monitor.ts b/2_PAC/node_modules/mongodb/src/sdam/monitor.ts new file mode 100644 index 00000000..2625efa1 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/sdam/monitor.ts @@ -0,0 +1,594 @@ +import { clearTimeout, 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 { MongoError, MongoErrorLabel, MongoNetworkTimeoutError } from '../error'; +import { CancellationToken, TypedEventEmitter } from '../mongo_types'; +import type { Callback } from '../utils'; +import { calculateDurationInMs, EventEmitterWithState, 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?: MongoError): 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]?: MonitorInterval; + [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] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: 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] = new MonitorInterval(monitorServer(this), { + heartbeatFrequencyMS: heartbeatFrequencyMS, + minHeartbeatFrequencyMS: 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) + ); + + const error = !(err instanceof MongoError) ? new MongoError(err) : err; + error.addErrorLabel(MongoErrorLabel.ResetPool); + if (error instanceof MongoNetworkTimeoutError) { + error.addErrorLabel(MongoErrorLabel.InterruptInUseConnections); + } + + monitor.emit('resetServer', error); + 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]: 1, + ...(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; + + 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) => { + if (monitor.s.state === STATE_MONITORING) { + process.nextTick(callback); + return; + } + 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) { + 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 + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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(); + }); +} + +/** + * @internal + */ +export interface MonitorIntervalOptions { + /** The interval to execute a method on */ + heartbeatFrequencyMS: number; + /** A minimum interval that must elapse before the method is called */ + minHeartbeatFrequencyMS: number; + /** Whether the method should be called immediately when the interval is started */ + immediate: boolean; +} + +/** + * @internal + */ +export class MonitorInterval { + fn: (callback: Callback) => void; + timerId: NodeJS.Timeout | undefined; + lastExecutionEnded: number; + isExpeditedCallToFnScheduled = false; + stopped = false; + isExecutionInProgress = false; + hasExecutedOnce = false; + + heartbeatFrequencyMS: number; + minHeartbeatFrequencyMS: number; + + constructor(fn: (callback: Callback) => void, options: Partial = {}) { + this.fn = fn; + this.lastExecutionEnded = -Infinity; + + this.heartbeatFrequencyMS = options.heartbeatFrequencyMS ?? 1000; + this.minHeartbeatFrequencyMS = options.minHeartbeatFrequencyMS ?? 500; + + if (options.immediate) { + this._executeAndReschedule(); + } else { + this._reschedule(undefined); + } + } + + wake() { + const currentTime = now(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + + // TODO(NODE-4674): Add error handling and logging to the monitor + if (timeSinceLastCall < 0) { + return this._executeAndReschedule(); + } + + if (this.isExecutionInProgress) { + return; + } + + // debounce multiple calls to wake within the `minInterval` + if (this.isExpeditedCallToFnScheduled) { + return; + } + + // reschedule a call as soon as possible, ensuring the call never happens + // faster than the `minInterval` + if (timeSinceLastCall < this.minHeartbeatFrequencyMS) { + this.isExpeditedCallToFnScheduled = true; + this._reschedule(this.minHeartbeatFrequencyMS - timeSinceLastCall); + return; + } + + this._executeAndReschedule(); + } + + stop() { + this.stopped = true; + if (this.timerId) { + clearTimeout(this.timerId); + this.timerId = undefined; + } + + this.lastExecutionEnded = -Infinity; + this.isExpeditedCallToFnScheduled = false; + } + + toString() { + return JSON.stringify(this); + } + + toJSON() { + const currentTime = now(); + const timeSinceLastCall = currentTime - this.lastExecutionEnded; + return { + timerId: this.timerId != null ? 'set' : 'cleared', + lastCallTime: this.lastExecutionEnded, + isExpeditedCheckScheduled: this.isExpeditedCallToFnScheduled, + stopped: this.stopped, + heartbeatFrequencyMS: this.heartbeatFrequencyMS, + minHeartbeatFrequencyMS: this.minHeartbeatFrequencyMS, + currentTime, + timeSinceLastCall + }; + } + + private _reschedule(ms?: number) { + if (this.stopped) return; + if (this.timerId) { + clearTimeout(this.timerId); + } + + this.timerId = setTimeout(this._executeAndReschedule, ms || this.heartbeatFrequencyMS); + } + + private _executeAndReschedule = () => { + if (this.stopped) return; + if (this.timerId) { + clearTimeout(this.timerId); + } + + this.isExpeditedCallToFnScheduled = false; + this.isExecutionInProgress = true; + + this.fn(() => { + this.lastExecutionEnded = now(); + this.isExecutionInProgress = false; + this._reschedule(this.heartbeatFrequencyMS); + }); + }; +} diff --git a/2_PAC/node_modules/mongodb/src/sdam/server.ts b/2_PAC/node_modules/mongodb/src/sdam/server.ts new file mode 100644 index 00000000..e9679de9 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/sdam/server.ts @@ -0,0 +1,560 @@ +import type { Document } from '../bson'; +import { CommandOptions, Connection, DestroyOptions } from '../cmap/connection'; +import { + ConnectionPool, + ConnectionPoolEvents, + ConnectionPoolOptions +} from '../cmap/connection_pool'; +import { PoolClearedError } from '../cmap/errors'; +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 { + AnyError, + isNetworkErrorBeforeHandshake, + isNodeShuttingDownError, + isSDAMUnrecoverableError, + MongoError, + MongoErrorLabel, + MongoInvalidArgumentError, + MongoNetworkError, + MongoNetworkTimeoutError, + MongoRuntimeError, + MongoServerClosedError, + MongoServerError, + MongoUnexpectedServerResponseError, + needsRetryableWriteLabel +} from '../error'; +import type { ServerApi } from '../mongo_client'; +import { TypedEventEmitter } from '../mongo_types'; +import type { GetMoreOptions } from '../operations/get_more'; +import type { ClientSession } from '../sessions'; +import { isTransactionCommand } from '../transactions'; +import { + Callback, + 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'); + +/** @internal */ +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; + /** 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, + state: STATE_CLOSED, + topology, + pool: new ConnectionPool(this, 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('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; + } + + 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; + if (!err) { + return cb(new MongoRuntimeError('Failed to create connection without error')); + } + if (!(err instanceof PoolClearedError)) { + this.handleError(err); + } + return cb(err); + } + + conn.command( + ns, + cmd, + finalOptions, + makeOperationHandler(this, conn, cmd, finalOptions, (error, response) => { + this.s.operationCount -= 1; + cb(error, response); + }) + ); + }, + callback + ); + } + + /** + * Handle SDAM error + * @internal + */ + handleError(error: AnyError, connection?: Connection) { + if (!(error instanceof MongoError)) { + return; + } + + const isStaleError = + error.connectionGeneration && error.connectionGeneration < this.s.pool.generation; + if (isStaleError) { + return; + } + + const isNetworkNonTimeoutError = + error instanceof MongoNetworkError && !(error instanceof MongoNetworkTimeoutError); + const isNetworkTimeoutBeforeHandshakeError = isNetworkErrorBeforeHandshake(error); + const isAuthHandshakeError = error.hasErrorLabel(MongoErrorLabel.HandshakeError); + if (isNetworkNonTimeoutError || isNetworkTimeoutBeforeHandshakeError || isAuthHandshakeError) { + // In load balanced mode we never mark the server as unknown and always + // clear for the specific service id. + if (!this.loadBalanced) { + error.addErrorLabel(MongoErrorLabel.ResetPool); + markServerUnknown(this, error); + } else if (connection) { + this.s.pool.clear({ serviceId: connection.serviceId }); + } + } else { + if (isSDAMUnrecoverableError(error)) { + if (shouldHandleStateChangeError(this, error)) { + const shouldClearPool = maxWireVersion(this) <= 7 || isNodeShuttingDownError(error); + if (this.loadBalanced && connection && shouldClearPool) { + this.s.pool.clear({ serviceId: connection.serviceId }); + } + + if (!this.loadBalanced) { + if (shouldClearPool) { + error.addErrorLabel(MongoErrorLabel.ResetPool); + } + markServerUnknown(this, error); + process.nextTick(() => this.requestCheck()); + } + } + } + } + } +} + +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?: MongoServerError) { + // 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 }) + ); +} + +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) { + // We should not swallow an error if it is present. + if (error == null && result != null) { + return callback(undefined, result); + } + + if (options != null && 'noResponse' in options && options.noResponse === true) { + return callback(undefined, null); + } + + 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); + } + } else { + if ( + (isRetryableWritesEnabled(server.s.topology) || isTransactionCommand(cmd)) && + needsRetryableWriteLabel(error, maxWireVersion(server)) && + !inActiveTransaction(session, cmd) + ) { + error.addErrorLabel(MongoErrorLabel.RetryableWriteError); + } + } + + if ( + session && + session.isPinned && + error.hasErrorLabel(MongoErrorLabel.TransientTransactionError) + ) { + session.unpin({ force: true }); + } + + server.handleError(error, connection); + + return callback(error); + }; +} diff --git a/2_PAC/node_modules/mongodb/src/sdam/server_description.ts b/2_PAC/node_modules/mongodb/src/sdam/server_description.ts new file mode 100644 index 00000000..ab5da450 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/sdam/server_description.ts @@ -0,0 +1,262 @@ +import { Document, Long, ObjectId } from '../bson'; +import { MongoError, MongoRuntimeError, MongoServerError } from '../error'; +import { arrayStrictEqual, compareObjectId, 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?: MongoServerError; + + /** The round trip time to ping this server (in ms) */ + roundTripTime?: number; + + /** 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 { + address: string; + type: ServerType; + hosts: string[]; + passives: string[]; + arbiters: string[]; + tags: TagSet; + error: MongoError | null; + topologyVersion: TopologyVersion | null; + minWireVersion: number; + maxWireVersion: number; + roundTripTime: number; + lastUpdateTime: number; + lastWriteDate: number; + me: string | null; + primary: string | null; + setName: string | null; + setVersion: number | null; + electionId: ObjectId | null; + logicalSessionTimeoutMinutes: number | null; + + // 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 (address == null || address === '') { + throw new MongoRuntimeError('ServerDescription must be provided with a non-empty address'); + } + + this.address = + typeof address === 'string' + ? HostAddress.fromString(address).toString() // Use HostAddress to normalize + : address.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; + this.error = options.error ?? null; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + this.topologyVersion = this.error?.topologyVersion ?? hello?.topologyVersion ?? null; + this.setName = hello?.setName ?? null; + this.setVersion = hello?.setVersion ?? null; + this.electionId = hello?.electionId ?? null; + this.logicalSessionTimeoutMinutes = hello?.logicalSessionTimeoutMinutes ?? null; + this.primary = hello?.primary ?? null; + this.me = hello?.me?.toLowerCase() ?? null; + this.$clusterTime = hello?.$clusterTime ?? null; + } + + get hostAddress(): HostAddress { + return HostAddress.fromString(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 | null): boolean { + // Despite using the comparator that would determine a nullish topologyVersion as greater than + // for equality we should only always perform direct equality comparison + const topologyVersionsEqual = + this.topologyVersion === other?.topologyVersion || + compareTopologyVersion(this.topologyVersion, other?.topologyVersion) === 0; + + const electionIdsEqual = + this.electionId != null && other?.electionId != null + ? compareObjectId(this.electionId, other.electionId) === 0 + : 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. + * + * 1. If the response topologyVersion is unset or the ServerDescription's + * topologyVersion is null, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is not equal to the + * ServerDescription's, the client MUST assume the response is more recent. + * 1. If the response's topologyVersion.processId is equal to the + * ServerDescription's, the client MUST use the counter field to determine + * which topologyVersion is more recent. + * + * ```ts + * currentTv < newTv === -1 + * currentTv === newTv === 0 + * currentTv > newTv === 1 + * ``` + */ +export function compareTopologyVersion( + currentTv?: TopologyVersion | null, + newTv?: TopologyVersion | null +): 0 | -1 | 1 { + if (currentTv == null || newTv == null) { + return -1; + } + + if (!currentTv.processId.equals(newTv.processId)) { + return -1; + } + + // TODO(NODE-2674): Preserve int64 sent from MongoDB + const currentCounter = Long.isLong(currentTv.counter) + ? currentTv.counter + : Long.fromNumber(currentTv.counter); + const newCounter = Long.isLong(newTv.counter) ? newTv.counter : Long.fromNumber(newTv.counter); + + return currentCounter.compare(newCounter); +} diff --git a/2_PAC/node_modules/mongodb/src/sdam/server_selection.ts b/2_PAC/node_modules/mongodb/src/sdam/server_selection.ts new file mode 100644 index 00000000..c7c2b563 --- /dev/null +++ b/2_PAC/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; + +/** @internal */ +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/2_PAC/node_modules/mongodb/src/sdam/srv_polling.ts b/2_PAC/node_modules/mongodb/src/sdam/srv_polling.ts new file mode 100644 index 00000000..253f3a74 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/sdam/srv_polling.ts @@ -0,0 +1,157 @@ +import * as dns from 'dns'; +import { clearTimeout, setTimeout } from 'timers'; + +import { MongoRuntimeError } from '../error'; +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 { + 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; + 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.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; + } + } + + // TODO(NODE-4994): implement new logging logic for SrvPoller failures + schedule(): void { + if (this._timeout) { + clearTimeout(this._timeout); + } + + this._timeout = setTimeout(() => { + this._poll().catch(() => null); + }, this.intervalMS); + } + + success(srvRecords: dns.SrvRecord[]): void { + this.haMode = false; + this.schedule(); + this.emit(SrvPoller.SRV_RECORD_DISCOVERY, new SrvPollingEvent(srvRecords)); + } + + failure(): void { + this.haMode = true; + this.schedule(); + } + + async _poll(): Promise { + const generation = this.generation; + let srvRecords; + + try { + srvRecords = await dns.promises.resolveSrv(this.srvAddress); + } catch (dnsError) { + this.failure(); + return; + } + + if (generation !== this.generation) { + return; + } + + const finalAddresses: dns.SrvRecord[] = []; + for (const record of srvRecords) { + if (matchesParentDomain(record.name, this.srvHost)) { + finalAddresses.push(record); + } + } + + if (!finalAddresses.length) { + this.failure(); + return; + } + + this.success(finalAddresses); + } +} diff --git a/2_PAC/node_modules/mongodb/src/sdam/topology.ts b/2_PAC/node_modules/mongodb/src/sdam/topology.ts new file mode 100644 index 00000000..a8623269 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/sdam/topology.ts @@ -0,0 +1,1020 @@ +import { clearTimeout, setTimeout } from 'timers'; +import { promisify } from 'util'; + +import type { BSONSerializeOptions, Document } 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, + MongoError, + MongoErrorLabel, + 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, + EventEmitterWithState, + HostAddress, + List, + 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; +} + +/** @internal */ +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]: List; + /** @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; + + selectServerAsync: ( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions + ) => Promise; + + /** + * @param seedlist - a list of HostAddress instances to connect to + */ + constructor(seeds: string | string[] | HostAddress | HostAddress[], options: TopologyOptions) { + super(); + + this.selectServerAsync = promisify( + ( + selector: string | ReadPreference | ServerSelector, + options: SelectServerOptions, + callback: (e: Error, r: Server) => void + ) => this.selectServer(selector, options, callback as any) + ); + + // 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 List(); + 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(callback: Callback): void; + connect(options: ConnectOptions, callback: Callback): void; + connect(options?: ConnectOptions | Callback, 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(callback: Callback): void; + close(options: CloseOptions): void; + close(options: CloseOptions, callback: Callback): void; + close(options?: CloseOptions | Callback, 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 as CloseOptions); + }); + + 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; + } + + // 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 | null { + 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; + if ( + incomingServerDescription.error instanceof MongoError && + incomingServerDescription.error.hasErrorLabel(MongoErrorLabel.ResetPool) + ) { + const interruptInUseConnections = incomingServerDescription.error.hasErrorLabel( + MongoErrorLabel.InterruptInUseConnections + ); + + server.s.pool.clear({ interruptInUseConnections }); + } else if (incomingServerDescription.error == null) { + const newTopologyType = topology.s.description.type; + const shouldMarkPoolReady = + incomingServerDescription.isDataBearing || + (incomingServerDescription.type !== ServerType.Unknown && + newTopologyType === TopologyType.Single); + if (shouldMarkPoolReady) { + server.s.pool.ready(); + } + } + } + } + + // 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: List, 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 { + const descriptions = 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/2_PAC/node_modules/mongodb/src/sdam/topology_description.ts b/2_PAC/node_modules/mongodb/src/sdam/topology_description.ts new file mode 100644 index 00000000..d35a9ad6 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/sdam/topology_description.ts @@ -0,0 +1,511 @@ +import type { ObjectId } from '../bson'; +import * as WIRE_CONSTANTS from '../cmap/wire_protocol/constants'; +import { MongoRuntimeError, MongoServerError } from '../error'; +import { compareObjectId, 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 | null; + maxSetVersion: number | null; + maxElectionId: ObjectId | null; + servers: Map; + stale: boolean; + compatible: boolean; + compatibilityError?: string; + logicalSessionTimeoutMinutes: number | null; + heartbeatFrequencyMS: number; + localThresholdMS: number; + commonWireVersion: number; + + /** + * Create a TopologyDescription + */ + constructor( + topologyType: TopologyType, + serverDescriptions: Map | null = null, + setName: string | null = null, + maxSetVersion: number | null = null, + maxElectionId: ObjectId | null = null, + commonWireVersion: number | null = null, + options: TopologyDescriptionOptions | null = null + ) { + 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; + this.setName = setName ?? null; + this.maxElectionId = maxElectionId ?? null; + this.maxSetVersion = maxSetVersion ?? null; + this.commonWireVersion = commonWireVersion ?? 0; + + // 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 = null; + 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 = null; + 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; + + 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); + } + } + + if ( + typeof serverDescription.setName === 'string' && + typeof setName === 'string' && + serverDescription.setName !== setName + ) { + if (topologyType === TopologyType.Single) { + // "Single" Topology with setName mismatch is direct connection usage, mark unknown do not remove + serverDescription = new ServerDescription(address); + } else { + serverDescriptions.delete(address); + } + } + + // 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(): MongoServerError | null { + const descriptionsWithError = Array.from(this.servers.values()).filter( + (sd: ServerDescription) => sd.error + ); + + if (descriptionsWithError.length > 0) { + return descriptionsWithError[0].error; + } + + return null; + } + + /** + * 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; + } +} + +function updateRsFromPrimary( + serverDescriptions: Map, + serverDescription: ServerDescription, + setName: string | null = null, + maxSetVersion: number | null = null, + maxElectionId: ObjectId | null = null +): [TopologyType, string | null, number | null, ObjectId | null] { + setName = setName || serverDescription.setName; + if (setName !== serverDescription.setName) { + serverDescriptions.delete(serverDescription.address); + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + + if (serverDescription.maxWireVersion >= 17) { + const electionIdComparison = compareObjectId(maxElectionId, serverDescription.electionId); + const maxElectionIdIsEqual = electionIdComparison === 0; + const maxElectionIdIsLess = electionIdComparison === -1; + const maxSetVersionIsLessOrEqual = + (maxSetVersion ?? -1) <= (serverDescription.setVersion ?? -1); + + if (maxElectionIdIsLess || (maxElectionIdIsEqual && maxSetVersionIsLessOrEqual)) { + // The reported electionId was greater + // or the electionId was equal and reported setVersion was greater + // Always update both values, they are a tuple + maxElectionId = serverDescription.electionId; + maxSetVersion = serverDescription.setVersion; + } else { + // Stale primary + // replace serverDescription with a default ServerDescription of type "Unknown" + serverDescriptions.set( + serverDescription.address, + new ServerDescription(serverDescription.address) + ); + + return [checkHasPrimary(serverDescriptions), setName, maxSetVersion, maxElectionId]; + } + } else { + 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 | null = null +): 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 | null = null +): [TopologyType, string | null] { + 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/2_PAC/node_modules/mongodb/src/sessions.ts b/2_PAC/node_modules/mongodb/src/sessions.ts new file mode 100644 index 00000000..9e427952 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/sessions.ts @@ -0,0 +1,1043 @@ +import { promisify } from 'util'; + +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 { ReadConcernLevel } from './read_concern'; +import { ReadPreference } from './read_preference'; +import { _advanceClusterTime, ClusterTime, TopologyType } from './sdam/common'; +import { isTransactionCommand, Transaction, TransactionOptions, TxnState } from './transactions'; +import { + ByteUtils, + calculateDurationInMs, + Callback, + commandSupportsReadConcern, + isPromiseLike, + List, + maxWireVersion, + 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; + + const defaultCausalConsistencyValue = this.explicit && options.snapshot !== true; + this.supports = { + // if we can enable causal consistency, do so by default + causalConsistency: options.causalConsistency ?? defaultCausalConsistencyValue + }; + + 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 + */ + async endSession(options?: EndSessionOptions): Promise { + try { + if (this.inTransaction()) { + await this.abortTransaction(); + } + if (!this.hasEnded) { + 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); + } + } catch { + // spec indicates that we should ignore all errors for `endSessions` + } finally { + maybeClearPinnedConnection(this, { force: true, ...options }); + } + } + + /** + * 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 ByteUtils.equals(this.id.id.buffer, 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 supported in 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. + */ + async commitTransaction(): Promise { + return endTransactionAsync(this, 'commitTransaction'); + } + + /** + * Aborts the currently active transaction in this session. + */ + async abortTransaction(): Promise { + return endTransactionAsync(this, 'abortTransaction'); + } + + /** + * 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 + */ + async 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({ serviceId: 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 { + 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); + } + ); +} + +const endTransactionAsync = promisify( + endTransaction as ( + session: ClientSession, + commandName: 'abortTransaction' | 'commitTransaction', + callback: (error: Error, result: Document) => void + ) => void +); + +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: List; + + constructor(client: MongoClient) { + if (client == null) { + throw new MongoRuntimeError('ServerSessionPool requires a MongoClient'); + } + + this.client = client; + this.sessions = new List(); + } + + /** + * 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; + } + + this.sessions.prune(session => session.hasTimedOut(sessionTimeoutMinutes)); + + 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; + // TODO(NODE-2674): Preserve int64 sent from MongoDB + 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/2_PAC/node_modules/mongodb/src/sort.ts b/2_PAC/node_modules/mongodb/src/sort.ts new file mode 100644 index 00000000..6b766b54 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/src/transactions.ts b/2_PAC/node_modules/mongodb/src/transactions.ts new file mode 100644 index 00000000..bff2df19 --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/transactions.ts @@ -0,0 +1,188 @@ +import type { Document } from './bson'; +import { MongoRuntimeError, MongoTransactionError } from './error'; +import type { CommandOperationOptions } from './operations/command'; +import { ReadConcern, ReadConcernLike } from './read_concern'; +import type { ReadPreferenceLike } from './read_preference'; +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?: ReadPreferenceLike; + /** 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/2_PAC/node_modules/mongodb/src/utils.ts b/2_PAC/node_modules/mongodb/src/utils.ts new file mode 100644 index 00000000..db076acf --- /dev/null +++ b/2_PAC/node_modules/mongodb/src/utils.ts @@ -0,0 +1,1353 @@ +import * as crypto from 'crypto'; +import type { SrvRecord } from 'dns'; +import * as os from 'os'; +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 { Hint, OperationOptions } from './operations/operation'; +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 type AnyOptions = Document; + +export const ByteUtils = { + toLocalBufferType(this: void, buffer: Buffer | Uint8Array): Buffer { + return Buffer.isBuffer(buffer) + ? buffer + : Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + }, + + equals(this: void, seqA: Uint8Array, seqB: Uint8Array) { + return ByteUtils.toLocalBufferType(seqA).equals(seqB); + }, + + compare(this: void, seqA: Uint8Array, seqB: Uint8Array) { + return ByteUtils.toLocalBufferType(seqA).compare(seqB); + }, + + toBase64(this: void, uint8array: Uint8Array) { + return ByteUtils.toLocalBufferType(uint8array).toString('base64'); + } +}; + +/** + * 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; +} + +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 resolution type of the possible promise + * @param value - An object that could be a promise + * @returns true if the provided value is a Promise + */ +export function isPromiseLike(value?: PromiseLike | void): value is Promise { + return !!value && typeof value.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'); +} + +/** @internal */ +export function ns(ns: string): MongoDBNamespace { + return MongoDBNamespace.fromString(ns); +} + +/** @public */ +export class MongoDBNamespace { + db: string; + collection: string | undefined; + /** + * Create a namespace object + * + * @param db - database name + * @param collection - collection name + */ + constructor(db: string, collection?: string) { + this.db = db; + this.collection = collection === '' ? undefined : 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 (typeof namespace !== 'string' || namespace === '') { + // TODO(NODE-3483): Replace with MongoNamespaceError + throw new MongoRuntimeError(`Cannot parse namespace from "${namespace}"`); + } + + const [db, ...collectionParts] = namespace.split('.'); + const collection = collectionParts.join('.'); + return new MongoDBNamespace(db, collection === '' ? undefined : collection); + } +} + +/** @internal */ +export function* makeCounter(seed = 0): Generator { + let count = seed; + while (true) { + const newCount = count; + count += 1; + yield newCount; + } +} + +/** + * Helper for handling legacy callback support. + */ +export function maybeCallback(promiseFn: () => Promise, callback: null): Promise; +export function maybeCallback( + promiseFn: () => Promise, + callback?: Callback +): Promise | void; +export function maybeCallback( + promiseFn: () => Promise, + callback?: Callback | null +): Promise | void { + const promise = promiseFn(); + if (callback == null) { + return promise; + } + + promise.then( + result => callback(undefined, result), + error => callback(error) + ); + return; +} + +/** @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 available 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; +} + +/** + * 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 | null, rhs?: AnyError | null): 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; +} + +/** @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; +} + +type ListNode = { + value: T; + next: ListNode | HeadNode; + prev: ListNode | HeadNode; +}; + +type HeadNode = { + value: null; + next: ListNode; + prev: ListNode; +}; + +/** + * When a list is empty the head is a reference with pointers to itself + * So this type represents that self referential state + */ +type EmptyNode = { + value: null; + next: EmptyNode; + prev: EmptyNode; +}; + +/** + * A sequential list of items in a circularly linked list + * @remarks + * The head node is special, it is always defined and has a value of null. + * It is never "included" in the list, in that, it is not returned by pop/shift or yielded by the iterator. + * The circular linkage and always defined head node are to reduce checks for null next/prev references to zero. + * New nodes are declared as object literals with keys always in the same order: next, prev, value. + * @internal + */ +export class List { + private readonly head: HeadNode | EmptyNode; + private count: number; + + get length() { + return this.count; + } + + get [Symbol.toStringTag]() { + return 'List' as const; + } + + constructor() { + this.count = 0; + + // this is carefully crafted: + // declaring a complete and consistently key ordered + // object is beneficial to the runtime optimizations + this.head = { + next: null, + prev: null, + value: null + } as unknown as EmptyNode; + this.head.next = this.head; + this.head.prev = this.head; + } + + toArray() { + return Array.from(this); + } + + toString() { + return `head <=> ${this.toArray().join(' <=> ')} <=> head`; + } + + *[Symbol.iterator](): Generator { + for (const node of this.nodes()) { + yield node.value; + } + } + + private *nodes(): Generator, void, void> { + let ptr: HeadNode | ListNode | EmptyNode = this.head.next; + while (ptr !== this.head) { + // Save next before yielding so that we make removing within iteration safe + const { next } = ptr as ListNode; + yield ptr as ListNode; + ptr = next; + } + } + + /** Insert at end of list */ + push(value: T) { + this.count += 1; + const newNode: ListNode = { + next: this.head as HeadNode, + prev: this.head.prev as ListNode, + value + }; + this.head.prev.next = newNode; + this.head.prev = newNode; + } + + /** Inserts every item inside an iterable instead of the iterable itself */ + pushMany(iterable: Iterable) { + for (const value of iterable) { + this.push(value); + } + } + + /** Insert at front of list */ + unshift(value: T) { + this.count += 1; + const newNode: ListNode = { + next: this.head.next as ListNode, + prev: this.head as HeadNode, + value + }; + this.head.next.prev = newNode; + this.head.next = newNode; + } + + private remove(node: ListNode | EmptyNode): T | null { + if (node === this.head || this.length === 0) { + return null; + } + + this.count -= 1; + + const prevNode = node.prev; + const nextNode = node.next; + prevNode.next = nextNode; + nextNode.prev = prevNode; + + return node.value; + } + + /** Removes the first node at the front of the list */ + shift(): T | null { + return this.remove(this.head.next); + } + + /** Removes the last node at the end of the list */ + pop(): T | null { + return this.remove(this.head.prev); + } + + /** Iterates through the list and removes nodes where filter returns true */ + prune(filter: (value: T) => boolean) { + for (const node of this.nodes()) { + if (filter(node.value)) { + this.remove(node); + } + } + } + + clear() { + this.count = 0; + this.head.next = this.head as EmptyNode; + this.head.prev = this.head as EmptyNode; + } + + /** Returns the first item in the list, does not remove */ + first(): T | null { + // If the list is empty, value will be the head's null + return this.head.next.value; + } + + /** Returns the last item in the list, does not remove */ + last(): T | null { + // If the list is empty, value will be the head's null + return this.head.prev.value; + } +} + +/** + * A pool of Buffers which allow you to read them as if they were one + * @internal + */ +export class BufferPool { + private buffers: List; + private totalByteLength: number; + + constructor() { + this.buffers = new List(); + this.totalByteLength = 0; + } + + get length(): number { + return this.totalByteLength; + } + + /** Adds a buffer to the internal buffer pool list */ + append(buffer: Buffer): void { + this.buffers.push(buffer); + this.totalByteLength += buffer.length; + } + + /** + * If BufferPool contains 4 bytes or more construct an int32 from the leading bytes, + * otherwise return null. Size can be negative, caller should error check. + */ + getInt32(): number | null { + if (this.totalByteLength < 4) { + return null; + } + const firstBuffer = this.buffers.first(); + if (firstBuffer != null && firstBuffer.byteLength >= 4) { + return firstBuffer.readInt32LE(0); + } + + // Unlikely case: an int32 is split across buffers. + // Use read and put the returned buffer back on top + const top4Bytes = this.read(4); + const value = top4Bytes.readInt32LE(0); + + // Put it back. + this.totalByteLength += 4; + this.buffers.unshift(top4Bytes); + + return value; + } + + /** Reads the requested number of bytes, optionally consuming them */ + read(size: number): Buffer { + if (typeof size !== 'number' || size < 0) { + throw new MongoInvalidArgumentError('Argument "size" must be a non-negative number'); + } + + // oversized request returns empty buffer + if (size > this.totalByteLength) { + return Buffer.alloc(0); + } + + // We know we have enough, we just don't know how it is spread across chunks + // TODO(NODE-4732): alloc API should change based on raw option + const result = Buffer.allocUnsafe(size); + + for (let bytesRead = 0; bytesRead < size; ) { + const buffer = this.buffers.shift(); + if (buffer == null) { + break; + } + const bytesRemaining = size - bytesRead; + const bytesReadable = Math.min(bytesRemaining, buffer.byteLength); + const bytes = buffer.subarray(0, bytesReadable); + + result.set(bytes, bytesRead); + + bytesRead += bytesReadable; + this.totalByteLength -= bytesReadable; + if (bytesReadable < buffer.byteLength) { + this.buffers.unshift(buffer.subarray(bytesReadable)); + } + } + + return result; + } +} + +/** @public */ +export class HostAddress { + host: string | undefined = undefined; + port: number | undefined = undefined; + socketPath: string | undefined = undefined; + isIPv6 = false; + + constructor(hostString: string) { + const escapedHost = hostString.split(' ').join('%20'); // escape spaces, for socket path hosts + + if (escapedHost.endsWith('.sock')) { + // heuristically determine if we're working with a domain socket + this.socketPath = decodeURIComponent(escapedHost); + return; + } + + const urlString = `iLoveJS://${escapedHost}`; + let url; + try { + url = new URL(urlString); + } catch (urlError) { + const runtimeError = new MongoRuntimeError(`Unable to parse ${escapedHost} with URL`); + runtimeError.cause = urlError; + throw runtimeError; + } + + const hostname = url.hostname; + const port = url.port; + + 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'); + } + Object.freeze(this); + } + + [Symbol.for('nodejs.util.inspect.custom')](): string { + return this.inspect(); + } + + inspect(): string { + return `new HostAddress('${this.toString()}')`; + } + + toString(): string { + if (typeof this.host === 'string') { + if (this.isIPv6) { + 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 + * ```ts + * 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; +} + +/** + * 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(NODE-4936): read concern eligibility for commands 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. */ +export function getMongoDBClientEncryption(): { + extension: (mdb: unknown) => { + AutoEncrypter: any; + ClientEncryption: any; + }; +} | null { + let mongodbClientEncryption = null; + + // 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 + ) { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require(process.env.MONGODB_CLIENT_ENCRYPTION_OVERRIDE); + } catch { + // ignore + } + } else { + try { + // NOTE(NODE-3199): Ensure you always wrap an optional require literally in the try block + // Cannot be moved to helper utility function, bundlers search and replace the actual require call + // in a way that makes this line throw at bundle time, not runtime, catching here will make bundling succeed + mongodbClientEncryption = require('mongodb-client-encryption'); + } catch { + // ignore + } + } + + return mongodbClientEncryption; +} + +/** + * Compare objectIds. `null` is always less + * - `+1 = oid1 is greater than oid2` + * - `-1 = oid1 is less than oid2` + * - `+0 = oid1 is equal oid2` + */ +export function compareObjectId(oid1?: ObjectId | null, oid2?: ObjectId | null): 0 | 1 | -1 { + if (oid1 == null && oid2 == null) { + return 0; + } + + if (oid1 == null) { + return -1; + } + + if (oid2 == null) { + return 1; + } + + return ByteUtils.compare(oid1.id, oid2.id); +} + +export function parseInteger(value: unknown): number | null { + if (typeof value === 'number') return Math.trunc(value); + const parsedValue = Number.parseInt(String(value), 10); + + return Number.isNaN(parsedValue) ? null : parsedValue; +} + +export function parseUnsignedInteger(value: unknown): number | null { + const parsedInt = parseInteger(value); + + return parsedInt != null && parsedInt >= 0 ? parsedInt : null; +} diff --git a/2_PAC/node_modules/mongodb/src/write_concern.ts b/2_PAC/node_modules/mongodb/src/write_concern.ts new file mode 100644 index 00000000..ebc77ebf --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/mongodb/tsconfig.json b/2_PAC/node_modules/mongodb/tsconfig.json new file mode 100644 index 00000000..55dd558a --- /dev/null +++ b/2_PAC/node_modules/mongodb/tsconfig.json @@ -0,0 +1,46 @@ +{ + "compilerOptions": { + "allowJs": false, + "checkJs": false, + "strict": true, + "alwaysStrict": true, + "target": "ES2020", + "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/2_PAC/node_modules/saslprep/.editorconfig b/2_PAC/node_modules/saslprep/.editorconfig new file mode 100644 index 00000000..d1d8a417 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/.gitattributes b/2_PAC/node_modules/saslprep/.gitattributes new file mode 100644 index 00000000..3ba45360 --- /dev/null +++ b/2_PAC/node_modules/saslprep/.gitattributes @@ -0,0 +1 @@ +*.mem binary diff --git a/2_PAC/node_modules/saslprep/.travis.yml b/2_PAC/node_modules/saslprep/.travis.yml new file mode 100644 index 00000000..0bca8265 --- /dev/null +++ b/2_PAC/node_modules/saslprep/.travis.yml @@ -0,0 +1,10 @@ +sudo: false +language: node_js +node_js: + - "6" + - "8" + - "10" + - "12" + +before_install: +- npm install -g npm@6 diff --git a/2_PAC/node_modules/saslprep/CHANGELOG.md b/2_PAC/node_modules/saslprep/CHANGELOG.md new file mode 100644 index 00000000..77980787 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/LICENSE b/2_PAC/node_modules/saslprep/LICENSE new file mode 100644 index 00000000..481c7a50 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/code-points.mem b/2_PAC/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;yp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^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/2_PAC/node_modules/saslprep/lib/code-points.js b/2_PAC/node_modules/saslprep/lib/code-points.js new file mode 100644 index 00000000..222182c8 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/lib/memory-code-points.js b/2_PAC/node_modules/saslprep/lib/memory-code-points.js new file mode 100644 index 00000000..cb0289c8 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/lib/util.js b/2_PAC/node_modules/saslprep/lib/util.js new file mode 100644 index 00000000..506bdc99 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/package.json b/2_PAC/node_modules/saslprep/package.json new file mode 100644 index 00000000..23c35627 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/readme.md b/2_PAC/node_modules/saslprep/readme.md new file mode 100644 index 00000000..8ff3d70d --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/test/index.js b/2_PAC/node_modules/saslprep/test/index.js new file mode 100644 index 00000000..80c71af5 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/saslprep/test/util.js b/2_PAC/node_modules/saslprep/test/util.js new file mode 100644 index 00000000..355db3f8 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/smart-buffer/.prettierrc.yaml b/2_PAC/node_modules/smart-buffer/.prettierrc.yaml new file mode 100644 index 00000000..9a4f5ed7 --- /dev/null +++ b/2_PAC/node_modules/smart-buffer/.prettierrc.yaml @@ -0,0 +1,5 @@ +parser: typescript +printWidth: 120 +tabWidth: 2 +singleQuote: true +trailingComma: none \ No newline at end of file diff --git a/2_PAC/node_modules/smart-buffer/.travis.yml b/2_PAC/node_modules/smart-buffer/.travis.yml new file mode 100644 index 00000000..eec71cec --- /dev/null +++ b/2_PAC/node_modules/smart-buffer/.travis.yml @@ -0,0 +1,13 @@ +language: node_js +node_js: + - 6 + - 8 + - 10 + - 12 + - stable + +before_script: + - npm install -g typescript + - tsc -p ./ + +script: "npm run coveralls" \ No newline at end of file diff --git a/2_PAC/node_modules/smart-buffer/LICENSE b/2_PAC/node_modules/smart-buffer/LICENSE new file mode 100644 index 00000000..aab5771a --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/smart-buffer/README.md b/2_PAC/node_modules/smart-buffer/README.md new file mode 100644 index 00000000..6e498288 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/smart-buffer/build/smartbuffer.js b/2_PAC/node_modules/smart-buffer/build/smartbuffer.js new file mode 100644 index 00000000..5353ae11 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/smart-buffer/build/smartbuffer.js.map b/2_PAC/node_modules/smart-buffer/build/smartbuffer.js.map new file mode 100644 index 00000000..37f0d6e1 --- /dev/null +++ b/2_PAC/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,CA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AY,CAAC;QAE1E,0EAA0E;QAC1E,IAAI,CAAC,gBAAgB,CAAC,QAAQ,EAAE,SAAS,CAAC,CAAC;QAE3C,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;QAExC,mFAAmF;QACnF,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE;YAC9B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,YAAY,EAAE,SAAS,GAAG,QAAQ,CAAC,CAAC;SACvE;aAAM;YACL,mGAAmG;YACnG,IAAI,CAAC,YAAY,IAAI,QAAQ,CAAC;SAC/B;QAED,OAAO,IAAI,CAAC;IACd,CAAC;CACF;AAE4B,kCAAW"} \ No newline at end of file diff --git a/2_PAC/node_modules/smart-buffer/build/utils.js b/2_PAC/node_modules/smart-buffer/build/utils.js new file mode 100644 index 00000000..6d559812 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/smart-buffer/build/utils.js.map b/2_PAC/node_modules/smart-buffer/build/utils.js.map new file mode 100644 index 00000000..fc7388d3 --- /dev/null +++ b/2_PAC/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,SA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IAAI,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,KAAK,CAAC;AACrF,CAAC;AAcD;;GAEG;AACH,SAAS,yBAAyB,CAAC,YAA0B;IAC3D,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE;QACjC,MAAM,IAAI,KAAK,CAAC,2CAA2C,CAAC,CAAC;KAC9D;IAED,IAAI,OAAO,eAAM,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK,WAAW,EAAE;QACzD,MAAM,IAAI,KAAK,CAAC,8CAA8C,YAAY,GAAG,CAAC,CAAC;KAChF;AACH,CAAC;AAIsC,8DAAyB"} \ No newline at end of file diff --git a/2_PAC/node_modules/smart-buffer/docs/CHANGELOG.md b/2_PAC/node_modules/smart-buffer/docs/CHANGELOG.md new file mode 100644 index 00000000..1199a4d6 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/smart-buffer/docs/README_v3.md b/2_PAC/node_modules/smart-buffer/docs/README_v3.md new file mode 100644 index 00000000..b7c48b8b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/smart-buffer/docs/ROADMAP.md b/2_PAC/node_modules/smart-buffer/docs/ROADMAP.md new file mode 100644 index 00000000..e69de29b diff --git a/2_PAC/node_modules/smart-buffer/package.json b/2_PAC/node_modules/smart-buffer/package.json new file mode 100644 index 00000000..2f326f24 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/smart-buffer/typings/smartbuffer.d.ts b/2_PAC/node_modules/smart-buffer/typings/smartbuffer.d.ts new file mode 100644 index 00000000..d07379b2 --- /dev/null +++ b/2_PAC/node_modules/smart-buffer/typings/smartbuffer.d.ts @@ -0,0 +1,755 @@ +/// +/** + * Object interface for constructing new SmartBuffer instances. + */ +interface SmartBufferOptions { + encoding?: BufferEncoding; + size?: number; + buff?: Buffer; +} +declare class SmartBuffer { + length: number; + private _encoding; + private _buff; + private _writeOffset; + private _readOffset; + /** + * Creates a new SmartBuffer instance. + * + * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. + */ + constructor(options?: SmartBufferOptions); + /** + * 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: number, encoding?: BufferEncoding): SmartBuffer; + /** + * 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: Buffer, encoding?: BufferEncoding): SmartBuffer; + /** + * 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: SmartBufferOptions): SmartBuffer; + /** + * Type checking function that determines if an object is a SmartBufferOptions object. + */ + static isSmartBufferOptions(options: SmartBufferOptions): options is SmartBufferOptions; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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?: number): bigint; + /** + * 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?: number): bigint; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: bigint, offset?: number): SmartBuffer; + /** + * 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: bigint, offset: number): SmartBuffer; + /** + * 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: bigint, offset?: number): SmartBuffer; + /** + * 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: bigint, offset: number): SmartBuffer; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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?: number): bigint; + /** + * 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?: number): bigint; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: bigint, offset?: number): SmartBuffer; + /** + * 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: bigint, offset: number): SmartBuffer; + /** + * 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: bigint, offset?: number): SmartBuffer; + /** + * 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: bigint, offset: number): SmartBuffer; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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?: number): number; + /** + * 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?: number): number; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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: number, offset?: number): SmartBuffer; + /** + * 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: number, offset: number): SmartBuffer; + /** + * 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?: number | BufferEncoding, encoding?: BufferEncoding): string; + /** + * 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: string, offset: number, encoding?: BufferEncoding): SmartBuffer; + /** + * 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: string, arg2?: number | BufferEncoding, encoding?: BufferEncoding): SmartBuffer; + /** + * 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?: BufferEncoding): string; + /** + * 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: string, offset: number, encoding?: BufferEncoding): SmartBuffer; + /** + * 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: string, arg2?: number | BufferEncoding, encoding?: BufferEncoding): SmartBuffer; + /** + * Reads a Buffer from the internal read position. + * + * @param length { Number } The length of data to read as a Buffer. + * + * @return { Buffer } + */ + readBuffer(length?: number): Buffer; + /** + * 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: Buffer, offset: number): SmartBuffer; + /** + * 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: Buffer, offset?: number): SmartBuffer; + /** + * Reads a null-terminated Buffer from the current read poisiton. + * + * @return { Buffer } + */ + readBufferNT(): Buffer; + /** + * 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: Buffer, offset: number): SmartBuffer; + /** + * 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: Buffer, offset?: number): SmartBuffer; + /** + * Clears the SmartBuffer instance to its original empty state. + */ + clear(): SmartBuffer; + /** + * Gets the remaining data left to be read from the SmartBuffer instance. + * + * @return { Number } + */ + remaining(): number; + /** + * Gets the current read offset value of the SmartBuffer instance. + * + * @return { Number } + */ + /** + * Sets the read offset value of the SmartBuffer instance. + * + * @param offset { Number } - The offset value to set. + */ + readOffset: number; + /** + * Gets the current write offset value of the SmartBuffer instance. + * + * @return { Number } + */ + /** + * Sets the write offset value of the SmartBuffer instance. + * + * @param offset { Number } - The offset value to set. + */ + writeOffset: number; + /** + * Gets the currently set string encoding of the SmartBuffer instance. + * + * @return { BufferEncoding } The string Buffer encoding currently set. + */ + /** + * Sets the string encoding of the SmartBuffer instance. + * + * @param encoding { BufferEncoding } The string Buffer encoding to set. + */ + encoding: BufferEncoding; + /** + * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer) + * + * @return { Buffer } The Buffer value. + */ + readonly internalBuffer: Buffer; + /** + * Gets the value of the internal managed Buffer (Includes managed data only) + * + * @param { Buffer } + */ + toBuffer(): Buffer; + /** + * 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?: BufferEncoding): string; + /** + * Destroys the SmartBuffer instance. + */ + destroy(): SmartBuffer; + /** + * 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). + */ + private _handleString; + /** + * Handles writing or insert of a Buffer. + * + * @param value { Buffer } The Buffer to write. + * @param offset { Number } The offset to write the Buffer to. + */ + private _handleBuffer; + /** + * 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. + */ + private ensureReadable; + /** + * 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. + */ + private ensureInsertable; + /** + * 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). + */ + private _ensureWriteable; + /** + * 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. + */ + private _ensureCapacity; + /** + * 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 + */ + private _readNumberValue; + /** + * 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 + */ + private _insertNumberValue; + /** + * 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 + */ + private _writeNumberValue; +} +export { SmartBufferOptions, SmartBuffer }; diff --git a/2_PAC/node_modules/smart-buffer/typings/utils.d.ts b/2_PAC/node_modules/smart-buffer/typings/utils.d.ts new file mode 100644 index 00000000..b32b4d44 --- /dev/null +++ b/2_PAC/node_modules/smart-buffer/typings/utils.d.ts @@ -0,0 +1,66 @@ +/// +import { SmartBuffer } from './smartbuffer'; +import { Buffer } from 'buffer'; +/** + * Error strings + */ +declare const ERRORS: { + INVALID_ENCODING: string; + INVALID_SMARTBUFFER_SIZE: string; + INVALID_SMARTBUFFER_BUFFER: string; + INVALID_SMARTBUFFER_OBJECT: string; + INVALID_OFFSET: string; + INVALID_OFFSET_NON_NUMBER: string; + INVALID_LENGTH: string; + INVALID_LENGTH_NON_NUMBER: string; + INVALID_TARGET_OFFSET: string; + INVALID_TARGET_LENGTH: string; + INVALID_READ_BEYOND_BOUNDS: string; + INVALID_WRITE_BEYOND_BOUNDS: string; +}; +/** + * Checks if a given encoding is a valid Buffer encoding. (Throws an exception if check fails) + * + * @param { String } encoding The encoding string to check. + */ +declare function checkEncoding(encoding: BufferEncoding): void; +/** + * Checks if a given number is a finite integer. (Throws an exception if check fails) + * + * @param { Number } value The number value to check. + */ +declare function isFiniteInteger(value: number): boolean; +/** + * Checks if a length value is valid. (Throws an exception if check fails) + * + * @param { Number } length The value to check. + */ +declare function checkLengthValue(length: any): void; +/** + * Checks if a offset value is valid. (Throws an exception if check fails) + * + * @param { Number } offset The value to check. + */ +declare function checkOffsetValue(offset: any): void; +/** + * 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. + */ +declare function checkTargetOffset(offset: number, buff: SmartBuffer): void; +interface Buffer { + readBigInt64BE(offset?: number): bigint; + readBigInt64LE(offset?: number): bigint; + readBigUInt64BE(offset?: number): bigint; + readBigUInt64LE(offset?: number): bigint; + writeBigInt64BE(value: bigint, offset?: number): number; + writeBigInt64LE(value: bigint, offset?: number): number; + writeBigUInt64BE(value: bigint, offset?: number): number; + writeBigUInt64LE(value: bigint, offset?: number): number; +} +/** + * Throws if Node.js version is too low to support bigint + */ +declare function bigIntAndBufferInt64Check(bufferMethod: keyof Buffer): void; +export { ERRORS, isFiniteInteger, checkEncoding, checkOffsetValue, checkLengthValue, checkTargetOffset, bigIntAndBufferInt64Check }; diff --git a/2_PAC/node_modules/socks/.eslintrc.cjs b/2_PAC/node_modules/socks/.eslintrc.cjs new file mode 100644 index 00000000..cc5d089e --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/.prettierrc.yaml b/2_PAC/node_modules/socks/.prettierrc.yaml new file mode 100644 index 00000000..d7b73350 --- /dev/null +++ b/2_PAC/node_modules/socks/.prettierrc.yaml @@ -0,0 +1,7 @@ +parser: typescript +printWidth: 80 +tabWidth: 2 +singleQuote: true +trailingComma: all +arrowParens: always +bracketSpacing: false \ No newline at end of file diff --git a/2_PAC/node_modules/socks/LICENSE b/2_PAC/node_modules/socks/LICENSE new file mode 100644 index 00000000..b2442a9e --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/README.md b/2_PAC/node_modules/socks/README.md new file mode 100644 index 00000000..b796220c --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/build/client/socksclient.js b/2_PAC/node_modules/socks/build/client/socksclient.js new file mode 100644 index 00000000..c3439169 --- /dev/null +++ b/2_PAC/node_modules/socks/build/client/socksclient.js @@ -0,0 +1,793 @@ +"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); + } + } + // Shuffle proxies + if (options.randomizeChain) { + (0, util_1.shuffleArray)(options.proxies); + } + try { + let sock; + 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, + existing_socket: sock, + }); + // If sock is undefined, assign it here. + 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/2_PAC/node_modules/socks/build/client/socksclient.js.map b/2_PAC/node_modules/socks/build/client/socksclient.js.map new file mode 100644 index 00000000..f01f317e --- /dev/null +++ b/2_PAC/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;AAw7B5D,iGAx7BM,uBAAgB,OAw7BN;AA95BlB,MAAM,WAAY,SAAQ,qBAAY;IAgBpC,YAAY,OAA2B;QACrC,KAAK,EAAE,CAAC;QACR,IAAI,CAAC,OAAO,qBACP,OAAO,CACX,CAAC;QAEF,8BAA8B;QAC9B,IAAA,oCAA0B,EAAC,OAAO,CAAC,CAAC;QAEpC,gBAAgB;QAChB,IAAI,CAAC,QAAQ,CAAC,4BAAgB,CAAC,OAAO,CAAC,CAAC;IAC1C,CAAC;IAED;;;;;;;OAOG;IACH,MAAM,CAAC,gBAAgB,CACrB,OAA2B,EAC3B,QAGS;QAET,OAAO,IAAI,OAAO,CAA8B,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAClE,8BAA8B;YAC9B,IAAI;gBACF,IAAA,oCAA0B,EAAC,OAAO,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC;aAClD;YAAC,OAAO,GAAG,EAAE;gBACZ,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;oBAClC,QAAQ,CAAC,GAAG,CAAC,CAAC;oBACd,8DAA8D;oBAC9D,OAAO,OAAO,CAAC,GAAU,CAAC,CAAC,CAAC,oDAAoD;iBACjF;qBAAM;oBACL,OAAO,MAAM,CAAC,GAAG,CAAC,CAAC;iBACpB;aACF;YAED,MAAM,MAAM,GAAG,IAAI,WAAW,CAAC,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC;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,CAC5C,CAAC;gBAEF,UAAU,GAAG;oBACX,IAAI,EAAE,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC;oBACjC,IAAI,EAAE,IAAI,CAAC,YAAY,EAAE;iBAC1B,CAAC;gBACF,OAAO;aACR;iBAAM,IAAI,WAAW,KAAK,0BAAc,CAAC,IAAI,EAAE;gBAC9C,8BAA8B;gBAC9B,MAAM,UAAU,GAAG,uCAA2B,CAAC,kBAAkB,CAAC;gBAClE,IAAI,IAAI,CAAC,aAAa,CAAC,MAAM,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/2_PAC/node_modules/socks/build/common/constants.js b/2_PAC/node_modules/socks/build/common/constants.js new file mode 100644 index 00000000..3c9ff90a --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/build/common/constants.js.map b/2_PAC/node_modules/socks/build/common/constants.js.map new file mode 100644 index 00000000..c1e070de --- /dev/null +++ b/2_PAC/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;IACr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AACjB,CAAC,EAJI,UAAU,KAAV,UAAU,QAId;AA+IC,gCAAU;AA7IZ,MAAM,wBAAwB,GAAG,IAAI,CAAC;AA0JpC,4DAAwB;AAzJ1B,MAAM,sBAAsB,GAAG,IAAI,CAAC;AA0JlC,wDAAsB;AAxJxB,MAAM,yBAAyB,GAAG,IAAI,CAAC;AAyJrC,8DAAyB;AAvJ3B,IAAK,cAUJ;AAVD,WAAK,cAAc;IACjB,yDAAc,CAAA;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/2_PAC/node_modules/socks/build/common/helpers.js b/2_PAC/node_modules/socks/build/common/helpers.js new file mode 100644 index 00000000..f84db8f6 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/build/common/helpers.js.map b/2_PAC/node_modules/socks/build/common/helpers.js.map new file mode 100644 index 00000000..dae12486 --- /dev/null +++ b/2_PAC/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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AA2B;IACzD,OAAO,CACL,UAAU;QACV,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ;QACnC,OAAO,UAAU,CAAC,IAAI,KAAK,QAAQ;QACnC,UAAU,CAAC,IAAI,IAAI,CAAC;QACpB,UAAU,CAAC,IAAI,IAAI,KAAK,CACzB,CAAC;AACJ,CAAC;AAED;;;GAGG;AACH,SAAS,iBAAiB,CAAC,KAAiB;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/2_PAC/node_modules/socks/build/common/receivebuffer.js b/2_PAC/node_modules/socks/build/common/receivebuffer.js new file mode 100644 index 00000000..3dacbf9b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/build/common/receivebuffer.js.map b/2_PAC/node_modules/socks/build/common/receivebuffer.js.map new file mode 100644 index 00000000..af5e2209 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/build/common/util.js b/2_PAC/node_modules/socks/build/common/util.js new file mode 100644 index 00000000..f66b72e4 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/build/common/util.js.map b/2_PAC/node_modules/socks/build/common/util.js.map new file mode 100644 index 00000000..f1993233 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/build/index.js b/2_PAC/node_modules/socks/build/index.js new file mode 100644 index 00000000..05fbb1d9 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/build/index.js.map b/2_PAC/node_modules/socks/build/index.js.map new file mode 100644 index 00000000..0e2bcb27 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/examples/index.md b/2_PAC/node_modules/socks/docs/examples/index.md new file mode 100644 index 00000000..87bfe250 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/examples/javascript/associateExample.md b/2_PAC/node_modules/socks/docs/examples/javascript/associateExample.md new file mode 100644 index 00000000..c2c7b17b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/examples/javascript/bindExample.md b/2_PAC/node_modules/socks/docs/examples/javascript/bindExample.md new file mode 100644 index 00000000..be601d52 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/examples/javascript/connectExample.md b/2_PAC/node_modules/socks/docs/examples/javascript/connectExample.md new file mode 100644 index 00000000..66244c5b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/examples/typescript/associateExample.md b/2_PAC/node_modules/socks/docs/examples/typescript/associateExample.md new file mode 100644 index 00000000..e8ca1934 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/examples/typescript/bindExample.md b/2_PAC/node_modules/socks/docs/examples/typescript/bindExample.md new file mode 100644 index 00000000..6b7607df --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/examples/typescript/connectExample.md b/2_PAC/node_modules/socks/docs/examples/typescript/connectExample.md new file mode 100644 index 00000000..30606d0b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/index.md b/2_PAC/node_modules/socks/docs/index.md new file mode 100644 index 00000000..3eb1d711 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/docs/migratingFromV1.md b/2_PAC/node_modules/socks/docs/migratingFromV1.md new file mode 100644 index 00000000..dd008384 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/socks/typings/client/socksclient.d.ts b/2_PAC/node_modules/socks/typings/client/socksclient.d.ts new file mode 100644 index 00000000..b886d957 --- /dev/null +++ b/2_PAC/node_modules/socks/typings/client/socksclient.d.ts @@ -0,0 +1,162 @@ +/// +/// +/// +import { EventEmitter } from 'events'; +import { SocksClientOptions, SocksClientChainOptions, SocksRemoteHost, SocksProxy, SocksClientBoundEvent, SocksClientEstablishedEvent, SocksUDPFrameDetails } from '../common/constants'; +import { SocksClientError } from '../common/util'; +import { Duplex } from 'stream'; +declare interface SocksClient { + on(event: 'error', listener: (err: SocksClientError) => void): this; + on(event: 'bound', listener: (info: SocksClientBoundEvent) => void): this; + on(event: 'established', listener: (info: SocksClientEstablishedEvent) => void): this; + once(event: string, listener: (...args: unknown[]) => void): this; + once(event: 'error', listener: (err: SocksClientError) => void): this; + once(event: 'bound', listener: (info: SocksClientBoundEvent) => void): this; + once(event: 'established', listener: (info: SocksClientEstablishedEvent) => void): this; + emit(event: string | symbol, ...args: unknown[]): boolean; + emit(event: 'error', err: SocksClientError): boolean; + emit(event: 'bound', info: SocksClientBoundEvent): boolean; + emit(event: 'established', info: SocksClientEstablishedEvent): boolean; +} +declare class SocksClient extends EventEmitter implements SocksClient { + private options; + private socket; + private state; + private receiveBuffer; + private nextRequiredPacketBufferSize; + private socks5ChosenAuthType; + private onDataReceived; + private onClose; + private onError; + private onConnect; + constructor(options: SocksClientOptions); + /** + * 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: SocksClientOptions, callback?: (error: Error | null, info?: SocksClientEstablishedEvent) => void): Promise; + /** + * 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: SocksClientChainOptions, callback?: (error: Error | null, socket?: SocksClientEstablishedEvent) => void): Promise; + /** + * Creates a SOCKS UDP Frame. + * @param options + */ + static createUDPFrame(options: SocksUDPFrameDetails): Buffer; + /** + * Parses a SOCKS UDP frame. + * @param data + */ + static parseUDPFrame(data: Buffer): SocksUDPFrameDetails; + /** + * Internal state setter. If the SocksClient is in an error state, it cannot be changed to a non error state. + */ + private setState; + /** + * 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?: Duplex): void; + private getSocketOptions; + /** + * Handles internal Socks timeout callback. + * Note: If the Socks client is not BoundWaitingForConnection or Established, the connection will be closed. + */ + private onEstablishedTimeout; + /** + * Handles Socket connect event. + */ + private onConnectHandler; + /** + * Handles Socket data event. + * @param data + */ + private onDataReceivedHandler; + /** + * Handles processing of the data we have received. + */ + private processData; + /** + * Handles Socket close event. + * @param had_error + */ + private onCloseHandler; + /** + * Handles Socket error event. + * @param err + */ + private onErrorHandler; + /** + * Removes internal event listeners on the underlying Socket. + */ + private removeInternalSocketHandlers; + /** + * Closes and destroys the underlying Socket. Emits an error event. + * @param err { String } An error string to include in error event. + */ + private closeSocket; + /** + * Sends initial Socks v4 handshake request. + */ + private sendSocks4InitialHandshake; + /** + * Handles Socks v4 handshake response. + * @param data + */ + private handleSocks4FinalHandshakeResponse; + /** + * Handles Socks v4 incoming connection request (BIND) + * @param data + */ + private handleSocks4IncomingConnectionResponse; + /** + * Sends initial Socks v5 handshake request. + */ + private sendSocks5InitialHandshake; + /** + * Handles initial Socks v5 handshake response. + * @param data + */ + private handleInitialSocks5HandshakeResponse; + /** + * Sends Socks v5 user & password auth handshake. + * + * Note: No auth and user/pass are currently supported. + */ + private sendSocks5UserPassAuthentication; + private sendSocks5CustomAuthentication; + private handleSocks5CustomAuthHandshakeResponse; + private handleSocks5AuthenticationNoAuthHandshakeResponse; + private handleSocks5AuthenticationUserPassHandshakeResponse; + /** + * Handles Socks v5 auth handshake response. + * @param data + */ + private handleInitialSocks5AuthenticationHandshakeResponse; + /** + * Sends Socks v5 final handshake request. + */ + private sendSocks5CommandRequest; + /** + * Handles Socks v5 final handshake response. + * @param data + */ + private handleSocks5FinalHandshakeResponse; + /** + * Handles Socks v5 incoming connection request (BIND). + */ + private handleSocks5IncomingConnectionResponse; + get socksClientOptions(): SocksClientOptions; +} +export { SocksClient, SocksClientOptions, SocksClientChainOptions, SocksClientError, SocksRemoteHost, SocksProxy, SocksUDPFrameDetails, }; diff --git a/2_PAC/node_modules/socks/typings/common/constants.d.ts b/2_PAC/node_modules/socks/typings/common/constants.d.ts new file mode 100644 index 00000000..32a57052 --- /dev/null +++ b/2_PAC/node_modules/socks/typings/common/constants.d.ts @@ -0,0 +1,152 @@ +/// +/// +/// +import { Duplex } from 'stream'; +import { Socket, SocketConnectOpts } from 'net'; +import { RequireOnlyOne } from './util'; +declare const DEFAULT_TIMEOUT = 30000; +declare type SocksProxyType = 4 | 5; +declare const ERRORS: { + InvalidSocksCommand: string; + InvalidSocksCommandForOperation: string; + InvalidSocksCommandChain: string; + InvalidSocksClientOptionsDestination: string; + InvalidSocksClientOptionsExistingSocket: string; + InvalidSocksClientOptionsProxy: string; + InvalidSocksClientOptionsTimeout: string; + InvalidSocksClientOptionsProxiesLength: string; + InvalidSocksClientOptionsCustomAuthRange: string; + InvalidSocksClientOptionsCustomAuthOptions: string; + NegotiationError: string; + SocketClosed: string; + ProxyConnectionTimedOut: string; + InternalError: string; + InvalidSocks4HandshakeResponse: string; + Socks4ProxyRejectedConnection: string; + InvalidSocks4IncomingConnectionResponse: string; + Socks4ProxyRejectedIncomingBoundConnection: string; + InvalidSocks5InitialHandshakeResponse: string; + InvalidSocks5IntiailHandshakeSocksVersion: string; + InvalidSocks5InitialHandshakeNoAcceptedAuthType: string; + InvalidSocks5InitialHandshakeUnknownAuthType: string; + Socks5AuthenticationFailed: string; + InvalidSocks5FinalHandshake: string; + InvalidSocks5FinalHandshakeRejected: string; + InvalidSocks5IncomingConnectionResponse: string; + Socks5ProxyRejectedIncomingBoundConnection: string; +}; +declare const SOCKS_INCOMING_PACKET_SIZES: { + Socks5InitialHandshakeResponse: number; + Socks5UserPassAuthenticationResponse: number; + Socks5ResponseHeader: number; + Socks5ResponseIPv4: number; + Socks5ResponseIPv6: number; + Socks5ResponseHostname: (hostNameLength: number) => number; + Socks4Response: number; +}; +declare type SocksCommandOption = 'connect' | 'bind' | 'associate'; +declare enum SocksCommand { + connect = 1, + bind = 2, + associate = 3 +} +declare enum Socks4Response { + Granted = 90, + Failed = 91, + Rejected = 92, + RejectedIdent = 93 +} +declare enum Socks5Auth { + NoAuth = 0, + GSSApi = 1, + UserPass = 2 +} +declare const SOCKS5_CUSTOM_AUTH_START = 128; +declare const SOCKS5_CUSTOM_AUTH_END = 254; +declare const SOCKS5_NO_ACCEPTABLE_AUTH = 255; +declare enum Socks5Response { + Granted = 0, + Failure = 1, + NotAllowed = 2, + NetworkUnreachable = 3, + HostUnreachable = 4, + ConnectionRefused = 5, + TTLExpired = 6, + CommandNotSupported = 7, + AddressNotSupported = 8 +} +declare enum Socks5HostType { + IPv4 = 1, + Hostname = 3, + IPv6 = 4 +} +declare enum SocksClientState { + Created = 0, + Connecting = 1, + Connected = 2, + SentInitialHandshake = 3, + ReceivedInitialHandshakeResponse = 4, + SentAuthentication = 5, + ReceivedAuthenticationResponse = 6, + SentFinalHandshake = 7, + ReceivedFinalResponse = 8, + BoundWaitingForConnection = 9, + Established = 10, + Disconnected = 11, + Error = 99 +} +/** + * Represents a SocksProxy + */ +declare type SocksProxy = RequireOnlyOne<{ + ipaddress?: string; + host?: string; + port: number; + type: SocksProxyType; + userId?: string; + password?: string; + custom_auth_method?: number; + custom_auth_request_handler?: () => Promise; + custom_auth_response_size?: number; + custom_auth_response_handler?: (data: Buffer) => Promise; +}, 'host' | 'ipaddress'>; +/** + * Represents a remote host + */ +interface SocksRemoteHost { + host: string; + port: number; +} +/** + * SocksClient connection options. + */ +interface SocksClientOptions { + command: SocksCommandOption; + destination: SocksRemoteHost; + proxy: SocksProxy; + timeout?: number; + existing_socket?: Duplex; + set_tcp_nodelay?: boolean; + socket_options?: SocketConnectOpts; +} +/** + * SocksClient chain connection options. + */ +interface SocksClientChainOptions { + command: 'connect'; + destination: SocksRemoteHost; + proxies: SocksProxy[]; + timeout?: number; + randomizeChain?: false; +} +interface SocksClientEstablishedEvent { + socket: Socket; + remoteHost?: SocksRemoteHost; +} +declare type SocksClientBoundEvent = SocksClientEstablishedEvent; +interface SocksUDPFrameDetails { + frameNumber?: number; + remoteHost: SocksRemoteHost; + data: Buffer; +} +export { DEFAULT_TIMEOUT, ERRORS, SocksProxyType, SocksCommand, Socks4Response, Socks5Auth, Socks5HostType, Socks5Response, SocksClientState, SocksProxy, SocksRemoteHost, SocksCommandOption, SocksClientOptions, SocksClientChainOptions, SocksClientEstablishedEvent, SocksClientBoundEvent, SocksUDPFrameDetails, SOCKS_INCOMING_PACKET_SIZES, SOCKS5_CUSTOM_AUTH_START, SOCKS5_CUSTOM_AUTH_END, SOCKS5_NO_ACCEPTABLE_AUTH, }; diff --git a/2_PAC/node_modules/socks/typings/common/helpers.d.ts b/2_PAC/node_modules/socks/typings/common/helpers.d.ts new file mode 100644 index 00000000..8c3a1069 --- /dev/null +++ b/2_PAC/node_modules/socks/typings/common/helpers.d.ts @@ -0,0 +1,13 @@ +import { SocksClientOptions, SocksClientChainOptions } from '../client/socksclient'; +/** + * Validates the provided SocksClientOptions + * @param options { SocksClientOptions } + * @param acceptedCommands { string[] } A list of accepted SocksProxy commands. + */ +declare function validateSocksClientOptions(options: SocksClientOptions, acceptedCommands?: string[]): void; +/** + * Validates the SocksClientChainOptions + * @param options { SocksClientChainOptions } + */ +declare function validateSocksClientChainOptions(options: SocksClientChainOptions): void; +export { validateSocksClientOptions, validateSocksClientChainOptions }; diff --git a/2_PAC/node_modules/socks/typings/common/receivebuffer.d.ts b/2_PAC/node_modules/socks/typings/common/receivebuffer.d.ts new file mode 100644 index 00000000..756e98b5 --- /dev/null +++ b/2_PAC/node_modules/socks/typings/common/receivebuffer.d.ts @@ -0,0 +1,12 @@ +/// +declare class ReceiveBuffer { + private buffer; + private offset; + private originalSize; + constructor(size?: number); + get length(): number; + append(data: Buffer): number; + peek(length: number): Buffer; + get(length: number): Buffer; +} +export { ReceiveBuffer }; diff --git a/2_PAC/node_modules/socks/typings/common/util.d.ts b/2_PAC/node_modules/socks/typings/common/util.d.ts new file mode 100644 index 00000000..83f20e7b --- /dev/null +++ b/2_PAC/node_modules/socks/typings/common/util.d.ts @@ -0,0 +1,17 @@ +import { SocksClientOptions, SocksClientChainOptions } from './constants'; +/** + * Error wrapper for SocksClient + */ +declare class SocksClientError extends Error { + options: SocksClientOptions | SocksClientChainOptions; + constructor(message: string, options: SocksClientOptions | SocksClientChainOptions); +} +/** + * Shuffles a given array. + * @param array The array to shuffle. + */ +declare function shuffleArray(array: unknown[]): void; +declare type RequireOnlyOne = Pick> & { + [K in Keys]?: Required> & Partial, undefined>>; +}[Keys]; +export { RequireOnlyOne, SocksClientError, shuffleArray }; diff --git a/2_PAC/node_modules/socks/typings/index.d.ts b/2_PAC/node_modules/socks/typings/index.d.ts new file mode 100644 index 00000000..fbf9006e --- /dev/null +++ b/2_PAC/node_modules/socks/typings/index.d.ts @@ -0,0 +1 @@ +export * from './client/socksclient'; diff --git a/2_PAC/node_modules/sparse-bitfield/.npmignore b/2_PAC/node_modules/sparse-bitfield/.npmignore new file mode 100644 index 00000000..3c3629e6 --- /dev/null +++ b/2_PAC/node_modules/sparse-bitfield/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/2_PAC/node_modules/sparse-bitfield/.travis.yml b/2_PAC/node_modules/sparse-bitfield/.travis.yml new file mode 100644 index 00000000..c0428217 --- /dev/null +++ b/2_PAC/node_modules/sparse-bitfield/.travis.yml @@ -0,0 +1,6 @@ +language: node_js +node_js: + - '0.10' + - '0.12' + - '4.0' + - '5.0' diff --git a/2_PAC/node_modules/sparse-bitfield/LICENSE b/2_PAC/node_modules/sparse-bitfield/LICENSE new file mode 100644 index 00000000..bae9da7b --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/sparse-bitfield/README.md b/2_PAC/node_modules/sparse-bitfield/README.md new file mode 100644 index 00000000..7b6b8f9e --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/sparse-bitfield/index.js b/2_PAC/node_modules/sparse-bitfield/index.js new file mode 100644 index 00000000..ff458c97 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/sparse-bitfield/package.json b/2_PAC/node_modules/sparse-bitfield/package.json new file mode 100644 index 00000000..092a23f6 --- /dev/null +++ b/2_PAC/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/2_PAC/node_modules/sparse-bitfield/test.js b/2_PAC/node_modules/sparse-bitfield/test.js new file mode 100644 index 00000000..ae42ef46 --- /dev/null +++ b/2_PAC/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/2_PAC/package-lock.json b/2_PAC/package-lock.json index 2f91834b..37298196 100644 --- a/2_PAC/package-lock.json +++ b/2_PAC/package-lock.json @@ -1,2990 +1,6510 @@ { - "name": "PacFactory", + + "name": "2_PAC", + "lockfileVersion": 2, + "requires": true, + "packages": { + "": { + "dependencies": { + "@arces-wot/sepa-js": "^0.12.1", + "body-parser": "^1.20.1", + "express": "^4.18.2", + + "mongodb": "^5.0.1", + "mysql": "^2.18.1", + "mysql2": "^2.3.3", + "node-fetch": "^3.3.0", + "op-client": "^1.4.2", + "request": "^2.88.2" + } + }, + "node_modules/@arces-wot/sepa-js": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/@arces-wot/sepa-js/-/sepa-js-0.12.1.tgz", + "integrity": "sha512-lvilgudP7hrfqHB9+uxY34tNeUO7f8sCs7D19xjCpqHVAdbBpWz4hHUt+8H7+wTDGV2XaJCPaex6SbRnQUzbgw==", + "dependencies": { + "axios": "^0.19.0", + "deepmerge": "^4.2.2", + "isomorphic-ws": "^4.0.0", + "ws": "^6.0.0" + } + }, + "node_modules/@servie/events": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@servie/events/-/events-1.0.0.tgz", + "integrity": "sha512-sBSO19KzdrJCM3gdx6eIxV8M9Gxfgg6iDQmH5TIAGaUu+X9VDdsINXJOnoiZ1Kx3TrHdH4bt5UVglkjsEGBcvw==" - }, + + }, + + "node_modules/@types/node": { + + "version": "18.13.0", + + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.13.0.tgz", + + "integrity": "sha512-gC3TazRzGoOnoKAhUx+Q0t8S9Tzs74z7m0ipwGpSqQrleP14hKxP4/JUeEQcD3W1/aIpnWl8pHowI7WokuZpXg==" + + }, + "node_modules/@types/tough-cookie": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-2.3.8.tgz", + "integrity": "sha512-7axfYN8SW9pWg78NgenHasSproWQee5rzyPVLC9HpaQSDgNArsnKJD88EaMfi4Pl48AyciO3agYCFqpHS1gLpg==" + + }, + + "node_modules/@types/webidl-conversions": { + + "version": "7.0.0", + + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + + "integrity": "sha512-xTE1E+YF4aWPJJeUzaZI5DRntlkY3+BCVJi0axFptnjGmAoWxkyREIh/XMrfxVLejwQxMCfDXdICo0VLxThrog==" + + }, + + "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/101": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/101/-/101-1.6.3.tgz", + "integrity": "sha512-4dmQ45yY0Dx24Qxp+zAsNLlMF6tteCyfVzgbulvSyC7tCyd3V8sW76sS0tHq8NpcbXfWTKasfyfzU1Kd86oKzw==", + "dependencies": { + "clone": "^1.0.2", + "deep-eql": "^0.1.3", + "keypather": "^1.10.2" + } + }, + "node_modules/101/node_modules/keypather": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/keypather/-/keypather-1.10.2.tgz", + "integrity": "sha512-hgomDZ+POrsgpkE7qQuSI2ffyfVLJdDLxk8spzWeR33ovNssz6jCWDOIBLEPyI8SAWcQ5njl1ignlqgMrZsGpA==", + "dependencies": { + "101": "^1.0.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "dependencies": { + "safer-buffer": "~2.1.0" + } + }, + "node_modules/assert-err": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assert-err/-/assert-err-1.1.0.tgz", + "integrity": "sha512-dEOsK5ngosvrne66QiI3D3nsvTesIMhiiH0tYC5sISAFFzvZza0PFxWWanNcoBX90McFTRsebVkR0ApXxtkGqA==", + "dependencies": { + "escape-string-regexp": "^1.0.5", + "object-assign": "^4.1.0" + } + }, + "node_modules/assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/async-limiter": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz", + "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==", + "engines": { + "node": "*" + } + }, + "node_modules/aws4": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.12.0.tgz", + "integrity": "sha512-NmWvPnx0F1SfrQbYwOi7OeaNGokp9XhzNioJ/CSBs8Qa4vxug81mhJEAVZwxXuBmYB5KDRfMq/F3RR0BIU7sWg==" + }, + "node_modules/axios": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz", + "integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==", + "deprecated": "Critical security vulnerability fixed in v0.21.1. For more information, see https://github.com/axios/axios/pull/3410", + "dependencies": { + "follow-redirects": "1.5.10" + } + }, + "node_modules/bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "dependencies": { + "tweetnacl": "^0.14.3" + } + }, + "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.20.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", + "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", + "dependencies": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + + } + + }, + + "node_modules/bson": { + + "version": "5.0.0", + + "resolved": "https://registry.npmjs.org/bson/-/bson-5.0.0.tgz", + + "integrity": "sha512-EL2KpZdyhshyyptj6pnQfnFKPoncD9KwZYvgmj/FXQiOUU1HWTHWmBOP4TZXU3YzStcI5qgpIl68YnMo16s26A==", + + "engines": { + + "node": ">=14.20.1" + } + }, + "node_modules/byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/byte-length/-/byte-length-1.0.2.tgz", + "integrity": "sha512-ovBpjmsgd/teRmgcPh23d4gJvxDoXtAzEL9xTfMU8Yc2kqCDb7L9jAG0XHl1nzuGl+h3ebCIF1i62UFyA9V/2Q==" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==" + }, + "node_modules/client-oauth2": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/client-oauth2/-/client-oauth2-4.3.3.tgz", + "integrity": "sha512-k8AvUYJon0vv75ufoVo4nALYb/qwFFicO3I0+39C6xEdflqVtr+f9cy+0ZxAduoVSTfhP5DX2tY2XICAd5hy6Q==", + "dependencies": { + "popsicle": "^12.0.5", + "safe-buffer": "^5.2.0" + }, + "engines": { + "node": ">=4.2.0" + } + }, + "node_modules/clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==", + "engines": { + "node": ">=0.8" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, + "node_modules/cross-fetch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", + "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", + "dependencies": { + "node-fetch": "2.6.7" + } + }, + "node_modules/cross-fetch/node_modules/node-fetch": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==", + "dependencies": { + "assert-plus": "^1.0.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/deep-eql": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-0.1.3.tgz", + "integrity": "sha512-6sEotTRGBFiNcqVoeHwnfopbSpi5NbH1VWJmYCVkmxMmaVTT0bUTrNaGyBwhgP4MZL012W/mkzIn3Da+iDYweg==", + "dependencies": { + "type-detect": "0.1.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.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": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==", + "dependencies": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express": { + "version": "4.18.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", + "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.1", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.5.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + } + }, + "node_modules/extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "node_modules/extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==", + "engines": [ + "node >=0.6.0" + ] + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/follow-redirects": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", + "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", + "dependencies": { + "debug": "=3.1.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/follow-redirects/node_modules/debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==", + "engines": { + "node": "*" + } + }, + "node_modules/form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 0.12" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/get-intrinsic": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.3.tgz", + "integrity": "sha512-QJVz1Tj7MS099PevUG5jvnt9tSkXN8K14dxQlikJuPt4uD9hHAHjLyLBiLR5zELelBdD9QNRAXZzsJx0WaDL9A==", + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==", + "dependencies": { + "assert-plus": "^1.0.0" + } + }, + "node_modules/har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==", + "engines": { + "node": ">=4" + } + }, + "node_modules/har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "deprecated": "this library is no longer supported", + "dependencies": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==", + "dependencies": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + }, + "engines": { + "node": ">=0.8", + "npm": ">=1.3.7" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + + "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/ip-regex": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", + "integrity": "sha512-58yWmlHpp7VYfcdTwMTvwMmqx/Elfxjd9RXTDyMsbL7lLWmhMylLEqiYVLKuLzOZqVgiWXD9MfR62Vv89VRxkw==", + "engines": { + "node": ">=4" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==" + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==" + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + }, + "node_modules/iso8601-duration": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/iso8601-duration/-/iso8601-duration-1.3.0.tgz", + "integrity": "sha512-K4CiUBzo3YeWk76FuET/dQPH03WE04R94feo5TSKQCXpoXQt9E4yx2CnY737QZnSAI3PI4WlKo/zfqizGx52QQ==" + }, + "node_modules/isomorphic-ws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-4.0.1.tgz", + "integrity": "sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w==", + "peerDependencies": { + "ws": "*" + } + }, + "node_modules/isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==" + }, + "node_modules/jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==" + }, + "node_modules/json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==" + }, + "node_modules/jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", + "dependencies": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + }, + "engines": { + "node": ">=0.6.0" + } + }, + "node_modules/keypather": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/keypather/-/keypather-3.1.0.tgz", + "integrity": "sha512-DsxfrBVXlQihWmefW/lNvVgtzFoSoDd67mCsop7a+tK9h7ybpBF5YRUXg192GBmOc3gn4IEv3AV69HElXYuCLA==", + "dependencies": { + "101": "^1.6.2", + "debug": "^3.1.0", + "escape-string-regexp": "^1.0.5", + "shallow-clone": "^3.0.0", + "string-reduce": "^1.0.0" + } + }, + "node_modules/keypather/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/keypather/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" + }, + "node_modules/make-error-cause": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/make-error-cause/-/make-error-cause-2.3.0.tgz", + "integrity": "sha512-etgt+n4LlOkGSJbBTV9VROHA5R7ekIPS4vfh+bCAoJgRrJWdqJCBbpS3osRJ/HrT7R68MzMiY3L3sDJ/Fd8aBg==", + "dependencies": { + "make-error": "^1.3.5" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "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", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + + "node_modules/mongodb": { + + "version": "5.0.1", + + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.0.1.tgz", + + "integrity": "sha512-KpjtY+NWFmcic6UDYEdfn768ZTuKyv7CRaui7ZSd6q/0/o1AURMC7KygTUwB1Cl8V10Pe5NiP+Y2eBMCDs/ygQ==", + + "dependencies": { + + "bson": "^5.0.0", + + "mongodb-connection-string-url": "^2.6.0", + + "socks": "^2.7.1" + + }, + + "engines": { + + "node": ">=14.20.1" + + }, + + "optionalDependencies": { + + "saslprep": "^1.0.3" + + }, + + "peerDependencies": { + + "@aws-sdk/credential-providers": "^3.201.0", + + "mongodb-client-encryption": "^2.3.0", + + "snappy": "^7.2.2" + + }, + + "peerDependenciesMeta": { + + "@aws-sdk/credential-providers": { + + "optional": true + + }, + + "mongodb-client-encryption": { + + "optional": true + + }, + + "snappy": { + + "optional": true + + } + + } + + }, + + "node_modules/mongodb-connection-string-url": { + + "version": "2.6.0", + + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", + + "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + + "dependencies": { + + "@types/whatwg-url": "^8.2.1", + + "whatwg-url": "^11.0.0" + + } + + }, + + "node_modules/mongodb-connection-string-url/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/mongodb-connection-string-url/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/mongodb-connection-string-url/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/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "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/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/mysql2": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-2.3.3.tgz", + "integrity": "sha512-wxJUev6LgMSgACDkb/InIFxDprRa6T95+VEoR+xPvtngtccNH2dGjEB/fVZ8yg1gWv1510c9CvXuJHi5zUm0ZA==", + "dependencies": { + "denque": "^2.0.1", + "generate-function": "^2.3.1", + "iconv-lite": "^0.6.3", + "long": "^4.0.0", + "lru-cache": "^6.0.0", + "named-placeholders": "^1.1.2", + "seq-queue": "^0.0.5", + "sqlstring": "^2.3.2" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/mysql2/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/mysql2/node_modules/sqlstring": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz", + "integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.2.tgz", + "integrity": "sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA==", + "dependencies": { + "lru-cache": "^4.1.3" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/named-placeholders/node_modules/lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "dependencies": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "node_modules/named-placeholders/node_modules/yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha512-ncTzHV7NvsQZkYe1DW7cbDLm0YpzHmZF5r/iyP3ZnQtMiJ+pjzisCiMNI+Sj+xQF5pXhSHxSB3uDbsBTzY/c2A==" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.0.tgz", + "integrity": "sha512-BKwRP/O0UvoMKp7GNdwPlObhYGB5DQqwhEDQlNKuoqwVYSxkSZCSbHjnFFmUEtwSKRPU4kNK8PbDYYitwaE3QA==", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==", + "engines": { + "node": "*" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.2.tgz", + "integrity": "sha512-z+cPxW0QGUp0mcqcsgQyLVRDoXFQbXOwBaqyF7VIgI4TWNQsDHrBpUQslRmIfAoYWdYzs6UlKJtB2XJpTaNSpQ==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/op-client": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/op-client/-/op-client-1.4.2.tgz", + "integrity": "sha512-IgOMyXLHzqVvQM6YZ0qpP7d3UXO2kQPukZAMEh/2b3iC73XNcSMFo9TTXSWpJYYZaBhKvkLhDI39UdJj9+Z/Xg==", + "dependencies": { + "client-oauth2": "^4.3.3", + "cross-fetch": "^3.0.5", + "iso8601-duration": "^1.2.0", + "keypather": "^3.1.0", + "reflect-metadata": "^0.1.10" + } + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + }, + "node_modules/performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==" + }, + "node_modules/popsicle": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/popsicle/-/popsicle-12.1.0.tgz", + "integrity": "sha512-muNC/cIrWhfR6HqqhHazkxjob3eyECBe8uZYSQ/N5vixNAgssacVleerXnE8Are5fspR0a+d2qWaBR1g7RYlmw==", + "dependencies": { + "popsicle-content-encoding": "^1.0.0", + "popsicle-cookie-jar": "^1.0.0", + "popsicle-redirects": "^1.1.0", + "popsicle-transport-http": "^1.0.8", + "popsicle-transport-xhr": "^2.0.0", + "popsicle-user-agent": "^1.0.0", + "servie": "^4.3.3", + "throwback": "^4.1.0" + } + }, + "node_modules/popsicle-content-encoding": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-content-encoding/-/popsicle-content-encoding-1.0.0.tgz", + "integrity": "sha512-4Df+vTfM8wCCJVTzPujiI6eOl3SiWQkcZg0AMrOkD1enMXsF3glIkFUZGvour1Sj7jOWCsNSEhBxpbbhclHhzw==", + "peerDependencies": { + "servie": "^4.0.0" + } + }, + "node_modules/popsicle-cookie-jar": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-cookie-jar/-/popsicle-cookie-jar-1.0.0.tgz", + "integrity": "sha512-vrlOGvNVELko0+J8NpGC5lHWDGrk8LQJq9nwAMIVEVBfN1Lib3BLxAaLRGDTuUnvl45j5N9dT2H85PULz6IjjQ==", + "dependencies": { + "@types/tough-cookie": "^2.3.5", + "tough-cookie": "^3.0.1" + }, + "peerDependencies": { + "servie": "^4.0.0" + } + }, + "node_modules/popsicle-redirects": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/popsicle-redirects/-/popsicle-redirects-1.1.1.tgz", + "integrity": "sha512-mC2HrKjdTAWDalOjGxlXw9j6Qxrz/Yd2ui6bPxpi2IQDYWpF4gUAMxbA8EpSWJhLi0PuWKDwTHHPrUPGutAoIA==", + "peerDependencies": { + "servie": "^4.1.0" + } + }, + "node_modules/popsicle-transport-http": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/popsicle-transport-http/-/popsicle-transport-http-1.2.1.tgz", + "integrity": "sha512-i5r3IGHkGiBDm1oPFvOfEeSGWR0lQJcsdTqwvvDjXqcTHYJJi4iSi3ecXIttDiTBoBtRAFAE9nF91fspQr63FQ==", + "dependencies": { + "make-error-cause": "^2.2.0" + }, + "peerDependencies": { + "servie": "^4.2.0" + } + }, + "node_modules/popsicle-transport-xhr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/popsicle-transport-xhr/-/popsicle-transport-xhr-2.0.0.tgz", + "integrity": "sha512-5Sbud4Widngf1dodJE5cjEYXkzEUIl8CzyYRYR57t6vpy9a9KPGQX6KBKdPjmBZlR5A06pOBXuJnVr23l27rtA==", + "peerDependencies": { + "servie": "^4.2.0" + } + }, + "node_modules/popsicle-user-agent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-user-agent/-/popsicle-user-agent-1.0.0.tgz", + "integrity": "sha512-epKaq3TTfTzXcxBxjpoKYMcTTcAX8Rykus6QZu77XNhJuRHSRxMd+JJrbX/3PFI0opFGSN0BabbAYCbGxbu0mA==", + "peerDependencies": { + "servie": "^4.0.0" + } + }, + "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/proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha512-b/YwNhb8lk1Zz2+bXXpS/LK9OisiZZ1SNsSLxN1x2OXVEhW2Ckr/7mWE5vrC1ZTiJlD9g19jWszTmJsB+oEpFQ==" + }, + "node_modules/psl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", + "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==" + }, + "node_modules/punycode": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.2.0.tgz", + "integrity": "sha512-LN6QV1IJ9ZhxWTNdktaPClrNfp8xdSAYS0Zk2ddX7XsXZAxckMHPCBcHRo0cTcEIgYPRiGEkmji3Idkh2yFtYw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/raw-body": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "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/readable-stream/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/reflect-metadata": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", + "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==" + }, + "node_modules/request": { + "version": "2.88.2", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", + "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "deprecated": "request has been deprecated, see https://github.com/request/request/issues/3142", + "dependencies": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/request/node_modules/qs": { + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/request/node_modules/tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "dependencies": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "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/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + + }, + + "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.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/seq-queue": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", + "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==" + }, + "node_modules/serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "dependencies": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/servie": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/servie/-/servie-4.3.3.tgz", + "integrity": "sha512-b0IrY3b1gVMsWvJppCf19g1p3JSnS0hQi6xu4Hi40CIhf0Lx8pQHcvBL+xunShpmOiQzg1NOia812NAWdSaShw==", + "dependencies": { + "@servie/events": "^1.0.0", + "byte-length": "^1.0.2", + "ts-expect": "^1.1.0" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "node_modules/shallow-clone": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", + "dependencies": { + "kind-of": "^6.0.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + + } + + }, + + "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.1", + + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", + + "integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", + + "dependencies": { + + "ip": "^2.0.0", + + "smart-buffer": "^4.2.0" + + }, + + "engines": { + + "node": ">= 10.13.0", + + "npm": ">= 3.0.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/sshpk": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz", + "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", + "dependencies": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + }, + "bin": { + "sshpk-conv": "bin/sshpk-conv", + "sshpk-sign": "bin/sshpk-sign", + "sshpk-verify": "bin/sshpk-verify" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "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/string_decoder/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/string-reduce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string-reduce/-/string-reduce-1.0.0.tgz", + "integrity": "sha512-Sc7/l7xG8TvJrC1+LNowFgAyW0jerj73NHPJo66ijTQCbveJ2TRHoq+mACTLzlFTO7V30ESzb23qTU6wB0VNCQ==", + "dependencies": { + "assert-err": "^1.1.0" + } + }, + "node_modules/throwback": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/throwback/-/throwback-4.1.0.tgz", + "integrity": "sha512-dLFe8bU8SeH0xeqeKL7BNo8XoPC/o91nz9/ooeplZPiso+DZukhoyZcSz9TFnUNScm+cA9qjU1m1853M6sPOng==" + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tough-cookie": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-3.0.1.tgz", + "integrity": "sha512-yQyJ0u4pZsv9D4clxO69OEjLWYw+jbgspjTue4lTQZLfV0c5l1VmK2y1JK8E9ahdpltPOaAThPcp5nKPUgSnsg==", + "dependencies": { + "ip-regex": "^2.1.0", + "psl": "^1.1.28", + "punycode": "^2.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "node_modules/ts-expect": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/ts-expect/-/ts-expect-1.3.0.tgz", + "integrity": "sha512-e4g0EJtAjk64xgnFPD6kTBUtpnMVzDrMb12N1YZV0VvSlhnVT3SGxiYTLdGy8Q5cYHOIC/FAHmZ10eGrAguicQ==" + }, + "node_modules/tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "engines": { + "node": "*" + } + }, + "node_modules/tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==" + }, + "node_modules/type-detect": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-0.1.1.tgz", + "integrity": "sha512-5rqszGVwYgBoDkIm2oUtvkfZMQ0vk29iDMU0W2qCa3rG0vPDNczCMT4hV/bLBgLg8k8ri6+u3Zbt+S/14eMzlA==", + "engines": { + "node": "*" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==", + "deprecated": "Please upgrade to version 7 or higher. Older versions may use Math.random() in certain circumstances, which is known to be problematic. See https://v8.dev/blog/math-random for details.", + "bin": { + "uuid": "bin/uuid" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==", + "engines": [ + "node >=0.6.0" + ], + "dependencies": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + } + }, + "node_modules/verror/node_modules/core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" + }, + "node_modules/web-streams-polyfill": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/ws": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-6.2.2.tgz", + "integrity": "sha512-zmhltoSR8u1cnDsD43TX59mzoMZsLKqUweyYBAIvTngR3shc0W6aOZylZmq/7hqyVxPdi+5Ud2QInblgyE72fw==", + "dependencies": { + "async-limiter": "~1.0.0" + } + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + } + }, + "dependencies": { + "101": { + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/101/-/101-1.6.3.tgz", + "integrity": "sha512-4dmQ45yY0Dx24Qxp+zAsNLlMF6tteCyfVzgbulvSyC7tCyd3V8sW76sS0tHq8NpcbXfWTKasfyfzU1Kd86oKzw==", + "requires": { + "clone": "^1.0.2", + "deep-eql": "^0.1.3", + "keypather": "^1.10.2" + }, + "dependencies": { + "keypather": { + "version": "1.10.2", + "resolved": "https://registry.npmjs.org/keypather/-/keypather-1.10.2.tgz", + "integrity": "sha512-hgomDZ+POrsgpkE7qQuSI2ffyfVLJdDLxk8spzWeR33ovNssz6jCWDOIBLEPyI8SAWcQ5njl1ignlqgMrZsGpA==", + "requires": { + "101": "^1.0.0" + } + } + } + }, + "@arces-wot/sepa-js": { + "version": "0.12.1", + "resolved": "https://registry.npmjs.org/@arces-wot/sepa-js/-/sepa-js-0.12.1.tgz", + "integrity": "sha512-lvilgudP7hrfqHB9+uxY34tNeUO7f8sCs7D19xjCpqHVAdbBpWz4hHUt+8H7+wTDGV2XaJCPaex6SbRnQUzbgw==", + "requires": { + "axios": "^0.19.0", + "deepmerge": "^4.2.2", + "isomorphic-ws": "^4.0.0", + "ws": "^6.0.0" + } + }, + "@servie/events": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@servie/events/-/events-1.0.0.tgz", + "integrity": "sha512-sBSO19KzdrJCM3gdx6eIxV8M9Gxfgg6iDQmH5TIAGaUu+X9VDdsINXJOnoiZ1Kx3TrHdH4bt5UVglkjsEGBcvw==" - }, + + }, + + "@types/node": { + + "version": "18.13.0", + + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.13.0.tgz", + + "integrity": "sha512-gC3TazRzGoOnoKAhUx+Q0t8S9Tzs74z7m0ipwGpSqQrleP14hKxP4/JUeEQcD3W1/aIpnWl8pHowI7WokuZpXg==" + + }, + "@types/tough-cookie": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/@types/tough-cookie/-/tough-cookie-2.3.8.tgz", + "integrity": "sha512-7axfYN8SW9pWg78NgenHasSproWQee5rzyPVLC9HpaQSDgNArsnKJD88EaMfi4Pl48AyciO3agYCFqpHS1gLpg==" + + }, + + "@types/webidl-conversions": { + + "version": "7.0.0", + + "resolved": "https://registry.npmjs.org/@types/webidl-conversions/-/webidl-conversions-7.0.0.tgz", + + "integrity": "sha512-xTE1E+YF4aWPJJeUzaZI5DRntlkY3+BCVJi0axFptnjGmAoWxkyREIh/XMrfxVLejwQxMCfDXdICo0VLxThrog==" + + }, + + "@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.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "requires": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + } + }, + "ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "requires": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + } + }, + "array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "asn1": { + "version": "0.2.6", + "resolved": "https://registry.npmjs.org/asn1/-/asn1-0.2.6.tgz", + "integrity": "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ==", + "requires": { + "safer-buffer": "~2.1.0" + } + }, + "assert-err": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assert-err/-/assert-err-1.1.0.tgz", + "integrity": "sha512-dEOsK5ngosvrne66QiI3D3nsvTesIMhiiH0tYC5sISAFFzvZza0PFxWWanNcoBX90McFTRsebVkR0ApXxtkGqA==", + "requires": { + "escape-string-regexp": "^1.0.5", + "object-assign": "^4.1.0" + } + }, + "assert-plus": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-1.0.0.tgz", + "integrity": "sha512-NfJ4UzBCcQGLDlQq7nHxH+tv3kyZ0hHQqF5BO6J7tNJeP5do1llPr8dZ8zHonfhAu0PHAdMkSo+8o0wxg9lZWw==" + }, + "async-limiter": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.1.tgz", + "integrity": "sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==" + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "aws-sign2": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/aws-sign2/-/aws-sign2-0.7.0.tgz", + "integrity": "sha512-08kcGqnYf/YmjoRhfxyu+CLxBjUtHLXLXX/vUfx9l2LYzG3c1m61nrpyFUZI6zeS+Li/wWMMidD9KgrqtGq3mA==" + }, + "aws4": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.12.0.tgz", + "integrity": "sha512-NmWvPnx0F1SfrQbYwOi7OeaNGokp9XhzNioJ/CSBs8Qa4vxug81mhJEAVZwxXuBmYB5KDRfMq/F3RR0BIU7sWg==" + }, + "axios": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-0.19.2.tgz", + "integrity": "sha512-fjgm5MvRHLhx+osE2xoekY70AhARk3a6hkN+3Io1jc00jtquGvxYlKlsFUhmUET0V5te6CcZI7lcv2Ym61mjHA==", + "requires": { + "follow-redirects": "1.5.10" + } + }, + "bcrypt-pbkdf": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/bcrypt-pbkdf/-/bcrypt-pbkdf-1.0.2.tgz", + "integrity": "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w==", + "requires": { + "tweetnacl": "^0.14.3" + } + }, + "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.20.1", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.1.tgz", + "integrity": "sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==", + "requires": { + "bytes": "3.1.2", + "content-type": "~1.0.4", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "on-finished": "2.4.1", + "qs": "6.11.0", + "raw-body": "2.5.1", + "type-is": "~1.6.18", + "unpipe": "1.0.0" + } + + }, + + "bson": { + + "version": "5.0.0", + + "resolved": "https://registry.npmjs.org/bson/-/bson-5.0.0.tgz", + + "integrity": "sha512-EL2KpZdyhshyyptj6pnQfnFKPoncD9KwZYvgmj/FXQiOUU1HWTHWmBOP4TZXU3YzStcI5qgpIl68YnMo16s26A==" + }, + "byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/byte-length/-/byte-length-1.0.2.tgz", + "integrity": "sha512-ovBpjmsgd/teRmgcPh23d4gJvxDoXtAzEL9xTfMU8Yc2kqCDb7L9jAG0XHl1nzuGl+h3ebCIF1i62UFyA9V/2Q==" + }, + "bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==" + }, + "call-bind": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "requires": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + } + }, + "caseless": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/caseless/-/caseless-0.12.0.tgz", + "integrity": "sha512-4tYFyifaFfGacoiObjJegolkwSU4xQNGbVgUiNYVUxbQ2x2lUsFvY4hVgVzGiIe6WLOPqycWXA40l+PWsxthUw==" + }, + "client-oauth2": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/client-oauth2/-/client-oauth2-4.3.3.tgz", + "integrity": "sha512-k8AvUYJon0vv75ufoVo4nALYb/qwFFicO3I0+39C6xEdflqVtr+f9cy+0ZxAduoVSTfhP5DX2tY2XICAd5hy6Q==", + "requires": { + "popsicle": "^12.0.5", + "safe-buffer": "^5.2.0" + } + }, + "clone": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", + "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==" + }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "requires": { + "safe-buffer": "5.2.1" + } + }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==" + }, + "cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==" + }, + "cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, + "cross-fetch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", + "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", + "requires": { + "node-fetch": "2.6.7" + }, + "dependencies": { + "node-fetch": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", + "requires": { + "whatwg-url": "^5.0.0" + } + } + } + }, + "dashdash": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/dashdash/-/dashdash-1.14.1.tgz", + "integrity": "sha512-jRFi8UDGo6j+odZiEpjazZaWqEal3w/basFjQHQEwVtZJGDpxbH1MeYluwCS8Xq5wmLJooDlMgvVarmWfGM44g==", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "data-uri-to-buffer": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-4.0.1.tgz", + "integrity": "sha512-0R9ikRb668HB7QDxT1vkpuUBtqc53YyAwMwGeUFKRojY/NWKvdZ+9UYtRfGmhqNbRkTSVpMbmyhXipFFv2cb/A==" + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "deep-eql": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-0.1.3.tgz", + "integrity": "sha512-6sEotTRGBFiNcqVoeHwnfopbSpi5NbH1VWJmYCVkmxMmaVTT0bUTrNaGyBwhgP4MZL012W/mkzIn3Da+iDYweg==", + "requires": { + "type-detect": "0.1.1" + } + }, + "deepmerge": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.2.2.tgz", + "integrity": "sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==" + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==" + }, + "denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==" + }, + "depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" + }, + "destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==" + }, + "ecc-jsbn": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/ecc-jsbn/-/ecc-jsbn-0.1.2.tgz", + "integrity": "sha512-eh9O+hwRHNbG4BLTjEl3nw044CkGm5X6LoaCf7LPp7UU8Qrt47JYNi6nPX8xjW97TKGKm1ouctg0QSpZe9qrnw==", + "requires": { + "jsbn": "~0.1.0", + "safer-buffer": "^2.1.0" + } + }, + "ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==" + }, + "escape-html": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" + }, + "escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==" + }, + "etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==" + }, + "express": { + "version": "4.18.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz", + "integrity": "sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==", + "requires": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "1.20.1", + "content-disposition": "0.5.4", + "content-type": "~1.0.4", + "cookie": "0.5.0", + "cookie-signature": "1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "1.2.0", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "merge-descriptors": "1.0.1", + "methods": "~1.1.2", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "0.1.7", + "proxy-addr": "~2.0.7", + "qs": "6.11.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "0.18.0", + "serve-static": "1.15.0", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + } + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "extsprintf": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.3.0.tgz", + "integrity": "sha512-11Ndz7Nv+mvAC1j0ktTa7fAb0vLyGGX+rMHNBYQviQDGU0Hw7lhctJANqbPhu9nV9/izT/IntTgZ7Im/9LJs9g==" + }, + "fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" + }, + "fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==" + }, + "fetch-blob": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", + "integrity": "sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==", + "requires": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + } + }, + "finalhandler": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.2.0.tgz", + "integrity": "sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==", + "requires": { + "debug": "2.6.9", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + } + }, + "follow-redirects": { + "version": "1.5.10", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.5.10.tgz", + "integrity": "sha512-0V5l4Cizzvqt5D44aTXbFZz+FtyXV1vrDN6qrelxtfYQKW0KO0W2T/hkE8xvGa/540LkZlkaUjO4ailYTFtHVQ==", + "requires": { + "debug": "=3.1.0" + }, + "dependencies": { + "debug": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.1.0.tgz", + "integrity": "sha512-OX8XqP7/1a9cqkxYw2yXss15f26NKWBpDXQd0/uK/KPqdQhxbPa994hnzjcE2VqQpDslf55723cKPUOGSmMY3g==", + "requires": { + "ms": "2.0.0" + } + } + } + }, + "forever-agent": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/forever-agent/-/forever-agent-0.6.1.tgz", + "integrity": "sha512-j0KLYPhm6zeac4lz3oJ3o65qvgQCcPubiyotZrXqEaG4hNagNYO8qdlUrX5vwqv9ohqeT/Z3j6+yW067yWWdUw==" + }, + "form-data": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", + "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.6", + "mime-types": "^2.1.12" + } + }, + "formdata-polyfill": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz", + "integrity": "sha512-buewHzMvYL29jdeQTVILecSaZKnt/RJWjoZCF5OW60Z67/GmSLBkOFM7qh1PI3zFNtJbaZL5eQu1vLfazOwj4g==", + "requires": { + "fetch-blob": "^3.1.2" + } + }, + "forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==" + }, + "fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==" + }, + "function-bind": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==" + }, + "generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "requires": { + "is-property": "^1.0.2" + } + }, + "get-intrinsic": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.1.3.tgz", + "integrity": "sha512-QJVz1Tj7MS099PevUG5jvnt9tSkXN8K14dxQlikJuPt4uD9hHAHjLyLBiLR5zELelBdD9QNRAXZzsJx0WaDL9A==", + "requires": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-symbols": "^1.0.3" + } + }, + "getpass": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/getpass/-/getpass-0.1.7.tgz", + "integrity": "sha512-0fzj9JxOLfJ+XGLhR8ze3unN0KZCgZwiSSDz168VERjK8Wl8kVSdcu2kspd4s4wtAa1y/qrVRiAA0WclVsu0ng==", + "requires": { + "assert-plus": "^1.0.0" + } + }, + "har-schema": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/har-schema/-/har-schema-2.0.0.tgz", + "integrity": "sha512-Oqluz6zhGX8cyRaTQlFMPw80bSJVG2x/cFb8ZPhUILGgHka9SsokCCOQgpveePerqidZOrT14ipqfJb7ILcW5Q==" + }, + "har-validator": { + "version": "5.1.5", + "resolved": "https://registry.npmjs.org/har-validator/-/har-validator-5.1.5.tgz", + "integrity": "sha512-nmT2T0lljbxdQZfspsno9hgrG3Uir6Ks5afism62poxqBM6sDnMEuPmzTq8XN0OEwqKLLdh1jQI3qyE66Nzb3w==", + "requires": { + "ajv": "^6.12.3", + "har-schema": "^2.0.0" + } + }, + "has": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "requires": { + "function-bind": "^1.1.1" + } + }, + "has-symbols": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==" + }, + "http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "requires": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + } + }, + "http-signature": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.2.0.tgz", + "integrity": "sha512-CAbnr6Rz4CYQkLYUtSNXxQPUH2gK8f3iWexVlsnMeD+GjlsQ0Xsy1cOX+mN3dtxYomRy21CiOzU8Uhw6OwncEQ==", + "requires": { + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" + } + }, + "iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3" + } + }, + "inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + + "ip": { + + "version": "2.0.0", + + "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.0.tgz", + + "integrity": "sha512-WKa+XuLG1A1R0UWhl2+1XQSi+fZWMsYKffMZTTYsiZaUD8k2yDAj5atimTUD2TZkyCkNEeYE5NhFZmupOGtjYQ==" + + }, + "ip-regex": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", + "integrity": "sha512-58yWmlHpp7VYfcdTwMTvwMmqx/Elfxjd9RXTDyMsbL7lLWmhMylLEqiYVLKuLzOZqVgiWXD9MfR62Vv89VRxkw==" + }, + "ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==" + }, + "is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==" + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==" + }, + "isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + }, + "iso8601-duration": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/iso8601-duration/-/iso8601-duration-1.3.0.tgz", + "integrity": "sha512-K4CiUBzo3YeWk76FuET/dQPH03WE04R94feo5TSKQCXpoXQt9E4yx2CnY737QZnSAI3PI4WlKo/zfqizGx52QQ==" + }, + "isomorphic-ws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-4.0.1.tgz", + "integrity": "sha512-BhBvN2MBpWTaSHdWRb/bwdZJ1WaehQ2L1KngkCkfLUGF0mAWAT1sQUQacEmQ0jXkFw/czDXPNQSL5u2/Krsz1w==", + "requires": {} + }, + "isstream": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.2.tgz", + "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==" + }, + "jsbn": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/jsbn/-/jsbn-0.1.1.tgz", + "integrity": "sha512-UVU9dibq2JcFWxQPA6KCqj5O42VOmAY3zQUfEKxU0KpTGXwNoCjkX1e13eHNvw/xPynt6pU0rZ1htjWTNTSXsg==" + }, + "json-schema": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz", + "integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==" + }, + "json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==" + }, + "json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==" + }, + "jsprim": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/jsprim/-/jsprim-1.4.2.tgz", + "integrity": "sha512-P2bSOMAc/ciLz6DzgjVlGJP9+BrJWu5UDGK70C2iweC5QBIeFf0ZXRvGjEj2uYgrY2MkAAhsSWHDWlFtEroZWw==", + "requires": { + "assert-plus": "1.0.0", + "extsprintf": "1.3.0", + "json-schema": "0.4.0", + "verror": "1.10.0" + } + }, + "keypather": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/keypather/-/keypather-3.1.0.tgz", + "integrity": "sha512-DsxfrBVXlQihWmefW/lNvVgtzFoSoDd67mCsop7a+tK9h7ybpBF5YRUXg192GBmOc3gn4IEv3AV69HElXYuCLA==", + "requires": { + "101": "^1.6.2", + "debug": "^3.1.0", + "escape-string-regexp": "^1.0.5", + "shallow-clone": "^3.0.0", + "string-reduce": "^1.0.0" + }, + "dependencies": { + "debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "requires": { + "ms": "^2.1.1" + } + }, + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, + "kind-of": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-6.0.3.tgz", + "integrity": "sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw==" + }, + "long": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/long/-/long-4.0.0.tgz", + "integrity": "sha512-XsP+KhQif4bjX1kbuSiySJFNAehNxgLb6hPRGJ9QsUr8ajHkuXGdrHmFUTUUXhDwVX2R5bY4JNZEwbUiMhV+MA==" + }, + "lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "requires": { + "yallist": "^4.0.0" + } + }, + "make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" + }, + "make-error-cause": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/make-error-cause/-/make-error-cause-2.3.0.tgz", + "integrity": "sha512-etgt+n4LlOkGSJbBTV9VROHA5R7ekIPS4vfh+bCAoJgRrJWdqJCBbpS3osRJ/HrT7R68MzMiY3L3sDJ/Fd8aBg==", + "requires": { + "make-error": "^1.3.5" + } + }, + "media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==" - }, + + }, + + "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", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.1.tgz", + "integrity": "sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==" + }, + "methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==" + }, + "mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==" + }, + "mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==" + }, + "mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "requires": { + "mime-db": "1.52.0" + } + }, + + "mongodb": { + + "version": "5.0.1", + + "resolved": "https://registry.npmjs.org/mongodb/-/mongodb-5.0.1.tgz", + + "integrity": "sha512-KpjtY+NWFmcic6UDYEdfn768ZTuKyv7CRaui7ZSd6q/0/o1AURMC7KygTUwB1Cl8V10Pe5NiP+Y2eBMCDs/ygQ==", + + "requires": { + + "bson": "^5.0.0", + + "mongodb-connection-string-url": "^2.6.0", + + "saslprep": "^1.0.3", + + "socks": "^2.7.1" + + } + + }, + + "mongodb-connection-string-url": { + + "version": "2.6.0", + + "resolved": "https://registry.npmjs.org/mongodb-connection-string-url/-/mongodb-connection-string-url-2.6.0.tgz", + + "integrity": "sha512-WvTZlI9ab0QYtTYnuMLgobULWhokRjtC7db9LtcVfJ+Hsnyr5eo6ZtNAt3Ly24XZScGMelOcGtm7lSn0332tPQ==", + + "requires": { + + "@types/whatwg-url": "^8.2.1", + + "whatwg-url": "^11.0.0" + + }, + + "dependencies": { + + "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" + + } + + }, + + "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" + + } + + } + + } + + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "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": { + "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==" + } + } + }, + "mysql2": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-2.3.3.tgz", + "integrity": "sha512-wxJUev6LgMSgACDkb/InIFxDprRa6T95+VEoR+xPvtngtccNH2dGjEB/fVZ8yg1gWv1510c9CvXuJHi5zUm0ZA==", + "requires": { + "denque": "^2.0.1", + "generate-function": "^2.3.1", + "iconv-lite": "^0.6.3", + "long": "^4.0.0", + "lru-cache": "^6.0.0", + "named-placeholders": "^1.1.2", + "seq-queue": "^0.0.5", + "sqlstring": "^2.3.2" + }, + "dependencies": { + "iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "requires": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + } + }, + "sqlstring": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz", + "integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==" + } + } + }, + "named-placeholders": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.2.tgz", + "integrity": "sha512-wiFWqxoLL3PGVReSZpjLVxyJ1bRqe+KKJVbr4hGs1KWfTZTQyezHFBbuKj9hsizHyGV2ne7EMjHdxEGAybD5SA==", + "requires": { + "lru-cache": "^4.1.3" + }, + "dependencies": { + "lru-cache": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-4.1.5.tgz", + "integrity": "sha512-sWZlbEP2OsHNkXrMl5GYk/jKk70MBng6UU4YI/qGDYbgf6YbP4EvmqISbXCoJiRKs+1bSpFHVgQxvJ17F2li5g==", + "requires": { + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" + } + }, + "yallist": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz", + "integrity": "sha512-ncTzHV7NvsQZkYe1DW7cbDLm0YpzHmZF5r/iyP3ZnQtMiJ+pjzisCiMNI+Sj+xQF5pXhSHxSB3uDbsBTzY/c2A==" + } + } + }, + "negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==" + }, + "node-domexception": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/node-domexception/-/node-domexception-1.0.0.tgz", + "integrity": "sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==" + }, + "node-fetch": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-3.3.0.tgz", + "integrity": "sha512-BKwRP/O0UvoMKp7GNdwPlObhYGB5DQqwhEDQlNKuoqwVYSxkSZCSbHjnFFmUEtwSKRPU4kNK8PbDYYitwaE3QA==", + "requires": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + } + }, + "oauth-sign": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.9.0.tgz", + "integrity": "sha512-fexhUFFPTGV8ybAtSIGbV6gOkSv8UtRbDBnAyLQw4QPKkgNlsH2ByPGtMUqdWkos6YCRmAqViwgZrJc/mRDzZQ==" + }, + "object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==" + }, + "object-inspect": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.2.tgz", + "integrity": "sha512-z+cPxW0QGUp0mcqcsgQyLVRDoXFQbXOwBaqyF7VIgI4TWNQsDHrBpUQslRmIfAoYWdYzs6UlKJtB2XJpTaNSpQ==" + }, + "on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "requires": { + "ee-first": "1.1.1" + } + }, + "op-client": { + "version": "1.4.2", + "resolved": "https://registry.npmjs.org/op-client/-/op-client-1.4.2.tgz", + "integrity": "sha512-IgOMyXLHzqVvQM6YZ0qpP7d3UXO2kQPukZAMEh/2b3iC73XNcSMFo9TTXSWpJYYZaBhKvkLhDI39UdJj9+Z/Xg==", + "requires": { + "client-oauth2": "^4.3.3", + "cross-fetch": "^3.0.5", + "iso8601-duration": "^1.2.0", + "keypather": "^3.1.0", + "reflect-metadata": "^0.1.10" + } + }, + "parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==" + }, + "path-to-regexp": { + "version": "0.1.7", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", + "integrity": "sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==" + }, + "performance-now": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/performance-now/-/performance-now-2.1.0.tgz", + "integrity": "sha512-7EAHlyLHI56VEIdK57uwHdHKIaAGbnXPiw0yWbarQZOKaKpvUIgW0jWRVLiatnM+XXlSwsanIBH/hzGMJulMow==" + }, + "popsicle": { + "version": "12.1.0", + "resolved": "https://registry.npmjs.org/popsicle/-/popsicle-12.1.0.tgz", + "integrity": "sha512-muNC/cIrWhfR6HqqhHazkxjob3eyECBe8uZYSQ/N5vixNAgssacVleerXnE8Are5fspR0a+d2qWaBR1g7RYlmw==", + "requires": { + "popsicle-content-encoding": "^1.0.0", + "popsicle-cookie-jar": "^1.0.0", + "popsicle-redirects": "^1.1.0", + "popsicle-transport-http": "^1.0.8", + "popsicle-transport-xhr": "^2.0.0", + "popsicle-user-agent": "^1.0.0", + "servie": "^4.3.3", + "throwback": "^4.1.0" + } + }, + "popsicle-content-encoding": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-content-encoding/-/popsicle-content-encoding-1.0.0.tgz", + "integrity": "sha512-4Df+vTfM8wCCJVTzPujiI6eOl3SiWQkcZg0AMrOkD1enMXsF3glIkFUZGvour1Sj7jOWCsNSEhBxpbbhclHhzw==", + "requires": {} + }, + "popsicle-cookie-jar": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-cookie-jar/-/popsicle-cookie-jar-1.0.0.tgz", + "integrity": "sha512-vrlOGvNVELko0+J8NpGC5lHWDGrk8LQJq9nwAMIVEVBfN1Lib3BLxAaLRGDTuUnvl45j5N9dT2H85PULz6IjjQ==", + "requires": { + "@types/tough-cookie": "^2.3.5", + "tough-cookie": "^3.0.1" + } + }, + "popsicle-redirects": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/popsicle-redirects/-/popsicle-redirects-1.1.1.tgz", + "integrity": "sha512-mC2HrKjdTAWDalOjGxlXw9j6Qxrz/Yd2ui6bPxpi2IQDYWpF4gUAMxbA8EpSWJhLi0PuWKDwTHHPrUPGutAoIA==", + "requires": {} + }, + "popsicle-transport-http": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/popsicle-transport-http/-/popsicle-transport-http-1.2.1.tgz", + "integrity": "sha512-i5r3IGHkGiBDm1oPFvOfEeSGWR0lQJcsdTqwvvDjXqcTHYJJi4iSi3ecXIttDiTBoBtRAFAE9nF91fspQr63FQ==", + "requires": { + "make-error-cause": "^2.2.0" + } + }, + "popsicle-transport-xhr": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/popsicle-transport-xhr/-/popsicle-transport-xhr-2.0.0.tgz", + "integrity": "sha512-5Sbud4Widngf1dodJE5cjEYXkzEUIl8CzyYRYR57t6vpy9a9KPGQX6KBKdPjmBZlR5A06pOBXuJnVr23l27rtA==", + "requires": {} + }, + "popsicle-user-agent": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/popsicle-user-agent/-/popsicle-user-agent-1.0.0.tgz", + "integrity": "sha512-epKaq3TTfTzXcxBxjpoKYMcTTcAX8Rykus6QZu77XNhJuRHSRxMd+JJrbX/3PFI0opFGSN0BabbAYCbGxbu0mA==", + "requires": {} + }, + "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==" + }, + "proxy-addr": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "requires": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + } + }, + "pseudomap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz", + "integrity": "sha512-b/YwNhb8lk1Zz2+bXXpS/LK9OisiZZ1SNsSLxN1x2OXVEhW2Ckr/7mWE5vrC1ZTiJlD9g19jWszTmJsB+oEpFQ==" + }, + "psl": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", + "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==" + }, + "punycode": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.2.0.tgz", + "integrity": "sha512-LN6QV1IJ9ZhxWTNdktaPClrNfp8xdSAYS0Zk2ddX7XsXZAxckMHPCBcHRo0cTcEIgYPRiGEkmji3Idkh2yFtYw==" + }, + "qs": { + "version": "6.11.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.11.0.tgz", + "integrity": "sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==", + "requires": { + "side-channel": "^1.0.4" + } + }, + "range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==" + }, + "raw-body": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.1.tgz", + "integrity": "sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==", + "requires": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + } + }, + "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" + }, + "dependencies": { + "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==" + } + } + }, + "reflect-metadata": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.1.13.tgz", + "integrity": "sha512-Ts1Y/anZELhSsjMcU605fU9RE4Oi3p5ORujwbIKXfWa+0Zxs510Qrmrce5/Jowq3cHSZSJqBjypxmHarc+vEWg==" + }, + "request": { + "version": "2.88.2", + "resolved": "https://registry.npmjs.org/request/-/request-2.88.2.tgz", + "integrity": "sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw==", + "requires": { + "aws-sign2": "~0.7.0", + "aws4": "^1.8.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.6", + "extend": "~3.0.2", + "forever-agent": "~0.6.1", + "form-data": "~2.3.2", + "har-validator": "~5.1.3", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.19", + "oauth-sign": "~0.9.0", + "performance-now": "^2.1.0", + "qs": "~6.5.2", + "safe-buffer": "^5.1.2", + "tough-cookie": "~2.5.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.3.2" + }, + "dependencies": { + "qs": { + "version": "6.5.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.5.3.tgz", + "integrity": "sha512-qxXIEh4pCGfHICj1mAJQ2/2XVZkjCDTcEgfoSQxc/fYivUZxTkk7L3bDBJSoNrEzXI17oUO5Dp07ktqE5KzczA==" + }, + "tough-cookie": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-2.5.0.tgz", + "integrity": "sha512-nlLsUzgm1kfLXSXfRZMc1KLAugd4hqJHDTvc2hDIwS3mZAfMEuMbc03SujMF+GEcpaX/qboeycw6iO8JwVv2+g==", + "requires": { + "psl": "^1.1.28", + "punycode": "^2.1.1" + } + } + } + }, + "safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" + }, + "safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" + }, + + "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.18.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.18.0.tgz", + "integrity": "sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==", + "requires": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "dependencies": { + "ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + } + } + }, + "seq-queue": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", + "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==" + }, + "serve-static": { + "version": "1.15.0", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.15.0.tgz", + "integrity": "sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==", + "requires": { + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.18.0" + } + }, + "servie": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/servie/-/servie-4.3.3.tgz", + "integrity": "sha512-b0IrY3b1gVMsWvJppCf19g1p3JSnS0hQi6xu4Hi40CIhf0Lx8pQHcvBL+xunShpmOiQzg1NOia812NAWdSaShw==", + "requires": { + "@servie/events": "^1.0.0", + "byte-length": "^1.0.2", + "ts-expect": "^1.1.0" + } + }, + "setprototypeof": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" + }, + "shallow-clone": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/shallow-clone/-/shallow-clone-3.0.1.tgz", + "integrity": "sha512-/6KqX+GVUdqPuPPd2LxDDxzX6CAbjJehAAOKlNpqqUpAqPM6HeL8f+o3a+JsyGjn2lv0WY8UsTgUJjU9Ok55NA==", + "requires": { + "kind-of": "^6.0.2" + } + }, + "side-channel": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "requires": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + + } + + }, + + "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.1", + + "resolved": "https://registry.npmjs.org/socks/-/socks-2.7.1.tgz", + + "integrity": "sha512-7maUZy1N7uo6+WVEX6psASxtNlKaNVMlGQKkG/63nEDdLOWNbiUMoLK7X4uYoLhQstau72mLgfEWcXcwsaHbYQ==", + + "requires": { + + "ip": "^2.0.0", + + "smart-buffer": "^4.2.0" + + } + + }, + + "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==" + }, + "sshpk": { + "version": "1.17.0", + "resolved": "https://registry.npmjs.org/sshpk/-/sshpk-1.17.0.tgz", + "integrity": "sha512-/9HIEs1ZXGhSPE8X6Ccm7Nam1z8KcoCqPdI7ecm1N33EzAetWahvQWVqLZtaZQ+IDKX4IyA2o0gBzqIMkAagHQ==", + "requires": { + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "safer-buffer": "^2.0.2", + "tweetnacl": "~0.14.0" + } + }, + "statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==" + }, + "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" + }, + "dependencies": { + "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-reduce": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string-reduce/-/string-reduce-1.0.0.tgz", + "integrity": "sha512-Sc7/l7xG8TvJrC1+LNowFgAyW0jerj73NHPJo66ijTQCbveJ2TRHoq+mACTLzlFTO7V30ESzb23qTU6wB0VNCQ==", + "requires": { + "assert-err": "^1.1.0" + } + }, + "throwback": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/throwback/-/throwback-4.1.0.tgz", + "integrity": "sha512-dLFe8bU8SeH0xeqeKL7BNo8XoPC/o91nz9/ooeplZPiso+DZukhoyZcSz9TFnUNScm+cA9qjU1m1853M6sPOng==" + }, + "toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==" + }, + "tough-cookie": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-3.0.1.tgz", + "integrity": "sha512-yQyJ0u4pZsv9D4clxO69OEjLWYw+jbgspjTue4lTQZLfV0c5l1VmK2y1JK8E9ahdpltPOaAThPcp5nKPUgSnsg==", + "requires": { + "ip-regex": "^2.1.0", + "psl": "^1.1.28", + "punycode": "^2.1.1" + } + }, + "tr46": { + "version": "0.0.3", + "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" + }, + "ts-expect": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/ts-expect/-/ts-expect-1.3.0.tgz", + "integrity": "sha512-e4g0EJtAjk64xgnFPD6kTBUtpnMVzDrMb12N1YZV0VvSlhnVT3SGxiYTLdGy8Q5cYHOIC/FAHmZ10eGrAguicQ==" + }, + "tunnel-agent": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", + "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "tweetnacl": { + "version": "0.14.5", + "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-0.14.5.tgz", + "integrity": "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA==" + }, + "type-detect": { + "version": "0.1.1", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-0.1.1.tgz", + "integrity": "sha512-5rqszGVwYgBoDkIm2oUtvkfZMQ0vk29iDMU0W2qCa3rG0vPDNczCMT4hV/bLBgLg8k8ri6+u3Zbt+S/14eMzlA==" + }, + "type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "requires": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + } + }, + "unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==" + }, + "uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "requires": { + "punycode": "^2.1.0" + } + }, + "util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==" + }, + "uuid": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.4.0.tgz", + "integrity": "sha512-HjSDRw6gZE5JMggctHBcjVak08+KEVhSIiDzFnT9S9aegmp85S/bReBVTb4QTFaRNptJ9kuYaNhnbNEOkbKb/A==" + }, + "vary": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==" + }, + "verror": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/verror/-/verror-1.10.0.tgz", + "integrity": "sha512-ZZKSmDAEFOijERBLkmYfJ+vmk3w+7hOLYDNkRCuRuMJGEmqYNCNLyBBFwWKVMhfwaEF3WOd0Zlw86U/WC/+nYw==", + "requires": { + "assert-plus": "^1.0.0", + "core-util-is": "1.0.2", + "extsprintf": "^1.2.0" + }, + "dependencies": { + "core-util-is": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "integrity": "sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==" + } + } + }, + "web-streams-polyfill": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz", + "integrity": "sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==" + }, + "webidl-conversions": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" + }, + "whatwg-url": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", + "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", + "requires": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "ws": { + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-6.2.2.tgz", + "integrity": "sha512-zmhltoSR8u1cnDsD43TX59mzoMZsLKqUweyYBAIvTngR3shc0W6aOZylZmq/7hqyVxPdi+5Ud2QInblgyE72fw==", + "requires": { + "async-limiter": "~1.0.0" + } + }, + "yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + } + } + } + diff --git a/2_PAC/package.json b/2_PAC/package.json index fa4e5ca6..001c8b18 100644 --- a/2_PAC/package.json +++ b/2_PAC/package.json @@ -1,17 +1,32 @@ { "scripts": { + "test": "node runPacApp TestMaster" + }, "dependencies": { + "@arces-wot/sepa-js": "^0.12.1", + "body-parser": "^1.20.1", + "express": "^4.18.2", + + "mongodb": "^5.0.1", + "mysql": "^2.18.1", + "mysql2": "^2.3.3", + "node-fetch": "^3.3.0", + "op-client": "^1.4.2", + "request": "^2.88.2" + } + } +