From 91abad4066e39e94533224a0fd92e5724b093b3b Mon Sep 17 00:00:00 2001 From: Alex Date: Mon, 2 Nov 2026 09:50:37 +0800 Subject: [PATCH] Initial MultiPay project --- .env | 8 + .env.example | 17 + .gitignore | 1 + README.md | 140 + alipayPublicKey_RSA2.txt | 1 + bun.lock | 103 + data/.master-key | 1 + data/alipay_app_public_key.pem | 9 + data/alipay_app_public_key.txt | 1 + data/multipay.sqlite | Bin 0 -> 143360 bytes data/multipay.sqlite-shm | Bin 0 -> 32768 bytes data/multipay.sqlite-wal | Bin 0 -> 1318432 bytes miyao.txt | 4 + node_modules/.bin/qrcode.bunx | Bin 0 -> 58 bytes node_modules/.bin/qrcode.exe | Bin 0 -> 8192 bytes node_modules/ansi-regex/index.d.ts | 37 + node_modules/ansi-regex/index.js | 10 + node_modules/ansi-regex/license | 9 + node_modules/ansi-regex/package.json | 55 + node_modules/ansi-regex/readme.md | 78 + node_modules/ansi-styles/index.d.ts | 345 + node_modules/ansi-styles/index.js | 163 + node_modules/ansi-styles/license | 9 + node_modules/ansi-styles/package.json | 56 + node_modules/ansi-styles/readme.md | 152 + node_modules/camelcase/index.d.ts | 63 + node_modules/camelcase/index.js | 76 + node_modules/camelcase/license | 9 + node_modules/camelcase/package.json | 43 + node_modules/camelcase/readme.md | 99 + node_modules/cliui/CHANGELOG.md | 76 + node_modules/cliui/LICENSE.txt | 14 + node_modules/cliui/README.md | 115 + node_modules/cliui/index.js | 354 + node_modules/cliui/package.json | 65 + node_modules/color-convert/CHANGELOG.md | 54 + node_modules/color-convert/LICENSE | 21 + node_modules/color-convert/README.md | 68 + node_modules/color-convert/conversions.js | 839 + node_modules/color-convert/index.js | 81 + node_modules/color-convert/package.json | 48 + node_modules/color-convert/route.js | 97 + node_modules/color-name/LICENSE | 8 + node_modules/color-name/README.md | 11 + node_modules/color-name/index.js | 152 + node_modules/color-name/package.json | 28 + node_modules/decamelize/index.js | 13 + node_modules/decamelize/license | 21 + node_modules/decamelize/package.json | 38 + node_modules/decamelize/readme.md | 48 + node_modules/dijkstrajs/.travis.yml | 4 + node_modules/dijkstrajs/CONTRIBUTING.md | 8 + node_modules/dijkstrajs/LICENSE.md | 19 + node_modules/dijkstrajs/README.md | 18 + node_modules/dijkstrajs/dijkstra.js | 165 + node_modules/dijkstrajs/package.json | 60 + node_modules/dijkstrajs/test/dijkstra.test.js | 96 + node_modules/emoji-regex/LICENSE-MIT.txt | 20 + node_modules/emoji-regex/README.md | 73 + node_modules/emoji-regex/es2015/index.js | 6 + node_modules/emoji-regex/es2015/text.js | 6 + node_modules/emoji-regex/index.d.ts | 23 + node_modules/emoji-regex/index.js | 6 + node_modules/emoji-regex/package.json | 50 + node_modules/emoji-regex/text.js | 6 + node_modules/find-up/index.d.ts | 137 + node_modules/find-up/index.js | 89 + node_modules/find-up/license | 9 + node_modules/find-up/package.json | 53 + node_modules/find-up/readme.md | 156 + node_modules/get-caller-file/LICENSE.md | 6 + node_modules/get-caller-file/README.md | 41 + node_modules/get-caller-file/index.d.ts | 2 + node_modules/get-caller-file/index.js | 22 + node_modules/get-caller-file/index.js.map | 1 + node_modules/get-caller-file/package.json | 42 + .../is-fullwidth-code-point/index.d.ts | 17 + node_modules/is-fullwidth-code-point/index.js | 50 + node_modules/is-fullwidth-code-point/license | 9 + .../is-fullwidth-code-point/package.json | 42 + .../is-fullwidth-code-point/readme.md | 39 + node_modules/locate-path/index.d.ts | 83 + node_modules/locate-path/index.js | 65 + node_modules/locate-path/license | 9 + node_modules/locate-path/package.json | 45 + node_modules/locate-path/readme.md | 122 + node_modules/p-limit/index.d.ts | 38 + node_modules/p-limit/index.js | 57 + node_modules/p-limit/license | 9 + node_modules/p-limit/package.json | 52 + node_modules/p-limit/readme.md | 101 + node_modules/p-locate/index.d.ts | 64 + node_modules/p-locate/index.js | 52 + node_modules/p-locate/license | 9 + node_modules/p-locate/package.json | 53 + node_modules/p-locate/readme.md | 90 + node_modules/p-try/index.d.ts | 39 + node_modules/p-try/index.js | 9 + node_modules/p-try/license | 9 + node_modules/p-try/package.json | 42 + node_modules/p-try/readme.md | 58 + node_modules/path-exists/index.d.ts | 28 + node_modules/path-exists/index.js | 23 + node_modules/path-exists/license | 9 + node_modules/path-exists/package.json | 39 + node_modules/path-exists/readme.md | 52 + node_modules/pg-cloudflare/LICENSE | 21 + node_modules/pg-cloudflare/README.md | 112 + node_modules/pg-cloudflare/dist/empty.d.ts | 2 + node_modules/pg-cloudflare/dist/empty.js | 6 + node_modules/pg-cloudflare/dist/empty.js.map | 1 + node_modules/pg-cloudflare/dist/index.d.ts | 29 + node_modules/pg-cloudflare/dist/index.js | 171 + node_modules/pg-cloudflare/dist/index.js.map | 1 + node_modules/pg-cloudflare/esm/index.mjs | 3 + node_modules/pg-cloudflare/package.json | 39 + node_modules/pg-cloudflare/src/empty.ts | 3 + node_modules/pg-cloudflare/src/index.ts | 187 + node_modules/pg-cloudflare/src/types.d.ts | 25 + node_modules/pg-connection-string/LICENSE | 21 + node_modules/pg-connection-string/README.md | 105 + .../pg-connection-string/esm/index.mjs | 8 + node_modules/pg-connection-string/index.d.ts | 37 + node_modules/pg-connection-string/index.js | 237 + .../pg-connection-string/package.json | 51 + node_modules/pg-int8/LICENSE | 13 + node_modules/pg-int8/README.md | 16 + node_modules/pg-int8/index.js | 100 + node_modules/pg-int8/package.json | 24 + node_modules/pg-pool/LICENSE | 21 + node_modules/pg-pool/README.md | 357 + node_modules/pg-pool/esm/index.mjs | 5 + node_modules/pg-pool/index.js | 517 + node_modules/pg-pool/package.json | 51 + node_modules/pg-protocol/LICENSE | 21 + node_modules/pg-protocol/README.md | 3 + node_modules/pg-protocol/dist/b.d.ts | 1 + node_modules/pg-protocol/dist/b.js | 23 + node_modules/pg-protocol/dist/b.js.map | 1 + .../pg-protocol/dist/buffer-reader.d.ts | 14 + .../pg-protocol/dist/buffer-reader.js | 55 + .../pg-protocol/dist/buffer-reader.js.map | 1 + .../pg-protocol/dist/buffer-writer.d.ts | 21 + .../pg-protocol/dist/buffer-writer.js | 113 + .../pg-protocol/dist/buffer-writer.js.map | 1 + .../pg-protocol/dist/inbound-parser.test.d.ts | 1 + .../pg-protocol/dist/inbound-parser.test.js | 538 + .../dist/inbound-parser.test.js.map | 1 + node_modules/pg-protocol/dist/index.d.ts | 5 + node_modules/pg-protocol/dist/index.js | 15 + node_modules/pg-protocol/dist/index.js.map | 1 + node_modules/pg-protocol/dist/messages.d.ts | 161 + node_modules/pg-protocol/dist/messages.js | 160 + node_modules/pg-protocol/dist/messages.js.map | 1 + .../dist/outbound-serializer.test.d.ts | 1 + .../dist/outbound-serializer.test.js | 325 + .../dist/outbound-serializer.test.js.map | 1 + node_modules/pg-protocol/dist/parser.d.ts | 22 + node_modules/pg-protocol/dist/parser.js | 325 + node_modules/pg-protocol/dist/parser.js.map | 1 + node_modules/pg-protocol/dist/serializer.d.ts | 42 + node_modules/pg-protocol/dist/serializer.js | 198 + .../pg-protocol/dist/serializer.js.map | 1 + node_modules/pg-protocol/esm/index.js | 11 + node_modules/pg-protocol/package.json | 44 + node_modules/pg-protocol/src/b.ts | 25 + node_modules/pg-protocol/src/buffer-reader.ts | 58 + node_modules/pg-protocol/src/buffer-writer.ts | 120 + .../pg-protocol/src/inbound-parser.test.ts | 585 + node_modules/pg-protocol/src/index.ts | 11 + node_modules/pg-protocol/src/messages.ts | 262 + .../src/outbound-serializer.test.ts | 356 + node_modules/pg-protocol/src/parser.ts | 414 + node_modules/pg-protocol/src/serializer.ts | 286 + .../pg-protocol/src/testing/buffer-list.ts | 67 + .../pg-protocol/src/testing/test-buffers.ts | 166 + node_modules/pg-types/.travis.yml | 7 + node_modules/pg-types/Makefile | 14 + node_modules/pg-types/README.md | 75 + node_modules/pg-types/index.d.ts | 137 + node_modules/pg-types/index.js | 47 + node_modules/pg-types/index.test-d.ts | 21 + node_modules/pg-types/lib/arrayParser.js | 11 + node_modules/pg-types/lib/binaryParsers.js | 257 + node_modules/pg-types/lib/builtins.js | 73 + node_modules/pg-types/lib/textParsers.js | 215 + node_modules/pg-types/package.json | 42 + node_modules/pg-types/test/index.js | 24 + node_modules/pg-types/test/types.js | 597 + node_modules/pg/LICENSE | 21 + node_modules/pg/README.md | 96 + node_modules/pg/esm/index.mjs | 20 + node_modules/pg/lib/client.js | 846 + node_modules/pg/lib/connection-parameters.js | 184 + node_modules/pg/lib/connection.js | 250 + node_modules/pg/lib/crypto/cert-signatures.js | 122 + node_modules/pg/lib/crypto/sasl.js | 262 + node_modules/pg/lib/crypto/utils.js | 89 + node_modules/pg/lib/defaults.js | 94 + node_modules/pg/lib/index.js | 73 + node_modules/pg/lib/native/client.js | 428 + node_modules/pg/lib/native/index.js | 2 + node_modules/pg/lib/native/query.js | 167 + node_modules/pg/lib/query.js | 263 + node_modules/pg/lib/result.js | 109 + node_modules/pg/lib/stream.js | 83 + node_modules/pg/lib/type-overrides.js | 35 + node_modules/pg/lib/utils.js | 225 + node_modules/pg/package.json | 76 + node_modules/pgpass/README.md | 74 + node_modules/pgpass/lib/helper.js | 233 + node_modules/pgpass/lib/index.js | 23 + node_modules/pgpass/package.json | 41 + node_modules/pngjs/.eslintignore | 2 + node_modules/pngjs/.eslintrc.json | 19 + node_modules/pngjs/.prettierignore | 3 + node_modules/pngjs/LICENSE | 20 + node_modules/pngjs/README.md | 429 + node_modules/pngjs/browser.js | 16096 ++++++++++++++++ .../pngjs/coverage/lcov-report/base.css | 354 + .../coverage/lcov-report/bitmapper.js.html | 881 + .../coverage/lcov-report/bitpacker.js.html | 554 + .../coverage/lcov-report/block-navigation.js | 77 + .../coverage/lcov-report/chunkstream.js.html | 647 + .../coverage/lcov-report/constants.js.html | 176 + .../pngjs/coverage/lcov-report/crc.js.html | 200 + .../pngjs/coverage/lcov-report/favicon.png | Bin 0 -> 540 bytes .../coverage/lcov-report/filter-pack.js.html | 593 + .../lcov-report/filter-parse-async.js.html | 152 + .../lcov-report/filter-parse-sync.js.html | 143 + .../coverage/lcov-report/filter-parse.js.html | 611 + .../lcov-report/format-normaliser.js.html | 359 + .../pngjs/coverage/lcov-report/index.html | 426 + .../coverage/lcov-report/interlace.js.html | 365 + .../coverage/lcov-report/packer-async.js.html | 230 + .../coverage/lcov-report/packer-sync.js.html | 248 + .../pngjs/coverage/lcov-report/packer.js.html | 467 + .../lcov-report/paeth-predictor.js.html | 128 + .../coverage/lcov-report/parser-async.js.html | 575 + .../coverage/lcov-report/parser-sync.js.html | 404 + .../pngjs/coverage/lcov-report/parser.js.html | 950 + .../coverage/lcov-report/png-sync.js.html | 116 + .../pngjs/coverage/lcov-report/png.js.html | 662 + .../pngjs/coverage/lcov-report/prettify.css | 101 + .../pngjs/coverage/lcov-report/prettify.js | 1007 + .../lcov-report/sort-arrow-sprite.png | Bin 0 -> 209 bytes .../pngjs/coverage/lcov-report/sorter.js | 169 + .../coverage/lcov-report/sync-inflate.js.html | 584 + .../coverage/lcov-report/sync-reader.js.html | 215 + node_modules/pngjs/coverage/lcov.info | 2177 +++ node_modules/pngjs/lib/bitmapper.js | 267 + node_modules/pngjs/lib/bitpacker.js | 158 + node_modules/pngjs/lib/chunkstream.js | 189 + node_modules/pngjs/lib/constants.js | 32 + node_modules/pngjs/lib/crc.js | 40 + node_modules/pngjs/lib/filter-pack.js | 171 + node_modules/pngjs/lib/filter-parse-async.js | 24 + node_modules/pngjs/lib/filter-parse-sync.js | 21 + node_modules/pngjs/lib/filter-parse.js | 177 + node_modules/pngjs/lib/format-normaliser.js | 93 + node_modules/pngjs/lib/interlace.js | 95 + node_modules/pngjs/lib/packer-async.js | 50 + node_modules/pngjs/lib/packer-sync.js | 56 + node_modules/pngjs/lib/packer.js | 129 + node_modules/pngjs/lib/paeth-predictor.js | 16 + node_modules/pngjs/lib/parser-async.js | 165 + node_modules/pngjs/lib/parser-sync.js | 108 + node_modules/pngjs/lib/parser.js | 290 + node_modules/pngjs/lib/png-sync.js | 12 + node_modules/pngjs/lib/png.js | 194 + node_modules/pngjs/lib/sync-inflate.js | 168 + node_modules/pngjs/lib/sync-reader.js | 45 + node_modules/pngjs/package.json | 73 + node_modules/postgres-array/index.d.ts | 4 + node_modules/postgres-array/index.js | 97 + node_modules/postgres-array/license | 21 + node_modules/postgres-array/package.json | 35 + node_modules/postgres-array/readme.md | 43 + node_modules/postgres-bytea/index.js | 33 + node_modules/postgres-bytea/license | 21 + node_modules/postgres-bytea/package.json | 34 + node_modules/postgres-bytea/readme.md | 34 + node_modules/postgres-date/index.js | 116 + node_modules/postgres-date/license | 21 + node_modules/postgres-date/package.json | 33 + node_modules/postgres-date/readme.md | 49 + node_modules/postgres-interval/index.d.ts | 20 + node_modules/postgres-interval/index.js | 125 + node_modules/postgres-interval/license | 21 + node_modules/postgres-interval/package.json | 36 + node_modules/postgres-interval/readme.md | 48 + node_modules/postgres/README.md | 1970 ++ node_modules/postgres/package.json | 39 + node_modules/postgres/src/build.js | 292 + node_modules/postgres/src/cf.js | 151 + node_modules/postgres/src/connection.js | 1226 ++ node_modules/postgres/src/diagnostics.js | 73 + node_modules/postgres/src/errors.js | 88 + node_modules/postgres/src/index.js | 617 + node_modules/postgres/src/large.js | 72 + node_modules/postgres/src/pool.js | 814 + node_modules/postgres/src/protocol.js | 458 + node_modules/postgres/src/query.js | 298 + node_modules/postgres/src/result.js | 36 + node_modules/postgres/src/socket.js | 149 + node_modules/postgres/src/startup.js | 469 + node_modules/postgres/src/subscribe.js | 403 + node_modules/postgres/src/types.js | 349 + node_modules/postgres/types/index.d.ts | 908 + node_modules/qrcode/README.md | 770 + node_modules/qrcode/bin/qrcode | 159 + node_modules/qrcode/helper/to-sjis-browser.js | 2 + node_modules/qrcode/helper/to-sjis.js | 105 + node_modules/qrcode/lib/browser.js | 76 + node_modules/qrcode/lib/can-promise.js | 7 + .../qrcode/lib/core/alignment-pattern.js | 83 + .../qrcode/lib/core/alphanumeric-data.js | 59 + node_modules/qrcode/lib/core/bit-buffer.js | 37 + node_modules/qrcode/lib/core/bit-matrix.js | 65 + node_modules/qrcode/lib/core/byte-data.js | 30 + .../qrcode/lib/core/error-correction-code.js | 135 + .../qrcode/lib/core/error-correction-level.js | 50 + .../qrcode/lib/core/finder-pattern.js | 22 + node_modules/qrcode/lib/core/format-info.js | 29 + node_modules/qrcode/lib/core/galois-field.js | 69 + node_modules/qrcode/lib/core/kanji-data.js | 54 + node_modules/qrcode/lib/core/mask-pattern.js | 234 + node_modules/qrcode/lib/core/mode.js | 167 + node_modules/qrcode/lib/core/numeric-data.js | 43 + node_modules/qrcode/lib/core/polynomial.js | 62 + node_modules/qrcode/lib/core/qrcode.js | 495 + .../qrcode/lib/core/reed-solomon-encoder.js | 56 + node_modules/qrcode/lib/core/regex.js | 31 + node_modules/qrcode/lib/core/segments.js | 330 + node_modules/qrcode/lib/core/utils.js | 63 + node_modules/qrcode/lib/core/version-check.js | 9 + node_modules/qrcode/lib/core/version.js | 163 + node_modules/qrcode/lib/index.js | 12 + node_modules/qrcode/lib/renderer/canvas.js | 63 + node_modules/qrcode/lib/renderer/png.js | 78 + node_modules/qrcode/lib/renderer/svg-tag.js | 81 + node_modules/qrcode/lib/renderer/svg.js | 19 + node_modules/qrcode/lib/renderer/terminal.js | 9 + .../lib/renderer/terminal/terminal-small.js | 85 + .../qrcode/lib/renderer/terminal/terminal.js | 49 + node_modules/qrcode/lib/renderer/utf8.js | 71 + node_modules/qrcode/lib/renderer/utils.js | 99 + node_modules/qrcode/lib/server.js | 138 + node_modules/qrcode/license | 10 + node_modules/qrcode/package.json | 77 + node_modules/require-directory/.jshintrc | 67 + node_modules/require-directory/.npmignore | 1 + node_modules/require-directory/.travis.yml | 3 + node_modules/require-directory/LICENSE | 22 + .../require-directory/README.markdown | 184 + node_modules/require-directory/index.js | 86 + node_modules/require-directory/package.json | 40 + .../require-main-filename/CHANGELOG.md | 26 + .../require-main-filename/LICENSE.txt | 14 + node_modules/require-main-filename/README.md | 26 + node_modules/require-main-filename/index.js | 18 + .../require-main-filename/package.json | 35 + node_modules/set-blocking/CHANGELOG.md | 26 + node_modules/set-blocking/LICENSE.txt | 14 + node_modules/set-blocking/README.md | 31 + node_modules/set-blocking/index.js | 7 + node_modules/set-blocking/package.json | 42 + node_modules/split2/LICENSE | 13 + node_modules/split2/README.md | 85 + node_modules/split2/bench.js | 27 + node_modules/split2/index.js | 141 + node_modules/split2/package.json | 39 + node_modules/split2/test.js | 409 + node_modules/string-width/index.d.ts | 29 + node_modules/string-width/index.js | 47 + node_modules/string-width/license | 9 + node_modules/string-width/package.json | 56 + node_modules/string-width/readme.md | 50 + node_modules/strip-ansi/index.d.ts | 17 + node_modules/strip-ansi/index.js | 4 + node_modules/strip-ansi/license | 9 + node_modules/strip-ansi/package.json | 54 + node_modules/strip-ansi/readme.md | 46 + node_modules/which-module/LICENSE | 13 + node_modules/which-module/README.md | 58 + node_modules/which-module/index.js | 9 + node_modules/which-module/package.json | 41 + node_modules/wrap-ansi/index.js | 186 + node_modules/wrap-ansi/license | 9 + node_modules/wrap-ansi/package.json | 61 + node_modules/wrap-ansi/readme.md | 97 + node_modules/xtend/.jshintrc | 30 + node_modules/xtend/LICENSE | 20 + node_modules/xtend/README.md | 32 + node_modules/xtend/immutable.js | 19 + node_modules/xtend/mutable.js | 17 + node_modules/xtend/package.json | 55 + node_modules/xtend/test.js | 103 + node_modules/y18n/CHANGELOG.md | 35 + node_modules/y18n/LICENSE | 13 + node_modules/y18n/README.md | 109 + node_modules/y18n/index.js | 188 + node_modules/y18n/package.json | 39 + node_modules/yargs-parser/CHANGELOG.md | 601 + node_modules/yargs-parser/LICENSE.txt | 14 + node_modules/yargs-parser/README.md | 449 + node_modules/yargs-parser/index.js | 1032 + .../yargs-parser/lib/tokenize-arg-string.js | 40 + node_modules/yargs-parser/package.json | 46 + node_modules/yargs/CHANGELOG.md | 420 + node_modules/yargs/LICENSE | 21 + node_modules/yargs/README.md | 140 + .../yargs/build/lib/apply-extends.d.ts | 2 + node_modules/yargs/build/lib/apply-extends.js | 65 + node_modules/yargs/build/lib/argsert.d.ts | 2 + node_modules/yargs/build/lib/argsert.js | 65 + node_modules/yargs/build/lib/command.d.ts | 64 + node_modules/yargs/build/lib/command.js | 416 + .../yargs/build/lib/common-types.d.ts | 36 + node_modules/yargs/build/lib/common-types.js | 25 + .../yargs/build/lib/completion-templates.d.ts | 2 + .../yargs/build/lib/completion-templates.js | 50 + node_modules/yargs/build/lib/completion.d.ts | 21 + node_modules/yargs/build/lib/completion.js | 135 + node_modules/yargs/build/lib/is-promise.d.ts | 1 + node_modules/yargs/build/lib/is-promise.js | 9 + node_modules/yargs/build/lib/levenshtein.d.ts | 1 + node_modules/yargs/build/lib/levenshtein.js | 58 + node_modules/yargs/build/lib/middleware.d.ts | 10 + node_modules/yargs/build/lib/middleware.js | 57 + node_modules/yargs/build/lib/obj-filter.d.ts | 1 + node_modules/yargs/build/lib/obj-filter.js | 14 + .../yargs/build/lib/parse-command.d.ts | 11 + node_modules/yargs/build/lib/parse-command.js | 36 + .../yargs/build/lib/process-argv.d.ts | 2 + node_modules/yargs/build/lib/process-argv.js | 31 + node_modules/yargs/build/lib/usage.d.ts | 49 + node_modules/yargs/build/lib/usage.js | 540 + node_modules/yargs/build/lib/validation.d.ts | 34 + node_modules/yargs/build/lib/validation.js | 330 + node_modules/yargs/build/lib/yargs.d.ts | 274 + node_modules/yargs/build/lib/yargs.js | 1190 ++ node_modules/yargs/build/lib/yerror.d.ts | 4 + node_modules/yargs/build/lib/yerror.js | 11 + node_modules/yargs/index.js | 40 + node_modules/yargs/locales/be.json | 46 + node_modules/yargs/locales/de.json | 46 + node_modules/yargs/locales/en.json | 51 + node_modules/yargs/locales/es.json | 46 + node_modules/yargs/locales/fi.json | 49 + node_modules/yargs/locales/fr.json | 53 + node_modules/yargs/locales/hi.json | 49 + node_modules/yargs/locales/hu.json | 46 + node_modules/yargs/locales/id.json | 50 + node_modules/yargs/locales/it.json | 46 + node_modules/yargs/locales/ja.json | 51 + node_modules/yargs/locales/ko.json | 49 + node_modules/yargs/locales/nb.json | 44 + node_modules/yargs/locales/nl.json | 49 + node_modules/yargs/locales/nn.json | 44 + node_modules/yargs/locales/pirate.json | 13 + node_modules/yargs/locales/pl.json | 49 + node_modules/yargs/locales/pt.json | 45 + node_modules/yargs/locales/pt_BR.json | 48 + node_modules/yargs/locales/ru.json | 46 + node_modules/yargs/locales/th.json | 46 + node_modules/yargs/locales/tr.json | 48 + node_modules/yargs/locales/zh_CN.json | 48 + node_modules/yargs/locales/zh_TW.json | 47 + node_modules/yargs/package.json | 92 + node_modules/yargs/yargs.js | 14 + package.json | 16 + public/admin.html | 25 + public/admin.js | 45 + public/app.css | 27 + public/checkout.html | 53 + public/checkout.js | 116 + scripts/export-alipay-app-public-key.ts | 32 + scripts/inspect-gateways.ts | 33 + scripts/set-alipay-product.ts | 13 + src/db.ts | 228 + src/external-db.ts | 203 + src/payments.ts | 486 + src/security.ts | 51 + src/server.ts | 843 + start.ps1 | 10 + tests/security.test.ts | 18 + tsconfig.json | 12 + 488 files changed, 76727 insertions(+) create mode 100644 .env create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 README.md create mode 100644 alipayPublicKey_RSA2.txt create mode 100644 bun.lock create mode 100644 data/.master-key create mode 100644 data/alipay_app_public_key.pem create mode 100644 data/alipay_app_public_key.txt create mode 100644 data/multipay.sqlite create mode 100644 data/multipay.sqlite-shm create mode 100644 data/multipay.sqlite-wal create mode 100644 miyao.txt create mode 100644 node_modules/.bin/qrcode.bunx create mode 100644 node_modules/.bin/qrcode.exe create mode 100644 node_modules/ansi-regex/index.d.ts create mode 100644 node_modules/ansi-regex/index.js create mode 100644 node_modules/ansi-regex/license create mode 100644 node_modules/ansi-regex/package.json create mode 100644 node_modules/ansi-regex/readme.md create mode 100644 node_modules/ansi-styles/index.d.ts create mode 100644 node_modules/ansi-styles/index.js create mode 100644 node_modules/ansi-styles/license create mode 100644 node_modules/ansi-styles/package.json create mode 100644 node_modules/ansi-styles/readme.md create mode 100644 node_modules/camelcase/index.d.ts create mode 100644 node_modules/camelcase/index.js create mode 100644 node_modules/camelcase/license create mode 100644 node_modules/camelcase/package.json create mode 100644 node_modules/camelcase/readme.md create mode 100644 node_modules/cliui/CHANGELOG.md create mode 100644 node_modules/cliui/LICENSE.txt create mode 100644 node_modules/cliui/README.md create mode 100644 node_modules/cliui/index.js create mode 100644 node_modules/cliui/package.json create mode 100644 node_modules/color-convert/CHANGELOG.md create mode 100644 node_modules/color-convert/LICENSE create mode 100644 node_modules/color-convert/README.md create mode 100644 node_modules/color-convert/conversions.js create mode 100644 node_modules/color-convert/index.js create mode 100644 node_modules/color-convert/package.json create mode 100644 node_modules/color-convert/route.js create mode 100644 node_modules/color-name/LICENSE create mode 100644 node_modules/color-name/README.md create mode 100644 node_modules/color-name/index.js create mode 100644 node_modules/color-name/package.json create mode 100644 node_modules/decamelize/index.js create mode 100644 node_modules/decamelize/license create mode 100644 node_modules/decamelize/package.json create mode 100644 node_modules/decamelize/readme.md create mode 100644 node_modules/dijkstrajs/.travis.yml create mode 100644 node_modules/dijkstrajs/CONTRIBUTING.md create mode 100644 node_modules/dijkstrajs/LICENSE.md create mode 100644 node_modules/dijkstrajs/README.md create mode 100644 node_modules/dijkstrajs/dijkstra.js create mode 100644 node_modules/dijkstrajs/package.json create mode 100644 node_modules/dijkstrajs/test/dijkstra.test.js create mode 100644 node_modules/emoji-regex/LICENSE-MIT.txt create mode 100644 node_modules/emoji-regex/README.md create mode 100644 node_modules/emoji-regex/es2015/index.js create mode 100644 node_modules/emoji-regex/es2015/text.js create mode 100644 node_modules/emoji-regex/index.d.ts create mode 100644 node_modules/emoji-regex/index.js create mode 100644 node_modules/emoji-regex/package.json create mode 100644 node_modules/emoji-regex/text.js create mode 100644 node_modules/find-up/index.d.ts create mode 100644 node_modules/find-up/index.js create mode 100644 node_modules/find-up/license create mode 100644 node_modules/find-up/package.json create mode 100644 node_modules/find-up/readme.md create mode 100644 node_modules/get-caller-file/LICENSE.md create mode 100644 node_modules/get-caller-file/README.md create mode 100644 node_modules/get-caller-file/index.d.ts create mode 100644 node_modules/get-caller-file/index.js create mode 100644 node_modules/get-caller-file/index.js.map create mode 100644 node_modules/get-caller-file/package.json create mode 100644 node_modules/is-fullwidth-code-point/index.d.ts create mode 100644 node_modules/is-fullwidth-code-point/index.js create mode 100644 node_modules/is-fullwidth-code-point/license create mode 100644 node_modules/is-fullwidth-code-point/package.json create mode 100644 node_modules/is-fullwidth-code-point/readme.md create mode 100644 node_modules/locate-path/index.d.ts create mode 100644 node_modules/locate-path/index.js create mode 100644 node_modules/locate-path/license create mode 100644 node_modules/locate-path/package.json create mode 100644 node_modules/locate-path/readme.md create mode 100644 node_modules/p-limit/index.d.ts create mode 100644 node_modules/p-limit/index.js create mode 100644 node_modules/p-limit/license create mode 100644 node_modules/p-limit/package.json create mode 100644 node_modules/p-limit/readme.md create mode 100644 node_modules/p-locate/index.d.ts create mode 100644 node_modules/p-locate/index.js create mode 100644 node_modules/p-locate/license create mode 100644 node_modules/p-locate/package.json create mode 100644 node_modules/p-locate/readme.md create mode 100644 node_modules/p-try/index.d.ts create mode 100644 node_modules/p-try/index.js create mode 100644 node_modules/p-try/license create mode 100644 node_modules/p-try/package.json create mode 100644 node_modules/p-try/readme.md create mode 100644 node_modules/path-exists/index.d.ts create mode 100644 node_modules/path-exists/index.js create mode 100644 node_modules/path-exists/license create mode 100644 node_modules/path-exists/package.json create mode 100644 node_modules/path-exists/readme.md create mode 100644 node_modules/pg-cloudflare/LICENSE create mode 100644 node_modules/pg-cloudflare/README.md create mode 100644 node_modules/pg-cloudflare/dist/empty.d.ts create mode 100644 node_modules/pg-cloudflare/dist/empty.js create mode 100644 node_modules/pg-cloudflare/dist/empty.js.map create mode 100644 node_modules/pg-cloudflare/dist/index.d.ts create mode 100644 node_modules/pg-cloudflare/dist/index.js create mode 100644 node_modules/pg-cloudflare/dist/index.js.map create mode 100644 node_modules/pg-cloudflare/esm/index.mjs create mode 100644 node_modules/pg-cloudflare/package.json create mode 100644 node_modules/pg-cloudflare/src/empty.ts create mode 100644 node_modules/pg-cloudflare/src/index.ts create mode 100644 node_modules/pg-cloudflare/src/types.d.ts create mode 100644 node_modules/pg-connection-string/LICENSE create mode 100644 node_modules/pg-connection-string/README.md create mode 100644 node_modules/pg-connection-string/esm/index.mjs create mode 100644 node_modules/pg-connection-string/index.d.ts create mode 100644 node_modules/pg-connection-string/index.js create mode 100644 node_modules/pg-connection-string/package.json create mode 100644 node_modules/pg-int8/LICENSE create mode 100644 node_modules/pg-int8/README.md create mode 100644 node_modules/pg-int8/index.js create mode 100644 node_modules/pg-int8/package.json create mode 100644 node_modules/pg-pool/LICENSE create mode 100644 node_modules/pg-pool/README.md create mode 100644 node_modules/pg-pool/esm/index.mjs create mode 100644 node_modules/pg-pool/index.js create mode 100644 node_modules/pg-pool/package.json create mode 100644 node_modules/pg-protocol/LICENSE create mode 100644 node_modules/pg-protocol/README.md create mode 100644 node_modules/pg-protocol/dist/b.d.ts create mode 100644 node_modules/pg-protocol/dist/b.js create mode 100644 node_modules/pg-protocol/dist/b.js.map create mode 100644 node_modules/pg-protocol/dist/buffer-reader.d.ts create mode 100644 node_modules/pg-protocol/dist/buffer-reader.js create mode 100644 node_modules/pg-protocol/dist/buffer-reader.js.map create mode 100644 node_modules/pg-protocol/dist/buffer-writer.d.ts create mode 100644 node_modules/pg-protocol/dist/buffer-writer.js create mode 100644 node_modules/pg-protocol/dist/buffer-writer.js.map create mode 100644 node_modules/pg-protocol/dist/inbound-parser.test.d.ts create mode 100644 node_modules/pg-protocol/dist/inbound-parser.test.js create mode 100644 node_modules/pg-protocol/dist/inbound-parser.test.js.map create mode 100644 node_modules/pg-protocol/dist/index.d.ts create mode 100644 node_modules/pg-protocol/dist/index.js create mode 100644 node_modules/pg-protocol/dist/index.js.map create mode 100644 node_modules/pg-protocol/dist/messages.d.ts create mode 100644 node_modules/pg-protocol/dist/messages.js create mode 100644 node_modules/pg-protocol/dist/messages.js.map create mode 100644 node_modules/pg-protocol/dist/outbound-serializer.test.d.ts create mode 100644 node_modules/pg-protocol/dist/outbound-serializer.test.js create mode 100644 node_modules/pg-protocol/dist/outbound-serializer.test.js.map create mode 100644 node_modules/pg-protocol/dist/parser.d.ts create mode 100644 node_modules/pg-protocol/dist/parser.js create mode 100644 node_modules/pg-protocol/dist/parser.js.map create mode 100644 node_modules/pg-protocol/dist/serializer.d.ts create mode 100644 node_modules/pg-protocol/dist/serializer.js create mode 100644 node_modules/pg-protocol/dist/serializer.js.map create mode 100644 node_modules/pg-protocol/esm/index.js create mode 100644 node_modules/pg-protocol/package.json create mode 100644 node_modules/pg-protocol/src/b.ts create mode 100644 node_modules/pg-protocol/src/buffer-reader.ts create mode 100644 node_modules/pg-protocol/src/buffer-writer.ts create mode 100644 node_modules/pg-protocol/src/inbound-parser.test.ts create mode 100644 node_modules/pg-protocol/src/index.ts create mode 100644 node_modules/pg-protocol/src/messages.ts create mode 100644 node_modules/pg-protocol/src/outbound-serializer.test.ts create mode 100644 node_modules/pg-protocol/src/parser.ts create mode 100644 node_modules/pg-protocol/src/serializer.ts create mode 100644 node_modules/pg-protocol/src/testing/buffer-list.ts create mode 100644 node_modules/pg-protocol/src/testing/test-buffers.ts create mode 100644 node_modules/pg-types/.travis.yml create mode 100644 node_modules/pg-types/Makefile create mode 100644 node_modules/pg-types/README.md create mode 100644 node_modules/pg-types/index.d.ts create mode 100644 node_modules/pg-types/index.js create mode 100644 node_modules/pg-types/index.test-d.ts create mode 100644 node_modules/pg-types/lib/arrayParser.js create mode 100644 node_modules/pg-types/lib/binaryParsers.js create mode 100644 node_modules/pg-types/lib/builtins.js create mode 100644 node_modules/pg-types/lib/textParsers.js create mode 100644 node_modules/pg-types/package.json create mode 100644 node_modules/pg-types/test/index.js create mode 100644 node_modules/pg-types/test/types.js create mode 100644 node_modules/pg/LICENSE create mode 100644 node_modules/pg/README.md create mode 100644 node_modules/pg/esm/index.mjs create mode 100644 node_modules/pg/lib/client.js create mode 100644 node_modules/pg/lib/connection-parameters.js create mode 100644 node_modules/pg/lib/connection.js create mode 100644 node_modules/pg/lib/crypto/cert-signatures.js create mode 100644 node_modules/pg/lib/crypto/sasl.js create mode 100644 node_modules/pg/lib/crypto/utils.js create mode 100644 node_modules/pg/lib/defaults.js create mode 100644 node_modules/pg/lib/index.js create mode 100644 node_modules/pg/lib/native/client.js create mode 100644 node_modules/pg/lib/native/index.js create mode 100644 node_modules/pg/lib/native/query.js create mode 100644 node_modules/pg/lib/query.js create mode 100644 node_modules/pg/lib/result.js create mode 100644 node_modules/pg/lib/stream.js create mode 100644 node_modules/pg/lib/type-overrides.js create mode 100644 node_modules/pg/lib/utils.js create mode 100644 node_modules/pg/package.json create mode 100644 node_modules/pgpass/README.md create mode 100644 node_modules/pgpass/lib/helper.js create mode 100644 node_modules/pgpass/lib/index.js create mode 100644 node_modules/pgpass/package.json create mode 100644 node_modules/pngjs/.eslintignore create mode 100644 node_modules/pngjs/.eslintrc.json create mode 100644 node_modules/pngjs/.prettierignore create mode 100644 node_modules/pngjs/LICENSE create mode 100644 node_modules/pngjs/README.md create mode 100644 node_modules/pngjs/browser.js create mode 100644 node_modules/pngjs/coverage/lcov-report/base.css create mode 100644 node_modules/pngjs/coverage/lcov-report/bitmapper.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/bitpacker.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/block-navigation.js create mode 100644 node_modules/pngjs/coverage/lcov-report/chunkstream.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/constants.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/crc.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/favicon.png create mode 100644 node_modules/pngjs/coverage/lcov-report/filter-pack.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/filter-parse-async.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/filter-parse-sync.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/filter-parse.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/format-normaliser.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/index.html create mode 100644 node_modules/pngjs/coverage/lcov-report/interlace.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/packer-async.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/packer-sync.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/packer.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/paeth-predictor.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/parser-async.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/parser-sync.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/parser.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/png-sync.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/png.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/prettify.css create mode 100644 node_modules/pngjs/coverage/lcov-report/prettify.js create mode 100644 node_modules/pngjs/coverage/lcov-report/sort-arrow-sprite.png create mode 100644 node_modules/pngjs/coverage/lcov-report/sorter.js create mode 100644 node_modules/pngjs/coverage/lcov-report/sync-inflate.js.html create mode 100644 node_modules/pngjs/coverage/lcov-report/sync-reader.js.html create mode 100644 node_modules/pngjs/coverage/lcov.info create mode 100644 node_modules/pngjs/lib/bitmapper.js create mode 100644 node_modules/pngjs/lib/bitpacker.js create mode 100644 node_modules/pngjs/lib/chunkstream.js create mode 100644 node_modules/pngjs/lib/constants.js create mode 100644 node_modules/pngjs/lib/crc.js create mode 100644 node_modules/pngjs/lib/filter-pack.js create mode 100644 node_modules/pngjs/lib/filter-parse-async.js create mode 100644 node_modules/pngjs/lib/filter-parse-sync.js create mode 100644 node_modules/pngjs/lib/filter-parse.js create mode 100644 node_modules/pngjs/lib/format-normaliser.js create mode 100644 node_modules/pngjs/lib/interlace.js create mode 100644 node_modules/pngjs/lib/packer-async.js create mode 100644 node_modules/pngjs/lib/packer-sync.js create mode 100644 node_modules/pngjs/lib/packer.js create mode 100644 node_modules/pngjs/lib/paeth-predictor.js create mode 100644 node_modules/pngjs/lib/parser-async.js create mode 100644 node_modules/pngjs/lib/parser-sync.js create mode 100644 node_modules/pngjs/lib/parser.js create mode 100644 node_modules/pngjs/lib/png-sync.js create mode 100644 node_modules/pngjs/lib/png.js create mode 100644 node_modules/pngjs/lib/sync-inflate.js create mode 100644 node_modules/pngjs/lib/sync-reader.js create mode 100644 node_modules/pngjs/package.json create mode 100644 node_modules/postgres-array/index.d.ts create mode 100644 node_modules/postgres-array/index.js create mode 100644 node_modules/postgres-array/license create mode 100644 node_modules/postgres-array/package.json create mode 100644 node_modules/postgres-array/readme.md create mode 100644 node_modules/postgres-bytea/index.js create mode 100644 node_modules/postgres-bytea/license create mode 100644 node_modules/postgres-bytea/package.json create mode 100644 node_modules/postgres-bytea/readme.md create mode 100644 node_modules/postgres-date/index.js create mode 100644 node_modules/postgres-date/license create mode 100644 node_modules/postgres-date/package.json create mode 100644 node_modules/postgres-date/readme.md create mode 100644 node_modules/postgres-interval/index.d.ts create mode 100644 node_modules/postgres-interval/index.js create mode 100644 node_modules/postgres-interval/license create mode 100644 node_modules/postgres-interval/package.json create mode 100644 node_modules/postgres-interval/readme.md create mode 100644 node_modules/postgres/README.md create mode 100644 node_modules/postgres/package.json create mode 100644 node_modules/postgres/src/build.js create mode 100644 node_modules/postgres/src/cf.js create mode 100644 node_modules/postgres/src/connection.js create mode 100644 node_modules/postgres/src/diagnostics.js create mode 100644 node_modules/postgres/src/errors.js create mode 100644 node_modules/postgres/src/index.js create mode 100644 node_modules/postgres/src/large.js create mode 100644 node_modules/postgres/src/pool.js create mode 100644 node_modules/postgres/src/protocol.js create mode 100644 node_modules/postgres/src/query.js create mode 100644 node_modules/postgres/src/result.js create mode 100644 node_modules/postgres/src/socket.js create mode 100644 node_modules/postgres/src/startup.js create mode 100644 node_modules/postgres/src/subscribe.js create mode 100644 node_modules/postgres/src/types.js create mode 100644 node_modules/postgres/types/index.d.ts create mode 100644 node_modules/qrcode/README.md create mode 100644 node_modules/qrcode/bin/qrcode create mode 100644 node_modules/qrcode/helper/to-sjis-browser.js create mode 100644 node_modules/qrcode/helper/to-sjis.js create mode 100644 node_modules/qrcode/lib/browser.js create mode 100644 node_modules/qrcode/lib/can-promise.js create mode 100644 node_modules/qrcode/lib/core/alignment-pattern.js create mode 100644 node_modules/qrcode/lib/core/alphanumeric-data.js create mode 100644 node_modules/qrcode/lib/core/bit-buffer.js create mode 100644 node_modules/qrcode/lib/core/bit-matrix.js create mode 100644 node_modules/qrcode/lib/core/byte-data.js create mode 100644 node_modules/qrcode/lib/core/error-correction-code.js create mode 100644 node_modules/qrcode/lib/core/error-correction-level.js create mode 100644 node_modules/qrcode/lib/core/finder-pattern.js create mode 100644 node_modules/qrcode/lib/core/format-info.js create mode 100644 node_modules/qrcode/lib/core/galois-field.js create mode 100644 node_modules/qrcode/lib/core/kanji-data.js create mode 100644 node_modules/qrcode/lib/core/mask-pattern.js create mode 100644 node_modules/qrcode/lib/core/mode.js create mode 100644 node_modules/qrcode/lib/core/numeric-data.js create mode 100644 node_modules/qrcode/lib/core/polynomial.js create mode 100644 node_modules/qrcode/lib/core/qrcode.js create mode 100644 node_modules/qrcode/lib/core/reed-solomon-encoder.js create mode 100644 node_modules/qrcode/lib/core/regex.js create mode 100644 node_modules/qrcode/lib/core/segments.js create mode 100644 node_modules/qrcode/lib/core/utils.js create mode 100644 node_modules/qrcode/lib/core/version-check.js create mode 100644 node_modules/qrcode/lib/core/version.js create mode 100644 node_modules/qrcode/lib/index.js create mode 100644 node_modules/qrcode/lib/renderer/canvas.js create mode 100644 node_modules/qrcode/lib/renderer/png.js create mode 100644 node_modules/qrcode/lib/renderer/svg-tag.js create mode 100644 node_modules/qrcode/lib/renderer/svg.js create mode 100644 node_modules/qrcode/lib/renderer/terminal.js create mode 100644 node_modules/qrcode/lib/renderer/terminal/terminal-small.js create mode 100644 node_modules/qrcode/lib/renderer/terminal/terminal.js create mode 100644 node_modules/qrcode/lib/renderer/utf8.js create mode 100644 node_modules/qrcode/lib/renderer/utils.js create mode 100644 node_modules/qrcode/lib/server.js create mode 100644 node_modules/qrcode/license create mode 100644 node_modules/qrcode/package.json create mode 100644 node_modules/require-directory/.jshintrc create mode 100644 node_modules/require-directory/.npmignore create mode 100644 node_modules/require-directory/.travis.yml create mode 100644 node_modules/require-directory/LICENSE create mode 100644 node_modules/require-directory/README.markdown create mode 100644 node_modules/require-directory/index.js create mode 100644 node_modules/require-directory/package.json create mode 100644 node_modules/require-main-filename/CHANGELOG.md create mode 100644 node_modules/require-main-filename/LICENSE.txt create mode 100644 node_modules/require-main-filename/README.md create mode 100644 node_modules/require-main-filename/index.js create mode 100644 node_modules/require-main-filename/package.json create mode 100644 node_modules/set-blocking/CHANGELOG.md create mode 100644 node_modules/set-blocking/LICENSE.txt create mode 100644 node_modules/set-blocking/README.md create mode 100644 node_modules/set-blocking/index.js create mode 100644 node_modules/set-blocking/package.json create mode 100644 node_modules/split2/LICENSE create mode 100644 node_modules/split2/README.md create mode 100644 node_modules/split2/bench.js create mode 100644 node_modules/split2/index.js create mode 100644 node_modules/split2/package.json create mode 100644 node_modules/split2/test.js create mode 100644 node_modules/string-width/index.d.ts create mode 100644 node_modules/string-width/index.js create mode 100644 node_modules/string-width/license create mode 100644 node_modules/string-width/package.json create mode 100644 node_modules/string-width/readme.md create mode 100644 node_modules/strip-ansi/index.d.ts create mode 100644 node_modules/strip-ansi/index.js create mode 100644 node_modules/strip-ansi/license create mode 100644 node_modules/strip-ansi/package.json create mode 100644 node_modules/strip-ansi/readme.md create mode 100644 node_modules/which-module/LICENSE create mode 100644 node_modules/which-module/README.md create mode 100644 node_modules/which-module/index.js create mode 100644 node_modules/which-module/package.json create mode 100644 node_modules/wrap-ansi/index.js create mode 100644 node_modules/wrap-ansi/license create mode 100644 node_modules/wrap-ansi/package.json create mode 100644 node_modules/wrap-ansi/readme.md create mode 100644 node_modules/xtend/.jshintrc create mode 100644 node_modules/xtend/LICENSE create mode 100644 node_modules/xtend/README.md create mode 100644 node_modules/xtend/immutable.js create mode 100644 node_modules/xtend/mutable.js create mode 100644 node_modules/xtend/package.json create mode 100644 node_modules/xtend/test.js create mode 100644 node_modules/y18n/CHANGELOG.md create mode 100644 node_modules/y18n/LICENSE create mode 100644 node_modules/y18n/README.md create mode 100644 node_modules/y18n/index.js create mode 100644 node_modules/y18n/package.json create mode 100644 node_modules/yargs-parser/CHANGELOG.md create mode 100644 node_modules/yargs-parser/LICENSE.txt create mode 100644 node_modules/yargs-parser/README.md create mode 100644 node_modules/yargs-parser/index.js create mode 100644 node_modules/yargs-parser/lib/tokenize-arg-string.js create mode 100644 node_modules/yargs-parser/package.json create mode 100644 node_modules/yargs/CHANGELOG.md create mode 100644 node_modules/yargs/LICENSE create mode 100644 node_modules/yargs/README.md create mode 100644 node_modules/yargs/build/lib/apply-extends.d.ts create mode 100644 node_modules/yargs/build/lib/apply-extends.js create mode 100644 node_modules/yargs/build/lib/argsert.d.ts create mode 100644 node_modules/yargs/build/lib/argsert.js create mode 100644 node_modules/yargs/build/lib/command.d.ts create mode 100644 node_modules/yargs/build/lib/command.js create mode 100644 node_modules/yargs/build/lib/common-types.d.ts create mode 100644 node_modules/yargs/build/lib/common-types.js create mode 100644 node_modules/yargs/build/lib/completion-templates.d.ts create mode 100644 node_modules/yargs/build/lib/completion-templates.js create mode 100644 node_modules/yargs/build/lib/completion.d.ts create mode 100644 node_modules/yargs/build/lib/completion.js create mode 100644 node_modules/yargs/build/lib/is-promise.d.ts create mode 100644 node_modules/yargs/build/lib/is-promise.js create mode 100644 node_modules/yargs/build/lib/levenshtein.d.ts create mode 100644 node_modules/yargs/build/lib/levenshtein.js create mode 100644 node_modules/yargs/build/lib/middleware.d.ts create mode 100644 node_modules/yargs/build/lib/middleware.js create mode 100644 node_modules/yargs/build/lib/obj-filter.d.ts create mode 100644 node_modules/yargs/build/lib/obj-filter.js create mode 100644 node_modules/yargs/build/lib/parse-command.d.ts create mode 100644 node_modules/yargs/build/lib/parse-command.js create mode 100644 node_modules/yargs/build/lib/process-argv.d.ts create mode 100644 node_modules/yargs/build/lib/process-argv.js create mode 100644 node_modules/yargs/build/lib/usage.d.ts create mode 100644 node_modules/yargs/build/lib/usage.js create mode 100644 node_modules/yargs/build/lib/validation.d.ts create mode 100644 node_modules/yargs/build/lib/validation.js create mode 100644 node_modules/yargs/build/lib/yargs.d.ts create mode 100644 node_modules/yargs/build/lib/yargs.js create mode 100644 node_modules/yargs/build/lib/yerror.d.ts create mode 100644 node_modules/yargs/build/lib/yerror.js create mode 100644 node_modules/yargs/index.js create mode 100644 node_modules/yargs/locales/be.json create mode 100644 node_modules/yargs/locales/de.json create mode 100644 node_modules/yargs/locales/en.json create mode 100644 node_modules/yargs/locales/es.json create mode 100644 node_modules/yargs/locales/fi.json create mode 100644 node_modules/yargs/locales/fr.json create mode 100644 node_modules/yargs/locales/hi.json create mode 100644 node_modules/yargs/locales/hu.json create mode 100644 node_modules/yargs/locales/id.json create mode 100644 node_modules/yargs/locales/it.json create mode 100644 node_modules/yargs/locales/ja.json create mode 100644 node_modules/yargs/locales/ko.json create mode 100644 node_modules/yargs/locales/nb.json create mode 100644 node_modules/yargs/locales/nl.json create mode 100644 node_modules/yargs/locales/nn.json create mode 100644 node_modules/yargs/locales/pirate.json create mode 100644 node_modules/yargs/locales/pl.json create mode 100644 node_modules/yargs/locales/pt.json create mode 100644 node_modules/yargs/locales/pt_BR.json create mode 100644 node_modules/yargs/locales/ru.json create mode 100644 node_modules/yargs/locales/th.json create mode 100644 node_modules/yargs/locales/tr.json create mode 100644 node_modules/yargs/locales/zh_CN.json create mode 100644 node_modules/yargs/locales/zh_TW.json create mode 100644 node_modules/yargs/package.json create mode 100644 node_modules/yargs/yargs.js create mode 100644 package.json create mode 100644 public/admin.html create mode 100644 public/admin.js create mode 100644 public/app.css create mode 100644 public/checkout.html create mode 100644 public/checkout.js create mode 100644 scripts/export-alipay-app-public-key.ts create mode 100644 scripts/inspect-gateways.ts create mode 100644 scripts/set-alipay-product.ts create mode 100644 src/db.ts create mode 100644 src/external-db.ts create mode 100644 src/payments.ts create mode 100644 src/security.ts create mode 100644 src/server.ts create mode 100644 start.ps1 create mode 100644 tests/security.test.ts create mode 100644 tsconfig.json diff --git a/.env b/.env new file mode 100644 index 0000000..dfe045f --- /dev/null +++ b/.env @@ -0,0 +1,8 @@ +PORT=3000 +HOST=127.0.0.1 +EXTERNAL_POSTGRES_HOST=localhost +EXTERNAL_POSTGRES_PORT=5432 +EXTERNAL_POSTGRES_DATABASE=new-api +EXTERNAL_POSTGRES_USER=root +EXTERNAL_POSTGRES_PASSWORD=44775bead42eb98fc1393bc65b34328058529490aa515757 +44775bead42eb98fc1393bc65b34328058529490aa515757 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..bb29b60 --- /dev/null +++ b/.env.example @@ -0,0 +1,17 @@ +PORT=3000 +HOST=0.0.0.0 +APP_BASE_URL=http://localhost:3000 +ADMIN_USERNAME=admin +ADMIN_PASSWORD=admin123456 +# 首次启动后,管理员密码以数据库中的值为准。 +# 生产环境务必配置固定的 32 字节主密钥(64 位十六进制)。 +PAY_MASTER_KEY= +# 本地联调业务回调时可设为 true;生产环境请保持 false,避免 SSRF。 +ALLOW_PRIVATE_CALLBACKS=false +# 外部 PostgreSQL 用于读取 users,并在支付确认后由服务端原子增加 users.quota;Docker Compose 内可设 postgres +EXTERNAL_POSTGRES_HOST=localhost +EXTERNAL_POSTGRES_PORT=5432 +EXTERNAL_POSTGRES_DATABASE=new-api +EXTERNAL_POSTGRES_USER=root +EXTERNAL_POSTGRES_PASSWORD=123456 + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ + diff --git a/README.md b/README.md new file mode 100644 index 0000000..1ea32a4 --- /dev/null +++ b/README.md @@ -0,0 +1,140 @@ +# MultiPay 本地聚合支付平台 + +一个使用 **Bun + SQLite** 的本地一体化支付服务,提供电脑端扫码收银台、支付宝当面付、微信 Native 支付、业务回调、充值记录和对账明细。 + +## 已实现 + +- 公开收银台:必须传入有效用户 ID,支持充值套餐、积分展示和近六个月充值记录。 +- 支付通道:本地模拟支付、支付宝 `alipay.trade.precreate`、微信支付 APIv3 Native 下单。 +- 安全校验:支付宝/微信请求签名、平台回调验签、金额复核、幂等处理。 +- 业务通知:HMAC-SHA256 签名、失败自动重试、手动重试、完整通知日志。 +- 管理后台:数据概览、用户管理、充值套餐、充值记录、按渠道/状态/分类/时间查询、对账明细、网关配置。 +- 本地存储:SQLite WAL 模式;支付密钥使用 AES-256-GCM 加密后入库。 +- 管理员安全:Argon2id 密码哈希、HttpOnly 会话、同源请求校验、审计日志。 + +## 启动 + +本机已安装 Bun 时: + +```powershell +bun install +Copy-Item .env.example .env +bun run start +``` + +当前机器可直接使用: + +```powershell +& 'C:\Users\11937\.bun\bin\bun.exe' install +& 'C:\Users\11937\.bun\bin\bun.exe' run start +``` + +- 收银台: +- 管理后台: +- 初始账户:`admin` +- 初始密码:`admin123456` + +首次登录后请立即在“系统设置”中修改密码。正式部署前,请在环境变量中设置固定的 `PAY_MASTER_KEY` 和外部可访问的 `APP_BASE_URL`,并使用 HTTPS 反向代理。 + +## 业务系统发起支付 + +把用户重定向到: + +```text +http://localhost:3000/pay?user_id=USER10001&merchant_order_no=ORDER202610310001&subject=账户充值¬ify_url=https%3A%2F%2Fmerchant.example.com%2Fpayment%2Fnotify&return_url=https%3A%2F%2Fmerchant.example.com%2Fresult +``` + +参数: + +| 参数 | 必填 | 说明 | +| --- | --- | --- | +| `user_id` | 是 | 后台已创建且启用的用户 ID;不存在时收银台拒绝进入 | +| `amount` | 否 | 用于预选同金额的后台套餐;没有匹配项时默认选择第一个可用套餐 | +| `merchant_order_no` | 是 | 6-32 位字母、数字、`_`、`-`,需唯一 | +| `subject` | 否 | 订单标题 | +| `category` | 否 | `recharge`、`purchase`、`service`、`other` | +| `notify_url` | 否 | 业务系统异步通知地址 | +| `return_url` | 否 | 支付完成后的返回地址 | +| `timestamp` / `sign` | 开启订单签名后必填 | 防止金额和回调地址被篡改 | + +### 外部订单签名 + +在后台开启“强制校验外部订单签名”后: + +```text +content = amount={服务端格式化为两位小数的套餐金额}&merchant_order_no={订单号}¬ify_url={回调地址}&package_id={套餐ID}×tamp={Unix秒}&user_id={用户ID} +sign = HMAC-SHA256(merchant_secret, content).hex() +``` + +时间戳有效期为 5 分钟。签名必须由业务服务端生成,不能把密钥放在网页代码里。 + +## 支付成功业务回调 + +支付页只轮询本平台订单状态,不直接修改业务数据。支付宝、微信等渠道经服务端查单或验签通知确认实付成功后,服务端先按订单绑定的用户 ID 原子增加 PostgreSQL `users.quota`;只有积分入账成功,订单才会变为 `paid` 并返回充值成功。业务入账使用独立的唯一订单流水表 `multipay_recharge_credits`,重复通知和重复轮询不会重复增加积分。 + +平台向 `notify_url` 发送 JSON: + +```json +{ + "event": "payment.succeeded", + "event_id": "evt_pay_xxx", + "order_id": "pay_xxx", + "merchant_order_no": "ORDER202610310001", + "user_id": "USER10001", + "package_id": 2, + "points": 520, + "channel": "wechat", + "amount": "99.00", + "status": "paid", + "provider_trade_no": "420000...", + "paid_at": "2026-10-31T08:00:00.000Z" +} +``` + +请求头: + +- `X-Pay-Timestamp`: Unix 秒 +- `X-Pay-Signature`: `HMAC-SHA256(merchant_secret, timestamp + "." + 原始请求体).hex()` +- `X-Pay-Event-Id`: 幂等事件 ID + +业务系统应校验签名与时间戳、按事件 ID 幂等处理,并返回任意 `2xx` 状态码。 + +## 用户与充值套餐 + +- 后台“用户管理”用于创建和停用本地用户,并查看积分余额、成功充值次数和累计金额。 +- 后台“充值套餐”可配置套餐名称、显示金额、到账积分、启用状态和展示顺序。 +- 支付渠道确认成功后,服务端将套餐积分增加到 PostgreSQL `users.quota`;入账成功后才向支付页返回成功。 +- 每个支付订单只允许生成一条业务入账流水;支付平台重复通知和页面重复轮询不会重复增加积分。 +- 收银台默认展示该用户最近六个月的成功充值记录。 +- 初始演示用户为 `demo-user`,仅用于本地验收,正式使用时请创建业务用户并停用演示用户。 + +## 后台退费 + +- 充值记录中的已支付订单可以由管理员发起原路全额退款。 +- 管理员可选择是否回退积分;默认回退该订单充值时到账的积分,也可以填写其他非负整数。 +- 支付渠道确认退款后,服务端按订单绑定的用户 ID 从 PostgreSQL `users.quota` 扣减积分,网页不会直接操作业务数据库。 +- 退款请求号与积分回退流水均按订单保持唯一;重复点击、网络重试或渠道重复响应不会重复退款、重复扣减积分。 +- 微信退款处于处理中时,可在充值记录中点击“查询退款”继续确认状态。 + +## 官方支付配置 + +### 支付宝 + +后台新增支付宝网关,填写 AppID、商户 PID、应用 RSA2 私钥和支付宝公钥。沙箱模式默认使用沙箱网关,正式模式使用生产网关。应用需在支付宝开放平台开通“当面付”。 + +### 微信支付 + +后台新增微信网关,填写 AppID、直连商户号、商户证书序列号、商户 API 私钥、微信支付公钥和 32 字节 APIv3 密钥。商户需开通 Native 支付。 + +回调地址必须能被支付平台通过公网 HTTPS 访问;本地联调可使用安全的隧道服务,并将 `APP_BASE_URL` 设置为该公网地址。 + +## 个人与企业主体说明 + +后台可将网关标注为“个人/个体主体”或“企业主体”。真实的服务端下单和自动回调仍要求支付宝或微信审核通过的商户资质与对应产品权限;普通个人收款码没有可靠的官方服务端通知,本项目不实现不安全的“个人免签监听”。 + +## 数据与备份 + +- 数据库:`data/multipay.sqlite` +- 自动生成的本地加密主密钥:`data/.master-key` + +备份时必须同时备份数据库和主密钥。丢失 `.master-key` 后,已保存的支付网关密钥无法解密。 diff --git a/alipayPublicKey_RSA2.txt b/alipayPublicKey_RSA2.txt new file mode 100644 index 0000000..99dc324 --- /dev/null +++ b/alipayPublicKey_RSA2.txt @@ -0,0 +1 @@ +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAowZZxGq7yUuwsnQTjSbZIh+n08bH0FMkp3fsrnuPXjvCjtflEbSBRDChLyrd8ehrINEaXsZ7DXA6y0qABv5nU3yUD31lKKa7Khk2uuiURcLDaC68Ur2ghx+KkLFxYWjxI9HGmn/kkkji7DVdeFDOOwnkDXbTYKshRmeJvpM1j1MfFV1AB6YlSGQHF0Vd/Wu2xZGwoWHwkA5ALpC6E3Ci0+bFwhLFC/EqO+7yScOliOdPw5AS3r4Btuj/rMmQTCjOVPZqV6QfhY96LOqwJ1qgSQiyG+PErMaKEexXRXPuVpGLjh9O80kYplIZ+UdtIPqZ4XPDTu7yzCencYhldhkxAwIDAQAB \ No newline at end of file diff --git a/bun.lock b/bun.lock new file mode 100644 index 0000000..03ddde4 --- /dev/null +++ b/bun.lock @@ -0,0 +1,103 @@ +{ + "lockfileVersion": 2, + "configVersion": 1, + "workspaces": { + "": { + "name": "multipay", + "dependencies": { + "pg": "^8.23.1", + "postgres": "^4.0.0", + "qrcode": "^1.5.4", + }, + }, + }, + "packages": { + "ansi-regex": ["ansi-regex@5.0.1", "", {}, "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ=="], + + "ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + + "camelcase": ["camelcase@5.3.1", "", {}, "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg=="], + + "cliui": ["cliui@6.0.0", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.0", "wrap-ansi": "^6.2.0" } }, "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ=="], + + "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + + "decamelize": ["decamelize@1.2.0", "", {}, "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA=="], + + "dijkstrajs": ["dijkstrajs@1.0.3", "", {}, "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA=="], + + "emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="], + + "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], + + "is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], + + "locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="], + + "p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], + + "p-locate": ["p-locate@4.1.0", "", { "dependencies": { "p-limit": "^2.2.0" } }, "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A=="], + + "p-try": ["p-try@2.2.0", "", {}, "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ=="], + + "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], + + "pg": ["pg@8.23.1", "", { "dependencies": { "pg-connection-string": "^2.14.1", "pg-pool": "^3.14.0", "pg-protocol": "^1.16.1", "pg-types": "2.2.0", "pgpass": "1.0.5" }, "optionalDependencies": { "pg-cloudflare": "^1.4.1" }, "peerDependencies": { "pg-native": ">=3.0.1" }, "optionalPeers": ["pg-native"] }, "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ=="], + + "pg-cloudflare": ["pg-cloudflare@1.4.1", "", {}, "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ=="], + + "pg-connection-string": ["pg-connection-string@2.14.1", "", {}, "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA=="], + + "pg-int8": ["pg-int8@1.0.1", "", {}, "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw=="], + + "pg-pool": ["pg-pool@3.14.0", "", { "peerDependencies": { "pg": ">=8.0" } }, "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw=="], + + "pg-protocol": ["pg-protocol@1.16.1", "", {}, "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg=="], + + "pg-types": ["pg-types@2.2.0", "", { "dependencies": { "pg-int8": "1.0.1", "postgres-array": "~2.0.0", "postgres-bytea": "~1.0.0", "postgres-date": "~1.0.4", "postgres-interval": "^1.1.0" } }, "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA=="], + + "pgpass": ["pgpass@1.0.5", "", { "dependencies": { "split2": "^4.1.0" } }, "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug=="], + + "pngjs": ["pngjs@5.0.0", "", {}, "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw=="], + + "postgres": ["postgres@4.0.0", "", {}, "sha512-kBh8qXtcvvIAc00DftQyOxz7M/3Zxww1tRMXZPLzipNXXl5PIzHml+9zB3Mrge2U8ldc0WF1ZdLp1iYQi7Kh3A=="], + + "postgres-array": ["postgres-array@2.0.0", "", {}, "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA=="], + + "postgres-bytea": ["postgres-bytea@1.0.1", "", {}, "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ=="], + + "postgres-date": ["postgres-date@1.0.7", "", {}, "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q=="], + + "postgres-interval": ["postgres-interval@1.2.0", "", { "dependencies": { "xtend": "^4.0.0" } }, "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ=="], + + "qrcode": ["qrcode@1.5.4", "", { "dependencies": { "dijkstrajs": "^1.0.1", "pngjs": "^5.0.0", "yargs": "^15.3.1" }, "bin": { "qrcode": "bin/qrcode" } }, "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg=="], + + "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], + + "require-main-filename": ["require-main-filename@2.0.0", "", {}, "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg=="], + + "set-blocking": ["set-blocking@2.0.0", "", {}, "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw=="], + + "split2": ["split2@4.2.0", "", {}, "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg=="], + + "string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], + + "which-module": ["which-module@2.0.1", "", {}, "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ=="], + + "wrap-ansi": ["wrap-ansi@6.2.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA=="], + + "xtend": ["xtend@4.0.2", "", {}, "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="], + + "y18n": ["y18n@4.0.3", "", {}, "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ=="], + + "yargs": ["yargs@15.4.1", "", { "dependencies": { "cliui": "^6.0.0", "decamelize": "^1.2.0", "find-up": "^4.1.0", "get-caller-file": "^2.0.1", "require-directory": "^2.1.1", "require-main-filename": "^2.0.0", "set-blocking": "^2.0.0", "string-width": "^4.2.0", "which-module": "^2.0.0", "y18n": "^4.0.0", "yargs-parser": "^18.1.2" } }, "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A=="], + + "yargs-parser": ["yargs-parser@18.1.3", "", { "dependencies": { "camelcase": "^5.0.0", "decamelize": "^1.2.0" } }, "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ=="], + } +} diff --git a/data/.master-key b/data/.master-key new file mode 100644 index 0000000..5818777 --- /dev/null +++ b/data/.master-key @@ -0,0 +1 @@ +8e9d4be99ec9d8e17ffd5ca982c38f1aa8eec3632c463d8f9c4f8bfe92d6d4b4 \ No newline at end of file diff --git a/data/alipay_app_public_key.pem b/data/alipay_app_public_key.pem new file mode 100644 index 0000000..527e483 --- /dev/null +++ b/data/alipay_app_public_key.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt3Dil3+ty7P6FzatAFmC +5gqtYHZ7qCeht1Y3/BdradbTnTEEb6b9NfTJDcvBtTzrZ/QPrkr+ZsUDRB4bJDNh +2LscRbEMafwHlLsdW3R8KAtizrSE1LzCa8dACDSMWQRlH24Q/qFPDH+ebcGr+n82 +Muk5PCCnrH3ZUjRQfAg2TT18meYDsnmKk8W077XwiF8dUh77Jwn9CUHN5ZzCWoD6 +NuXwt7JqX0CwT66ffrWo2SjicaFi3egnqpIGZK1kNHzwTx/cvEwbImswPQ3nRHai +/h4TzQkdv+qpSX3GHRXRqzgxxZdHPnHlxxMBe1XfiXvTsTPsTAfUOsBro2YqDtXC +fwIDAQAB +-----END PUBLIC KEY----- diff --git a/data/alipay_app_public_key.txt b/data/alipay_app_public_key.txt new file mode 100644 index 0000000..07bc6d2 --- /dev/null +++ b/data/alipay_app_public_key.txt @@ -0,0 +1 @@ +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt3Dil3+ty7P6FzatAFmC5gqtYHZ7qCeht1Y3/BdradbTnTEEb6b9NfTJDcvBtTzrZ/QPrkr+ZsUDRB4bJDNh2LscRbEMafwHlLsdW3R8KAtizrSE1LzCa8dACDSMWQRlH24Q/qFPDH+ebcGr+n82Muk5PCCnrH3ZUjRQfAg2TT18meYDsnmKk8W077XwiF8dUh77Jwn9CUHN5ZzCWoD6NuXwt7JqX0CwT66ffrWo2SjicaFi3egnqpIGZK1kNHzwTx/cvEwbImswPQ3nRHai/h4TzQkdv+qpSX3GHRXRqzgxxZdHPnHlxxMBe1XfiXvTsTPsTAfUOsBro2YqDtXCfwIDAQAB \ No newline at end of file diff --git a/data/multipay.sqlite b/data/multipay.sqlite new file mode 100644 index 0000000000000000000000000000000000000000..6f823bffe0d9af95958ab4779fb0a38907a7428e GIT binary patch literal 143360 zcmeIb3v?sdc^(MxO*RR1PfrikYPE*bBQ~2x4^Zz1we$o8KoTSfk^l&j(2v#IdwKiXPsLc5TU$eNL3K*<;z>Sk5Nir&qSRrN-{^Ko(d3zQv62_G8Payu zHZWlOTQf5@n{5>SKM(({&n@^eWIe!Nd&l>FUq@~3PyE)fPVD?ko#wsHznuC}$B#^Y zWol#M=O;fl@-HUJ6aJA84}WVYY5(J)JN9MgU-ZlBog9Ah{8OXT-g*0pq7)>#u1NJ{ zMHY(%QOPNSrW6aww35^0irO7|-4_XXV}Y4q*dN%N>7Qz1#`tW8XS&nh6SG30Am{Ew zxLVC=_h&>wlQYFiLk}^_m!%{$tUnO-&3}}_?}`D)m%Tfo*v#CV(RA}4yf!kuId8WalC73=pe~X^RVy0L zr^Ot%$}~mgsRuvi9G#w((m%w#Jy_NFz1_ezMDj8Wz zRx7z~kSzEra=9w2S~69X8vQ8LQn8@QNmUcHYD?hS88o9?Iao1jRTO2lm7v{atoFey zO0gn?$Q#|ft0m3mJ9dmt<2UUmY)dnl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M|p!~tl%GFR%k7)ja6EA>tll=vLbRB z!&NNeBWgz^3bIhA@;p*qZ}5gsGgtxm?N|?&bj=<4uLz zOndVM4XlyoFw>?@<4ub|;+ctQ=`7Tp6fudLc|O!RDme)x7bxZ!=JP`GgQ}H4s0B(m tmRoo+)Hy0S2_zSoNmKoOl$=Jjp%?gyHGIqW{K!xI!f*T$`ixUea07R3&c6Tv literal 0 HcmV?d00001 diff --git a/data/multipay.sqlite-wal b/data/multipay.sqlite-wal new file mode 100644 index 0000000000000000000000000000000000000000..c66c2165b1f32c2b56213deca41f126290b491e1 GIT binary patch literal 1318432 zcmeFa3w#_`dH284>b8=0$2VD46eqHswXG-~&z!k$vQ1@Mc6@g%*^Y<8c6N7GUTaq? z?XE1#DHl6UYaq}RQrdsH{CU%GZ2~QYQfPqBzvb-(2!#Lz3U6s>69VP(LYfvx-oF3m z%6d!5g>!bd+pIo_{6ntcCT zd;eQ+|MmOdl7gf*cly||uSuVN==mpu%(s2*%xQpZGxnNB{{S0VIF~ zkN^@u0!RP}AOR$R1TGta!FKTE9Px3_jOgS2#h!I+-Rm}&P8qzErXB$1VPp=Jj}h=_1ps-hog z>AW#acaSu*xoy;c@YJIZeCMH$f9HYsK6UY+;q{b~#WhLmFTfk~C$}jRhSauaJ1Jq}T*2(b; zoc+)L_=}F~@BJp7X5eRj|Sc7WhE|NB{{S0VIF~kN^@u0!RP}AOR$R1g>%d z?S7_3@YCO1rIp1@WmW z@4lz|uI`b*e+Rx8cqlL**caH;_0z7;cD-hmvrqWS(++E1BaCcsY)oKsCCh1wKEgI-%(0xH>Lc5lG3HcOpvJc}Hs&Le z!fFDikBl^BEWvD0MIXKyjQfFx{c>jgV`dGD%EZy|Fg5M!iZ1~6zAGxV1V**oAf$yfq#$tqkF;Vs5jbOYaUlI{C zILWde-at+3@hzE2`p8h@;!DPYK73=N;yIX1%Mz8>!#6BdeA#SdedFRw#+*KUeS_jT z#hS%(iCD4u6kndsrZ2E|h|Xnbp$Djtks()94^`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%WB=c4+0R#{>G|e>?K7z0_ zQ=_b-vz2z(Z>4UZxEf*d*@ewDH>_1yUuc-RejAcp)z}J7n6#%Vy?Z$)tkRziDhey` z!m3>iUKSemjFC(2a8Mbb)-;l}X=S#=4hKKC8#dVD(2cucjloCIbc|Wb08`SaF47am zydfNbkD%!pcq*&9HUpXE0@NCX0TQVwn!&Q1uw6H(u#6q{CvxN6cDT&acDSW4zdg2F ebx5^&H~r;KXfrk$50kvGV>wK4#-0E^g8v7#sJGGp literal 0 HcmV?d00001 diff --git a/miyao.txt b/miyao.txt new file mode 100644 index 0000000..da79b4a --- /dev/null +++ b/miyao.txt @@ -0,0 +1,4 @@ +应用私钥 +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC3cOKXf63Ls/oXNq0AWYLmCq1gdnuoJ6G3Vjf8F2tp1tOdMQRvpv019MkNy8G1POtn9A+uSv5mxQNEHhskM2HYuxxFsQxp/AeUux1bdHwoC2LOtITUvMJrx0AINIxZBGUfbhD+oU8Mf55twav6fzYy6Tk8IKesfdlSNFB8CDZNPXyZ5gOyeYqTxbTvtfCIXx1SHvsnCf0JQc3lnMJagPo25fC3smpfQLBPrp9+tajZKOJxoWLd6CeqkgZkrWQ0fPBPH9y8TBsiazA9DedEdqL+HhPNCR2/6qlJfcYdFdGrODHFl0c+ceXHEwF7Vd+Je9OxM+xMB9Q6wGujZioO1cJ/AgMBAAECggEASUxvDlAzVuEMfngXertJpbgAfTn6wT9MzCBEcJO/FOSFXBs5BZA5P3UXXU7ckRnNipUoKuHGc7QnUPGisL1jTKG/c02Cg1r0gIaf/Wo3Lh0Wlzfkl8jw+vX77QtqRSuPaJanbcdw+bKI0JyBpq9sLb2pZBA8T51d2A4VVupFIGlR+0QGkQzf1JvpQ/g48xGb2yrBk4cyMOOq3wUWiabzs794TK11n4bzJ1Mb5mDqCTd8NkRutyVLd/2ICRz6p4K7Yo4jnyBQgIz7aUakmk+129u+YP/LywKXEiemN1Os2k1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LDaC68Ur2ghx+KkLFxYWjxI9HGmn/kkkji7DVdeFDOOwnkDXbTYKshRmeJvpM1j1MfFV1AB6YlSGQHF0Vd/Wu2xZGwoWHwkA5ALpC6E3Ci0+bFwhLFC/EqO+7yScOliOdPw5AS3r4Btuj/rMmQTCjOVPZqV6QfhY96LOqwJ1qgSQiyG+PErMaKEexXRXPuVpGLjh9O80kYplIZ+UdtIPqZ4XPDTu7yzCencYhldhkxAwIDAQAB diff --git a/node_modules/.bin/qrcode.bunx b/node_modules/.bin/qrcode.bunx new file mode 100644 index 0000000000000000000000000000000000000000..9aef9e8621ba5b3eb6f9bd04aa00e46a344a78e2 GIT binary patch literal 58 ucmXS9C}K!v$Y)4lNM(p&NMguj$OF=aNTNy%3_vl63Izrbj|+&+R|5b?ObO%w literal 0 HcmV?d00001 diff --git a/node_modules/.bin/qrcode.exe b/node_modules/.bin/qrcode.exe new file mode 100644 index 0000000000000000000000000000000000000000..ddd76cfd176229fe2f3e563e460c964d89cd11d0 GIT binary patch literal 8192 zcmeHMeQ;CPmA{f@BY(g%Sxg*~ZXfP5*jq4mmf4ytPW+5TugEjF!NIg4#gF z^n{%bo0XB&;jN;X%uaT;on|`Bz;>D0?o7$h;IL^c0l|}YqPE%;g)Yi-E0F*|(38qo-@KwI#&GL~uxIAOxgsqm+l_y$zmBgqh3&(Z` zoQdusXTm=UWTaQte!3oOlUj3(IUi*VhmGMtx*X7awk9k_Zdk%!<;hM9-*7Rs z${pS7u-0frTt5L;eR66!xJ2P^PuO3bK4H=Bn<_bCnX+QYNKO5On3*WVe+lbB;2Tbc z-{bnnj;0jXKWMtNHM!pF96L>BZ%JBNE%8;MgNG59#!;rJM@`sV<{QbPWa1G1bptc ziP%PBtYLELEAsR!79svq=&B@MHs^C9ghK3nM9bY4-P=4@Bg8Xi=!`O9-&IVIpUqT! zT8O<3it^P%QUuUxxrvNPF8+QwxS}(aLM#O;Pb{;;NIPQSjLsBm^4Eo9742?$?1sTc zE^PkmWmcz=awNa`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qQr literal 0 HcmV?d00001 diff --git a/node_modules/ansi-regex/index.d.ts b/node_modules/ansi-regex/index.d.ts new file mode 100644 index 0000000..2dbf6af --- /dev/null +++ b/node_modules/ansi-regex/index.d.ts @@ -0,0 +1,37 @@ +declare namespace ansiRegex { + interface Options { + /** + Match only the first ANSI escape. + + @default false + */ + onlyFirst: boolean; + } +} + +/** +Regular expression for matching ANSI escape codes. + +@example +``` +import ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` +*/ +declare function ansiRegex(options?: ansiRegex.Options): RegExp; + +export = ansiRegex; diff --git a/node_modules/ansi-regex/index.js b/node_modules/ansi-regex/index.js new file mode 100644 index 0000000..616ff83 --- /dev/null +++ b/node_modules/ansi-regex/index.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = ({onlyFirst = false} = {}) => { + const pattern = [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' + ].join('|'); + + return new RegExp(pattern, onlyFirst ? undefined : 'g'); +}; diff --git a/node_modules/ansi-regex/license b/node_modules/ansi-regex/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/ansi-regex/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/ansi-regex/package.json b/node_modules/ansi-regex/package.json new file mode 100644 index 0000000..017f531 --- /dev/null +++ b/node_modules/ansi-regex/package.json @@ -0,0 +1,55 @@ +{ + "name": "ansi-regex", + "version": "5.0.1", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": "chalk/ansi-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd", + "view-supported": "node fixtures/view-codes.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.9.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/ansi-regex/readme.md b/node_modules/ansi-regex/readme.md new file mode 100644 index 0000000..4d848bc --- /dev/null +++ b/node_modules/ansi-regex/readme.md @@ -0,0 +1,78 @@ +# ansi-regex + +> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) + + +## Install + +``` +$ npm install ansi-regex +``` + + +## Usage + +```js +const ansiRegex = require('ansi-regex'); + +ansiRegex().test('\u001B[4mcake\u001B[0m'); +//=> true + +ansiRegex().test('cake'); +//=> false + +'\u001B[4mcake\u001B[0m'.match(ansiRegex()); +//=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] +``` + + +## API + +### ansiRegex(options?) + +Returns a regex for matching ANSI escape codes. + +#### options + +Type: `object` + +##### onlyFirst + +Type: `boolean`
+Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first ANSI escape. + + +## FAQ + +### Why do you test for codes not in the ECMA 48 standard? + +Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. + +On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/ansi-styles/index.d.ts b/node_modules/ansi-styles/index.d.ts new file mode 100644 index 0000000..44a907e --- /dev/null +++ b/node_modules/ansi-styles/index.d.ts @@ -0,0 +1,345 @@ +declare type CSSColor = + | 'aliceblue' + | 'antiquewhite' + | 'aqua' + | 'aquamarine' + | 'azure' + | 'beige' + | 'bisque' + | 'black' + | 'blanchedalmond' + | 'blue' + | 'blueviolet' + | 'brown' + | 'burlywood' + | 'cadetblue' + | 'chartreuse' + | 'chocolate' + | 'coral' + | 'cornflowerblue' + | 'cornsilk' + | 'crimson' + | 'cyan' + | 'darkblue' + | 'darkcyan' + | 'darkgoldenrod' + | 'darkgray' + | 'darkgreen' + | 'darkgrey' + | 'darkkhaki' + | 'darkmagenta' + | 'darkolivegreen' + | 'darkorange' + | 'darkorchid' + | 'darkred' + | 'darksalmon' + | 'darkseagreen' + | 'darkslateblue' + | 'darkslategray' + | 'darkslategrey' + | 'darkturquoise' + | 'darkviolet' + | 'deeppink' + | 'deepskyblue' + | 'dimgray' + | 'dimgrey' + | 'dodgerblue' + | 'firebrick' + | 'floralwhite' + | 'forestgreen' + | 'fuchsia' + | 'gainsboro' + | 'ghostwhite' + | 'gold' + | 'goldenrod' + | 'gray' + | 'green' + | 'greenyellow' + | 'grey' + | 'honeydew' + | 'hotpink' + | 'indianred' + | 'indigo' + | 'ivory' + | 'khaki' + | 'lavender' + | 'lavenderblush' + | 'lawngreen' + | 'lemonchiffon' + | 'lightblue' + | 'lightcoral' + | 'lightcyan' + | 'lightgoldenrodyellow' + | 'lightgray' + | 'lightgreen' + | 'lightgrey' + | 'lightpink' + | 'lightsalmon' + | 'lightseagreen' + | 'lightskyblue' + | 'lightslategray' + | 'lightslategrey' + | 'lightsteelblue' + | 'lightyellow' + | 'lime' + | 'limegreen' + | 'linen' + | 'magenta' + | 'maroon' + | 'mediumaquamarine' + | 'mediumblue' + | 'mediumorchid' + | 'mediumpurple' + | 'mediumseagreen' + | 'mediumslateblue' + | 'mediumspringgreen' + | 'mediumturquoise' + | 'mediumvioletred' + | 'midnightblue' + | 'mintcream' + | 'mistyrose' + | 'moccasin' + | 'navajowhite' + | 'navy' + | 'oldlace' + | 'olive' + | 'olivedrab' + | 'orange' + | 'orangered' + | 'orchid' + | 'palegoldenrod' + | 'palegreen' + | 'paleturquoise' + | 'palevioletred' + | 'papayawhip' + | 'peachpuff' + | 'peru' + | 'pink' + | 'plum' + | 'powderblue' + | 'purple' + | 'rebeccapurple' + | 'red' + | 'rosybrown' + | 'royalblue' + | 'saddlebrown' + | 'salmon' + | 'sandybrown' + | 'seagreen' + | 'seashell' + | 'sienna' + | 'silver' + | 'skyblue' + | 'slateblue' + | 'slategray' + | 'slategrey' + | 'snow' + | 'springgreen' + | 'steelblue' + | 'tan' + | 'teal' + | 'thistle' + | 'tomato' + | 'turquoise' + | 'violet' + | 'wheat' + | 'white' + | 'whitesmoke' + | 'yellow' + | 'yellowgreen'; + +declare namespace ansiStyles { + interface ColorConvert { + /** + The RGB color space. + + @param red - (`0`-`255`) + @param green - (`0`-`255`) + @param blue - (`0`-`255`) + */ + rgb(red: number, green: number, blue: number): string; + + /** + The RGB HEX color space. + + @param hex - A hexadecimal string containing RGB data. + */ + hex(hex: string): string; + + /** + @param keyword - A CSS color name. + */ + keyword(keyword: CSSColor): string; + + /** + The HSL color space. + + @param hue - (`0`-`360`) + @param saturation - (`0`-`100`) + @param lightness - (`0`-`100`) + */ + hsl(hue: number, saturation: number, lightness: number): string; + + /** + The HSV color space. + + @param hue - (`0`-`360`) + @param saturation - (`0`-`100`) + @param value - (`0`-`100`) + */ + hsv(hue: number, saturation: number, value: number): string; + + /** + The HSV color space. + + @param hue - (`0`-`360`) + @param whiteness - (`0`-`100`) + @param blackness - (`0`-`100`) + */ + hwb(hue: number, whiteness: number, blackness: number): string; + + /** + Use a [4-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4-bit) to set text color. + */ + ansi(ansi: number): string; + + /** + Use an [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color. + */ + ansi256(ansi: number): string; + } + + interface CSPair { + /** + The ANSI terminal control sequence for starting this style. + */ + readonly open: string; + + /** + The ANSI terminal control sequence for ending this style. + */ + readonly close: string; + } + + interface ColorBase { + readonly ansi: ColorConvert; + readonly ansi256: ColorConvert; + readonly ansi16m: ColorConvert; + + /** + The ANSI terminal control sequence for ending this color. + */ + readonly close: string; + } + + interface Modifier { + /** + Resets the current color chain. + */ + readonly reset: CSPair; + + /** + Make text bold. + */ + readonly bold: CSPair; + + /** + Emitting only a small amount of light. + */ + readonly dim: CSPair; + + /** + Make text italic. (Not widely supported) + */ + readonly italic: CSPair; + + /** + Make text underline. (Not widely supported) + */ + readonly underline: CSPair; + + /** + Inverse background and foreground colors. + */ + readonly inverse: CSPair; + + /** + Prints the text, but makes it invisible. + */ + readonly hidden: CSPair; + + /** + Puts a horizontal line through the center of the text. (Not widely supported) + */ + readonly strikethrough: CSPair; + } + + interface ForegroundColor { + readonly black: CSPair; + readonly red: CSPair; + readonly green: CSPair; + readonly yellow: CSPair; + readonly blue: CSPair; + readonly cyan: CSPair; + readonly magenta: CSPair; + readonly white: CSPair; + + /** + Alias for `blackBright`. + */ + readonly gray: CSPair; + + /** + Alias for `blackBright`. + */ + readonly grey: CSPair; + + readonly blackBright: CSPair; + readonly redBright: CSPair; + readonly greenBright: CSPair; + readonly yellowBright: CSPair; + readonly blueBright: CSPair; + readonly cyanBright: CSPair; + readonly magentaBright: CSPair; + readonly whiteBright: CSPair; + } + + interface BackgroundColor { + readonly bgBlack: CSPair; + readonly bgRed: CSPair; + readonly bgGreen: CSPair; + readonly bgYellow: CSPair; + readonly bgBlue: CSPair; + readonly bgCyan: CSPair; + readonly bgMagenta: CSPair; + readonly bgWhite: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGray: CSPair; + + /** + Alias for `bgBlackBright`. + */ + readonly bgGrey: CSPair; + + readonly bgBlackBright: CSPair; + readonly bgRedBright: CSPair; + readonly bgGreenBright: CSPair; + readonly bgYellowBright: CSPair; + readonly bgBlueBright: CSPair; + readonly bgCyanBright: CSPair; + readonly bgMagentaBright: CSPair; + readonly bgWhiteBright: CSPair; + } +} + +declare const ansiStyles: { + readonly modifier: ansiStyles.Modifier; + readonly color: ansiStyles.ForegroundColor & ansiStyles.ColorBase; + readonly bgColor: ansiStyles.BackgroundColor & ansiStyles.ColorBase; + readonly codes: ReadonlyMap; +} & ansiStyles.BackgroundColor & ansiStyles.ForegroundColor & ansiStyles.Modifier; + +export = ansiStyles; diff --git a/node_modules/ansi-styles/index.js b/node_modules/ansi-styles/index.js new file mode 100644 index 0000000..5d82581 --- /dev/null +++ b/node_modules/ansi-styles/index.js @@ -0,0 +1,163 @@ +'use strict'; + +const wrapAnsi16 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${code + offset}m`; +}; + +const wrapAnsi256 = (fn, offset) => (...args) => { + const code = fn(...args); + return `\u001B[${38 + offset};5;${code}m`; +}; + +const wrapAnsi16m = (fn, offset) => (...args) => { + const rgb = fn(...args); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +}; + +const ansi2ansi = n => n; +const rgb2rgb = (r, g, b) => [r, g, b]; + +const setLazyProperty = (object, property, get) => { + Object.defineProperty(object, property, { + get: () => { + const value = get(); + + Object.defineProperty(object, property, { + value, + enumerable: true, + configurable: true + }); + + return value; + }, + enumerable: true, + configurable: true + }); +}; + +/** @type {typeof import('color-convert')} */ +let colorConvert; +const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert === undefined) { + colorConvert = require('color-convert'); + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert)) { + const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; + if (sourceSpace === targetSpace) { + styles[name] = wrap(identity, offset); + } else if (typeof suite === 'object') { + styles[name] = wrap(suite[targetSpace], offset); + } + } + + return styles; +}; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); + setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); + setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); + setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); diff --git a/node_modules/ansi-styles/license b/node_modules/ansi-styles/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/ansi-styles/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/ansi-styles/package.json b/node_modules/ansi-styles/package.json new file mode 100644 index 0000000..7539328 --- /dev/null +++ b/node_modules/ansi-styles/package.json @@ -0,0 +1,56 @@ +{ + "name": "ansi-styles", + "version": "4.3.0", + "description": "ANSI escape codes for styling strings in the terminal", + "license": "MIT", + "repository": "chalk/ansi-styles", + "funding": "https://github.com/chalk/ansi-styles?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd", + "screenshot": "svg-term --command='node screenshot' --out=screenshot.svg --padding=3 --width=55 --height=3 --at=1000 --no-cursor" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "color-convert": "^2.0.1" + }, + "devDependencies": { + "@types/color-convert": "^1.9.0", + "ava": "^2.3.0", + "svg-term-cli": "^2.1.1", + "tsd": "^0.11.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/ansi-styles/readme.md b/node_modules/ansi-styles/readme.md new file mode 100644 index 0000000..24883de --- /dev/null +++ b/node_modules/ansi-styles/readme.md @@ -0,0 +1,152 @@ +# ansi-styles [![Build Status](https://travis-ci.org/chalk/ansi-styles.svg?branch=master)](https://travis-ci.org/chalk/ansi-styles) + +> [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) for styling strings in the terminal + +You probably want the higher-level [chalk](https://github.com/chalk/chalk) module for styling your strings. + + + +## Install + +``` +$ npm install ansi-styles +``` + +## Usage + +```js +const style = require('ansi-styles'); + +console.log(`${style.green.open}Hello world!${style.green.close}`); + + +// Color conversion between 16/256/truecolor +// NOTE: If conversion goes to 16 colors or 256 colors, the original color +// may be degraded to fit that color palette. This means terminals +// that do not support 16 million colors will best-match the +// original color. +console.log(style.bgColor.ansi.hsl(120, 80, 72) + 'Hello world!' + style.bgColor.close); +console.log(style.color.ansi256.rgb(199, 20, 250) + 'Hello world!' + style.color.close); +console.log(style.color.ansi16m.hex('#abcdef') + 'Hello world!' + style.color.close); +``` + +## API + +Each style has an `open` and `close` property. + +## Styles + +### Modifiers + +- `reset` +- `bold` +- `dim` +- `italic` *(Not widely supported)* +- `underline` +- `inverse` +- `hidden` +- `strikethrough` *(Not widely supported)* + +### Colors + +- `black` +- `red` +- `green` +- `yellow` +- `blue` +- `magenta` +- `cyan` +- `white` +- `blackBright` (alias: `gray`, `grey`) +- `redBright` +- `greenBright` +- `yellowBright` +- `blueBright` +- `magentaBright` +- `cyanBright` +- `whiteBright` + +### Background colors + +- `bgBlack` +- `bgRed` +- `bgGreen` +- `bgYellow` +- `bgBlue` +- `bgMagenta` +- `bgCyan` +- `bgWhite` +- `bgBlackBright` (alias: `bgGray`, `bgGrey`) +- `bgRedBright` +- `bgGreenBright` +- `bgYellowBright` +- `bgBlueBright` +- `bgMagentaBright` +- `bgCyanBright` +- `bgWhiteBright` + +## Advanced usage + +By default, you get a map of styles, but the styles are also available as groups. They are non-enumerable so they don't show up unless you access them explicitly. This makes it easier to expose only a subset in a higher-level module. + +- `style.modifier` +- `style.color` +- `style.bgColor` + +###### Example + +```js +console.log(style.color.green.open); +``` + +Raw escape codes (i.e. without the CSI escape prefix `\u001B[` and render mode postfix `m`) are available under `style.codes`, which returns a `Map` with the open codes as keys and close codes as values. + +###### Example + +```js +console.log(style.codes.get(36)); +//=> 39 +``` + +## [256 / 16 million (TrueColor) support](https://gist.github.com/XVilka/8346728) + +`ansi-styles` uses the [`color-convert`](https://github.com/Qix-/color-convert) package to allow for converting between various colors and ANSI escapes, with support for 256 and 16 million colors. + +The following color spaces from `color-convert` are supported: + +- `rgb` +- `hex` +- `keyword` +- `hsl` +- `hsv` +- `hwb` +- `ansi` +- `ansi256` + +To use these, call the associated conversion function with the intended output, for example: + +```js +style.color.ansi.rgb(100, 200, 15); // RGB to 16 color ansi foreground code +style.bgColor.ansi.rgb(100, 200, 15); // RGB to 16 color ansi background code + +style.color.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code +style.bgColor.ansi256.hsl(120, 100, 60); // HSL to 256 color ansi foreground code + +style.color.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color foreground code +style.bgColor.ansi16m.hex('#C0FFEE'); // Hex (RGB) to 16 million color background code +``` + +## Related + +- [ansi-escapes](https://github.com/sindresorhus/ansi-escapes) - ANSI escape codes for manipulating the terminal + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + +## For enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of `ansi-styles` and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-ansi-styles?utm_source=npm-ansi-styles&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) diff --git a/node_modules/camelcase/index.d.ts b/node_modules/camelcase/index.d.ts new file mode 100644 index 0000000..58f2069 --- /dev/null +++ b/node_modules/camelcase/index.d.ts @@ -0,0 +1,63 @@ +declare namespace camelcase { + interface Options { + /** + Uppercase the first character: `foo-bar` → `FooBar`. + + @default false + */ + readonly pascalCase?: boolean; + } +} + +declare const camelcase: { + /** + Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`. + + @param input - String to convert to camel case. + + @example + ``` + import camelCase = require('camelcase'); + + camelCase('foo-bar'); + //=> 'fooBar' + + camelCase('foo_bar'); + //=> 'fooBar' + + camelCase('Foo-Bar'); + //=> 'fooBar' + + camelCase('Foo-Bar', {pascalCase: true}); + //=> 'FooBar' + + camelCase('--foo.bar', {pascalCase: false}); + //=> 'fooBar' + + camelCase('foo bar'); + //=> 'fooBar' + + console.log(process.argv[3]); + //=> '--foo-bar' + camelCase(process.argv[3]); + //=> 'fooBar' + + camelCase(['foo', 'bar']); + //=> 'fooBar' + + camelCase(['__foo__', '--bar'], {pascalCase: true}); + //=> 'FooBar' + ``` + */ + (input: string | ReadonlyArray, options?: camelcase.Options): string; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function camelcase( + // input: string | ReadonlyArray, + // options?: camelcase.Options + // ): string; + // export = camelcase; + default: typeof camelcase; +}; + +export = camelcase; diff --git a/node_modules/camelcase/index.js b/node_modules/camelcase/index.js new file mode 100644 index 0000000..579f99b --- /dev/null +++ b/node_modules/camelcase/index.js @@ -0,0 +1,76 @@ +'use strict'; + +const preserveCamelCase = string => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && /[a-zA-Z]/.test(character) && character.toUpperCase() === character) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[a-zA-Z]/.test(character) && character.toLowerCase() === character) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = character.toLowerCase() === character && character.toUpperCase() !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = character.toUpperCase() === character && character.toLowerCase() !== character; + } + } + + return string; +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = Object.assign({ + pascalCase: false + }, options); + + const postProcess = x => options.pascalCase ? x.charAt(0).toUpperCase() + x.slice(1) : x; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + if (input.length === 1) { + return options.pascalCase ? input.toUpperCase() : input.toLowerCase(); + } + + const hasUpperCase = input !== input.toLowerCase(); + + if (hasUpperCase) { + input = preserveCamelCase(input); + } + + input = input + .replace(/^[_.\- ]+/, '') + .toLowerCase() + .replace(/[_.\- ]+(\w|$)/g, (_, p1) => p1.toUpperCase()) + .replace(/\d+(\w|$)/g, m => m.toUpperCase()); + + return postProcess(input); +}; + +module.exports = camelCase; +// TODO: Remove this for the next major release +module.exports.default = camelCase; diff --git a/node_modules/camelcase/license b/node_modules/camelcase/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/camelcase/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/camelcase/package.json b/node_modules/camelcase/package.json new file mode 100644 index 0000000..fbdbaaa --- /dev/null +++ b/node_modules/camelcase/package.json @@ -0,0 +1,43 @@ +{ + "name": "camelcase", + "version": "5.3.1", + "description": "Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar`", + "license": "MIT", + "repository": "sindresorhus/camelcase", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "camelcase", + "camel-case", + "camel", + "case", + "dash", + "hyphen", + "dot", + "underscore", + "separator", + "string", + "text", + "convert", + "pascalcase", + "pascal-case" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/camelcase/readme.md b/node_modules/camelcase/readme.md new file mode 100644 index 0000000..fde2726 --- /dev/null +++ b/node_modules/camelcase/readme.md @@ -0,0 +1,99 @@ +# camelcase [![Build Status](https://travis-ci.org/sindresorhus/camelcase.svg?branch=master)](https://travis-ci.org/sindresorhus/camelcase) + +> Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: `foo-bar` → `fooBar` + +--- + +
+ + Get professional support for 'camelcase' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
+ +--- + +## Install + +``` +$ npm install camelcase +``` + + +## Usage + +```js +const camelCase = require('camelcase'); + +camelCase('foo-bar'); +//=> 'fooBar' + +camelCase('foo_bar'); +//=> 'fooBar' + +camelCase('Foo-Bar'); +//=> 'fooBar' + +camelCase('Foo-Bar', {pascalCase: true}); +//=> 'FooBar' + +camelCase('--foo.bar', {pascalCase: false}); +//=> 'fooBar' + +camelCase('foo bar'); +//=> 'fooBar' + +console.log(process.argv[3]); +//=> '--foo-bar' +camelCase(process.argv[3]); +//=> 'fooBar' + +camelCase(['foo', 'bar']); +//=> 'fooBar' + +camelCase(['__foo__', '--bar'], {pascalCase: true}); +//=> 'FooBar' +``` + + +## API + +### camelCase(input, [options]) + +#### input + +Type: `string` `string[]` + +String to convert to camel case. + +#### options + +Type: `Object` + +##### pascalCase + +Type: `boolean`
+Default: `false` + +Uppercase the first character: `foo-bar` → `FooBar` + + +## Security + +To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. + + +## Related + +- [decamelize](https://github.com/sindresorhus/decamelize) - The inverse of this module +- [uppercamelcase](https://github.com/SamVerschueren/uppercamelcase) - Like this module, but to PascalCase instead of camelCase +- [titleize](https://github.com/sindresorhus/titleize) - Capitalize every word in string +- [humanize-string](https://github.com/sindresorhus/humanize-string) - Convert a camelized/dasherized/underscored string into a humanized one + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/cliui/CHANGELOG.md b/node_modules/cliui/CHANGELOG.md new file mode 100644 index 0000000..6a77f8f --- /dev/null +++ b/node_modules/cliui/CHANGELOG.md @@ -0,0 +1,76 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [6.0.0](https://www.github.com/yargs/cliui/compare/v5.0.0...v6.0.0) (2019-11-10) + + +### ⚠ BREAKING CHANGES + +* update deps, drop Node 6 + +### Code Refactoring + +* update deps, drop Node 6 ([62056df](https://www.github.com/yargs/cliui/commit/62056df)) + +## [5.0.0](https://github.com/yargs/cliui/compare/v4.1.0...v5.0.0) (2019-04-10) + + +### Bug Fixes + +* Update wrap-ansi to fix compatibility with latest versions of chalk. ([#60](https://github.com/yargs/cliui/issues/60)) ([7bf79ae](https://github.com/yargs/cliui/commit/7bf79ae)) + + +### BREAKING CHANGES + +* Drop support for node < 6. + + + + +## [4.1.0](https://github.com/yargs/cliui/compare/v4.0.0...v4.1.0) (2018-04-23) + + +### Features + +* add resetOutput method ([#57](https://github.com/yargs/cliui/issues/57)) ([7246902](https://github.com/yargs/cliui/commit/7246902)) + + + + +## [4.0.0](https://github.com/yargs/cliui/compare/v3.2.0...v4.0.0) (2017-12-18) + + +### Bug Fixes + +* downgrades strip-ansi to version 3.0.1 ([#54](https://github.com/yargs/cliui/issues/54)) ([5764c46](https://github.com/yargs/cliui/commit/5764c46)) +* set env variable FORCE_COLOR. ([#56](https://github.com/yargs/cliui/issues/56)) ([7350e36](https://github.com/yargs/cliui/commit/7350e36)) + + +### Chores + +* drop support for node < 4 ([#53](https://github.com/yargs/cliui/issues/53)) ([b105376](https://github.com/yargs/cliui/commit/b105376)) + + +### Features + +* add fallback for window width ([#45](https://github.com/yargs/cliui/issues/45)) ([d064922](https://github.com/yargs/cliui/commit/d064922)) + + +### BREAKING CHANGES + +* officially drop support for Node < 4 + + + + +## [3.2.0](https://github.com/yargs/cliui/compare/v3.1.2...v3.2.0) (2016-04-11) + + +### Bug Fixes + +* reduces tarball size ([acc6c33](https://github.com/yargs/cliui/commit/acc6c33)) + +### Features + +* adds standard-version for release management ([ff84e32](https://github.com/yargs/cliui/commit/ff84e32)) diff --git a/node_modules/cliui/LICENSE.txt b/node_modules/cliui/LICENSE.txt new file mode 100644 index 0000000..c7e2747 --- /dev/null +++ b/node_modules/cliui/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/cliui/README.md b/node_modules/cliui/README.md new file mode 100644 index 0000000..deacfa0 --- /dev/null +++ b/node_modules/cliui/README.md @@ -0,0 +1,115 @@ +# cliui + +[![Build Status](https://travis-ci.org/yargs/cliui.svg)](https://travis-ci.org/yargs/cliui) +[![Coverage Status](https://coveralls.io/repos/yargs/cliui/badge.svg?branch=)](https://coveralls.io/r/yargs/cliui?branch=) +[![NPM version](https://img.shields.io/npm/v/cliui.svg)](https://www.npmjs.com/package/cliui) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +easily create complex multi-column command-line-interfaces. + +## Example + +```js +var ui = require('cliui')() + +ui.div('Usage: $0 [command] [options]') + +ui.div({ + text: 'Options:', + padding: [2, 0, 2, 0] +}) + +ui.div( + { + text: "-f, --file", + width: 20, + padding: [0, 4, 0, 4] + }, + { + text: "the file to load." + + chalk.green("(if this description is long it wraps).") + , + width: 20 + }, + { + text: chalk.red("[required]"), + align: 'right' + } +) + +console.log(ui.toString()) +``` + + + +## Layout DSL + +cliui exposes a simple layout DSL: + +If you create a single `ui.div`, passing a string rather than an +object: + +* `\n`: characters will be interpreted as new rows. +* `\t`: characters will be interpreted as new columns. +* `\s`: characters will be interpreted as padding. + +**as an example...** + +```js +var ui = require('./')({ + width: 60 +}) + +ui.div( + 'Usage: node ./bin/foo.js\n' + + ' \t provide a regex\n' + + ' \t provide a glob\t [required]' +) + +console.log(ui.toString()) +``` + +**will output:** + +```shell +Usage: node ./bin/foo.js + provide a regex + provide a glob [required] +``` + +## Methods + +```js +cliui = require('cliui') +``` + +### cliui({width: integer}) + +Specify the maximum width of the UI being generated. +If no width is provided, cliui will try to get the current window's width and use it, and if that doesn't work, width will be set to `80`. + +### cliui({wrap: boolean}) + +Enable or disable the wrapping of text in a column. + +### cliui.div(column, column, column) + +Create a row with any number of columns, a column +can either be a string, or an object with the following +options: + +* **text:** some text to place in the column. +* **width:** the width of a column. +* **align:** alignment, `right` or `center`. +* **padding:** `[top, right, bottom, left]`. +* **border:** should a border be placed around the div? + +### cliui.span(column, column, column) + +Similar to `div`, except the next row will be appended without +a new line being created. + +### cliui.resetOutput() + +Resets the UI elements of the current cliui instance, maintaining the values +set for `width` and `wrap`. diff --git a/node_modules/cliui/index.js b/node_modules/cliui/index.js new file mode 100644 index 0000000..e917b00 --- /dev/null +++ b/node_modules/cliui/index.js @@ -0,0 +1,354 @@ +'use strict' + +const stringWidth = require('string-width') +const stripAnsi = require('strip-ansi') +const wrap = require('wrap-ansi') + +const align = { + right: alignRight, + center: alignCenter +} +const top = 0 +const right = 1 +const bottom = 2 +const left = 3 + +class UI { + constructor (opts) { + this.width = opts.width + this.wrap = opts.wrap + this.rows = [] + } + + span (...args) { + const cols = this.div(...args) + cols.span = true + } + + resetOutput () { + this.rows = [] + } + + div (...args) { + if (args.length === 0) { + this.div('') + } + + if (this.wrap && this._shouldApplyLayoutDSL(...args)) { + return this._applyLayoutDSL(args[0]) + } + + const cols = args.map(arg => { + if (typeof arg === 'string') { + return this._colFromString(arg) + } + + return arg + }) + + this.rows.push(cols) + return cols + } + + _shouldApplyLayoutDSL (...args) { + return args.length === 1 && typeof args[0] === 'string' && + /[\t\n]/.test(args[0]) + } + + _applyLayoutDSL (str) { + const rows = str.split('\n').map(row => row.split('\t')) + let leftColumnWidth = 0 + + // simple heuristic for layout, make sure the + // second column lines up along the left-hand. + // don't allow the first column to take up more + // than 50% of the screen. + rows.forEach(columns => { + if (columns.length > 1 && stringWidth(columns[0]) > leftColumnWidth) { + leftColumnWidth = Math.min( + Math.floor(this.width * 0.5), + stringWidth(columns[0]) + ) + } + }) + + // generate a table: + // replacing ' ' with padding calculations. + // using the algorithmically generated width. + rows.forEach(columns => { + this.div(...columns.map((r, i) => { + return { + text: r.trim(), + padding: this._measurePadding(r), + width: (i === 0 && columns.length > 1) ? leftColumnWidth : undefined + } + })) + }) + + return this.rows[this.rows.length - 1] + } + + _colFromString (text) { + return { + text, + padding: this._measurePadding(text) + } + } + + _measurePadding (str) { + // measure padding without ansi escape codes + const noAnsi = stripAnsi(str) + return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length] + } + + toString () { + const lines = [] + + this.rows.forEach(row => { + this.rowToString(row, lines) + }) + + // don't display any lines with the + // hidden flag set. + return lines + .filter(line => !line.hidden) + .map(line => line.text) + .join('\n') + } + + rowToString (row, lines) { + this._rasterize(row).forEach((rrow, r) => { + let str = '' + rrow.forEach((col, c) => { + const { width } = row[c] // the width with padding. + const wrapWidth = this._negatePadding(row[c]) // the width without padding. + + let ts = col // temporary string used during alignment/padding. + + if (wrapWidth > stringWidth(col)) { + ts += ' '.repeat(wrapWidth - stringWidth(col)) + } + + // align the string within its column. + if (row[c].align && row[c].align !== 'left' && this.wrap) { + ts = align[row[c].align](ts, wrapWidth) + if (stringWidth(ts) < wrapWidth) { + ts += ' '.repeat(width - stringWidth(ts) - 1) + } + } + + // apply border and padding to string. + const padding = row[c].padding || [0, 0, 0, 0] + if (padding[left]) { + str += ' '.repeat(padding[left]) + } + + str += addBorder(row[c], ts, '| ') + str += ts + str += addBorder(row[c], ts, ' |') + if (padding[right]) { + str += ' '.repeat(padding[right]) + } + + // if prior row is span, try to render the + // current row on the prior line. + if (r === 0 && lines.length > 0) { + str = this._renderInline(str, lines[lines.length - 1]) + } + }) + + // remove trailing whitespace. + lines.push({ + text: str.replace(/ +$/, ''), + span: row.span + }) + }) + + return lines + } + + // if the full 'source' can render in + // the target line, do so. + _renderInline (source, previousLine) { + const leadingWhitespace = source.match(/^ */)[0].length + const target = previousLine.text + const targetTextWidth = stringWidth(target.trimRight()) + + if (!previousLine.span) { + return source + } + + // if we're not applying wrapping logic, + // just always append to the span. + if (!this.wrap) { + previousLine.hidden = true + return target + source + } + + if (leadingWhitespace < targetTextWidth) { + return source + } + + previousLine.hidden = true + + return target.trimRight() + ' '.repeat(leadingWhitespace - targetTextWidth) + source.trimLeft() + } + + _rasterize (row) { + const rrows = [] + const widths = this._columnWidths(row) + let wrapped + + // word wrap all columns, and create + // a data-structure that is easy to rasterize. + row.forEach((col, c) => { + // leave room for left and right padding. + col.width = widths[c] + if (this.wrap) { + wrapped = wrap(col.text, this._negatePadding(col), { hard: true }).split('\n') + } else { + wrapped = col.text.split('\n') + } + + if (col.border) { + wrapped.unshift('.' + '-'.repeat(this._negatePadding(col) + 2) + '.') + wrapped.push("'" + '-'.repeat(this._negatePadding(col) + 2) + "'") + } + + // add top and bottom padding. + if (col.padding) { + wrapped.unshift(...new Array(col.padding[top] || 0).fill('')) + wrapped.push(...new Array(col.padding[bottom] || 0).fill('')) + } + + wrapped.forEach((str, r) => { + if (!rrows[r]) { + rrows.push([]) + } + + const rrow = rrows[r] + + for (let i = 0; i < c; i++) { + if (rrow[i] === undefined) { + rrow.push('') + } + } + + rrow.push(str) + }) + }) + + return rrows + } + + _negatePadding (col) { + let wrapWidth = col.width + if (col.padding) { + wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0) + } + + if (col.border) { + wrapWidth -= 4 + } + + return wrapWidth + } + + _columnWidths (row) { + if (!this.wrap) { + return row.map(col => { + return col.width || stringWidth(col.text) + }) + } + + let unset = row.length + let remainingWidth = this.width + + // column widths can be set in config. + const widths = row.map(col => { + if (col.width) { + unset-- + remainingWidth -= col.width + return col.width + } + + return undefined + }) + + // any unset widths should be calculated. + const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0 + + return widths.map((w, i) => { + if (w === undefined) { + return Math.max(unsetWidth, _minWidth(row[i])) + } + + return w + }) + } +} + +function addBorder (col, ts, style) { + if (col.border) { + if (/[.']-+[.']/.test(ts)) { + return '' + } + + if (ts.trim().length !== 0) { + return style + } + + return ' ' + } + + return '' +} + +// calculates the minimum width of +// a column, based on padding preferences. +function _minWidth (col) { + const padding = col.padding || [] + const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0) + if (col.border) { + return minWidth + 4 + } + + return minWidth +} + +function getWindowWidth () { + /* istanbul ignore next: depends on terminal */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return process.stdout.columns + } +} + +function alignRight (str, width) { + str = str.trim() + const strWidth = stringWidth(str) + + if (strWidth < width) { + return ' '.repeat(width - strWidth) + str + } + + return str +} + +function alignCenter (str, width) { + str = str.trim() + const strWidth = stringWidth(str) + + /* istanbul ignore next */ + if (strWidth >= width) { + return str + } + + return ' '.repeat((width - strWidth) >> 1) + str +} + +module.exports = function (opts = {}) { + return new UI({ + width: opts.width || getWindowWidth() || /* istanbul ignore next */ 80, + wrap: opts.wrap !== false + }) +} diff --git a/node_modules/cliui/package.json b/node_modules/cliui/package.json new file mode 100644 index 0000000..f92fd10 --- /dev/null +++ b/node_modules/cliui/package.json @@ -0,0 +1,65 @@ +{ + "name": "cliui", + "version": "6.0.0", + "description": "easily create complex multi-column command-line-interfaces", + "main": "index.js", + "scripts": { + "pretest": "standard", + "test": "nyc mocha", + "coverage": "nyc --reporter=text-lcov mocha | coveralls" + }, + "repository": { + "type": "git", + "url": "http://github.com/yargs/cliui.git" + }, + "config": { + "blanket": { + "pattern": [ + "index.js" + ], + "data-cover-never": [ + "node_modules", + "test" + ], + "output-reporter": "spec" + } + }, + "standard": { + "ignore": [ + "**/example/**" + ], + "globals": [ + "it" + ] + }, + "keywords": [ + "cli", + "command-line", + "layout", + "design", + "console", + "wrap", + "table" + ], + "author": "Ben Coe ", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + }, + "devDependencies": { + "chai": "^4.2.0", + "chalk": "^3.0.0", + "coveralls": "^3.0.3", + "mocha": "^6.2.2", + "nyc": "^14.1.1", + "standard": "^12.0.1" + }, + "files": [ + "index.js" + ], + "engine": { + "node": ">=8" + } +} diff --git a/node_modules/color-convert/CHANGELOG.md b/node_modules/color-convert/CHANGELOG.md new file mode 100644 index 0000000..0a7bce4 --- /dev/null +++ b/node_modules/color-convert/CHANGELOG.md @@ -0,0 +1,54 @@ +# 1.0.0 - 2016-01-07 + +- Removed: unused speed test +- Added: Automatic routing between previously unsupported conversions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Removed: `convert()` class +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: all functions to lookup dictionary +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Changed: `ansi` to `ansi256` +([#27](https://github.com/Qix-/color-convert/pull/27)) +- Fixed: argument grouping for functions requiring only one argument +([#27](https://github.com/Qix-/color-convert/pull/27)) + +# 0.6.0 - 2015-07-23 + +- Added: methods to handle +[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors: + - rgb2ansi16 + - rgb2ansi + - hsl2ansi16 + - hsl2ansi + - hsv2ansi16 + - hsv2ansi + - hwb2ansi16 + - hwb2ansi + - cmyk2ansi16 + - cmyk2ansi + - keyword2ansi16 + - keyword2ansi + - ansi162rgb + - ansi162hsl + - ansi162hsv + - ansi162hwb + - ansi162cmyk + - ansi162keyword + - ansi2rgb + - ansi2hsl + - ansi2hsv + - ansi2hwb + - ansi2cmyk + - ansi2keyword +([#18](https://github.com/harthur/color-convert/pull/18)) + +# 0.5.3 - 2015-06-02 + +- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]` +([#15](https://github.com/harthur/color-convert/issues/15)) + +--- + +Check out commit logs for older releases diff --git a/node_modules/color-convert/LICENSE b/node_modules/color-convert/LICENSE new file mode 100644 index 0000000..5b4c386 --- /dev/null +++ b/node_modules/color-convert/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) 2011-2016 Heather Arthur + +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/node_modules/color-convert/README.md b/node_modules/color-convert/README.md new file mode 100644 index 0000000..d4b08fc --- /dev/null +++ b/node_modules/color-convert/README.md @@ -0,0 +1,68 @@ +# color-convert + +[![Build Status](https://travis-ci.org/Qix-/color-convert.svg?branch=master)](https://travis-ci.org/Qix-/color-convert) + +Color-convert is a color conversion library for JavaScript and node. +It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest): + +```js +var convert = require('color-convert'); + +convert.rgb.hsl(140, 200, 100); // [96, 48, 59] +convert.keyword.rgb('blue'); // [0, 0, 255] + +var rgbChannels = convert.rgb.channels; // 3 +var cmykChannels = convert.cmyk.channels; // 4 +var ansiChannels = convert.ansi16.channels; // 1 +``` + +# Install + +```console +$ npm install color-convert +``` + +# API + +Simply get the property of the _from_ and _to_ conversion that you're looking for. + +All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function. + +All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha). + +```js +var convert = require('color-convert'); + +// Hex to LAB +convert.hex.lab('DEADBF'); // [ 76, 21, -2 ] +convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ] + +// RGB to CMYK +convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ] +convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ] +``` + +### Arrays +All functions that accept multiple arguments also support passing an array. + +Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.) + +```js +var convert = require('color-convert'); + +convert.rgb.hex(123, 45, 67); // '7B2D43' +convert.rgb.hex([123, 45, 67]); // '7B2D43' +``` + +## Routing + +Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex). + +Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js). + +# Contribute + +If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request. + +# License +Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE). diff --git a/node_modules/color-convert/conversions.js b/node_modules/color-convert/conversions.js new file mode 100644 index 0000000..2657f26 --- /dev/null +++ b/node_modules/color-convert/conversions.js @@ -0,0 +1,839 @@ +/* MIT license */ +/* eslint-disable no-mixed-operators */ +const cssKeywords = require('color-name'); + +// NOTE: conversions should only return primitive values (i.e. arrays, or +// values that give correct `typeof` results). +// do not use box values types (i.e. Number(), String(), etc.) + +const reverseKeywords = {}; +for (const key of Object.keys(cssKeywords)) { + reverseKeywords[cssKeywords[key]] = key; +} + +const convert = { + rgb: {channels: 3, labels: 'rgb'}, + hsl: {channels: 3, labels: 'hsl'}, + hsv: {channels: 3, labels: 'hsv'}, + hwb: {channels: 3, labels: 'hwb'}, + cmyk: {channels: 4, labels: 'cmyk'}, + xyz: {channels: 3, labels: 'xyz'}, + lab: {channels: 3, labels: 'lab'}, + lch: {channels: 3, labels: 'lch'}, + hex: {channels: 1, labels: ['hex']}, + keyword: {channels: 1, labels: ['keyword']}, + ansi16: {channels: 1, labels: ['ansi16']}, + ansi256: {channels: 1, labels: ['ansi256']}, + hcg: {channels: 3, labels: ['h', 'c', 'g']}, + apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, + gray: {channels: 1, labels: ['gray']} +}; + +module.exports = convert; + +// Hide .channels and .labels properties +for (const model of Object.keys(convert)) { + if (!('channels' in convert[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert[model].labels.length !== convert[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const {channels, labels} = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], 'channels', {value: channels}); + Object.defineProperty(convert[model], 'labels', {value: labels}); +} + +convert.rgb.hsl = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta; + } else if (g === max) { + h = 2 + (b - r) / delta; + } else if (b === max) { + h = 4 + (r - g) / delta; + } + + h = Math.min(h * 60, 360); + + if (h < 0) { + h += 360; + } + + const l = (min + max) / 2; + + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + + return [h, s * 100, l * 100]; +}; + +convert.rgb.hsv = function (rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + + if (r === v) { + h = bdif - gdif; + } else if (g === v) { + h = (1 / 3) + rdif - bdif; + } else if (b === v) { + h = (2 / 3) + gdif - rdif; + } + + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + + return [ + h * 360, + s * 100, + v * 100 + ]; +}; + +convert.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + + return [h, w * 100, b * 100]; +}; + +convert.rgb.cmyk = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + + return [c * 100, m * 100, y * 100, k * 100]; +}; + +function comparativeDistance(x, y) { + /* + See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + */ + return ( + ((x[0] - y[0]) ** 2) + + ((x[1] - y[1]) ** 2) + + ((x[2] - y[2]) ** 2) + ); +} + +convert.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(cssKeywords)) { + const value = cssKeywords[keyword]; + + // Compute comparative distance + const distance = comparativeDistance(rgb, value); + + // Check if its less, if so set as closest + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + + return currentClosestKeyword; +}; + +convert.keyword.rgb = function (keyword) { + return cssKeywords[keyword]; +}; + +convert.rgb.xyz = function (rgb) { + let r = rgb[0] / 255; + let g = rgb[1] / 255; + let b = rgb[2] / 255; + + // Assume sRGB + r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); + g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); + b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); + + const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); + const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); + const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); + + return [x * 100, y * 100, z * 100]; +}; + +convert.rgb.lab = function (rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.hsl.rgb = function (hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t2; + let t3; + let val; + + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + + if (l < 0.5) { + t2 = l * (1 + s); + } else { + t2 = l + s - l * s; + } + + const t1 = 2 * l - t2; + + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + + if (t3 > 1) { + t3--; + } + + if (6 * t3 < 1) { + val = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + val = t2; + } else if (3 * t3 < 2) { + val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + val = t1; + } + + rgb[i] = val * 255; + } + + return rgb; +}; + +convert.hsl.hsv = function (hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + + l *= 2; + s *= (l <= 1) ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); + + return [h, sv * 100, v * 100]; +}; + +convert.hsv.rgb = function (hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - (s * f)); + const t = 255 * v * (1 - (s * (1 - f))); + v *= 255; + + switch (hi) { + case 0: + return [v, t, p]; + case 1: + return [q, v, p]; + case 2: + return [p, v, t]; + case 3: + return [p, q, v]; + case 4: + return [t, p, v]; + case 5: + return [v, p, q]; + } +}; + +convert.hsv.hsl = function (hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= (lmin <= 1) ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + + return [h, sl * 100, l * 100]; +}; + +// http://dev.w3.org/csswg/css-color/#hwb-to-rgb +convert.hwb.rgb = function (hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + + // Wh + bl cant be > 1 + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + const n = wh + f * (v - wh); // Linear interpolation + + let r; + let g; + let b; + /* eslint-disable max-statements-per-line,no-multi-spaces */ + switch (i) { + default: + case 6: + case 0: r = v; g = n; b = wh; break; + case 1: r = n; g = v; b = wh; break; + case 2: r = wh; g = v; b = n; break; + case 3: r = wh; g = n; b = v; break; + case 4: r = n; g = wh; b = v; break; + case 5: r = v; g = wh; b = n; break; + } + /* eslint-enable max-statements-per-line,no-multi-spaces */ + + return [r * 255, g * 255, b * 255]; +}; + +convert.cmyk.rgb = function (cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.rgb = function (xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + + r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); + g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); + b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); + + // Assume sRGB + r = r > 0.0031308 + ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) + : r * 12.92; + + g = g > 0.0031308 + ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) + : g * 12.92; + + b = b > 0.0031308 + ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) + : b * 12.92; + + r = Math.min(Math.max(0, r), 1); + g = Math.min(Math.max(0, g), 1); + b = Math.min(Math.max(0, b), 1); + + return [r * 255, g * 255, b * 255]; +}; + +convert.xyz.lab = function (xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + + x /= 95.047; + y /= 100; + z /= 108.883; + + x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); + y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); + z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + + const l = (116 * y) - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + + return [l, a, b]; +}; + +convert.lab.xyz = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; + x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; + z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + + x *= 95.047; + y *= 100; + z *= 108.883; + + return [x, y, z]; +}; + +convert.lab.lch = function (lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + const c = Math.sqrt(a * a + b * b); + + return [l, c, h]; +}; + +convert.lch.lab = function (lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + + return [l, a, b]; +}; + +convert.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + let ansi = 30 + + ((Math.round(b / 255) << 2) + | (Math.round(g / 255) << 1) + | Math.round(r / 255)); + + if (value === 2) { + ansi += 60; + } + + return ansi; +}; + +convert.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; + +convert.rgb.ansi256 = function (args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (r === g && g === b) { + if (r < 8) { + return 16; + } + + if (r > 248) { + return 231; + } + + return Math.round(((r - 8) / 247) * 24) + 232; + } + + const ansi = 16 + + (36 * Math.round(r / 255 * 5)) + + (6 * Math.round(g / 255 * 5)) + + Math.round(b / 255 * 5); + + return ansi; +}; + +convert.ansi16.rgb = function (args) { + let color = args % 10; + + // Handle greyscale + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + + color = color / 10.5 * 255; + + return [color, color, color]; + } + + const mult = (~~(args > 50) + 1) * 0.5; + const r = ((color & 1) * mult) * 255; + const g = (((color >> 1) & 1) * mult) * 255; + const b = (((color >> 2) & 1) * mult) * 255; + + return [r, g, b]; +}; + +convert.ansi256.rgb = function (args) { + // Handle greyscale + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = (rem % 6) / 5 * 255; + + return [r, g, b]; +}; + +convert.rgb.hex = function (args) { + const integer = ((Math.round(args[0]) & 0xFF) << 16) + + ((Math.round(args[1]) & 0xFF) << 8) + + (Math.round(args[2]) & 0xFF); + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.hex.rgb = function (args) { + const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + if (!match) { + return [0, 0, 0]; + } + + let colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(char => { + return char + char; + }).join(''); + } + + const integer = parseInt(colorString, 16); + const r = (integer >> 16) & 0xFF; + const g = (integer >> 8) & 0xFF; + const b = integer & 0xFF; + + return [r, g, b]; +}; + +convert.rgb.hcg = function (rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = (max - min); + let grayscale; + let hue; + + if (chroma < 1) { + grayscale = min / (1 - chroma); + } else { + grayscale = 0; + } + + if (chroma <= 0) { + hue = 0; + } else + if (max === r) { + hue = ((g - b) / chroma) % 6; + } else + if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + + hue /= 6; + hue %= 1; + + return [hue * 360, chroma * 100, grayscale * 100]; +}; + +convert.hsl.hcg = function (hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + + const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + + let f = 0; + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; +}; + +convert.hsv.hcg = function (hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + + const c = s * v; + let f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; +}; + +convert.hcg.rgb = function (hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + const pure = [0, 0, 0]; + const hi = (h % 1) * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + + /* eslint-disable max-statements-per-line */ + switch (Math.floor(hi)) { + case 0: + pure[0] = 1; pure[1] = v; pure[2] = 0; break; + case 1: + pure[0] = w; pure[1] = 1; pure[2] = 0; break; + case 2: + pure[0] = 0; pure[1] = 1; pure[2] = v; break; + case 3: + pure[0] = 0; pure[1] = w; pure[2] = 1; break; + case 4: + pure[0] = v; pure[1] = 0; pure[2] = 1; break; + default: + pure[0] = 1; pure[1] = 0; pure[2] = w; + } + /* eslint-enable max-statements-per-line */ + + mg = (1.0 - c) * g; + + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; + +convert.hcg.hsv = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const v = c + g * (1.0 - c); + let f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; +}; + +convert.hcg.hsl = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + + const l = g * (1.0 - c) + 0.5 * c; + let s = 0; + + if (l > 0.0 && l < 0.5) { + s = c / (2 * l); + } else + if (l >= 0.5 && l < 1.0) { + s = c / (2 * (1 - l)); + } + + return [hcg[0], s * 100, l * 100]; +}; + +convert.hcg.hwb = function (hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; + +convert.hwb.hcg = function (hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + + if (c < 1) { + g = (v - c) / (1 - c); + } + + return [hwb[0], c * 100, g * 100]; +}; + +convert.apple.rgb = function (apple) { + return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; +}; + +convert.rgb.apple = function (rgb) { + return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; +}; + +convert.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert.gray.hsl = function (args) { + return [0, 0, args[0]]; +}; + +convert.gray.hsv = convert.gray.hsl; + +convert.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert.gray.hex = function (gray) { + const val = Math.round(gray[0] / 100 * 255) & 0xFF; + const integer = (val << 16) + (val << 8) + val; + + const string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; +}; + +convert.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; diff --git a/node_modules/color-convert/index.js b/node_modules/color-convert/index.js new file mode 100644 index 0000000..b648e57 --- /dev/null +++ b/node_modules/color-convert/index.js @@ -0,0 +1,81 @@ +const conversions = require('./conversions'); +const route = require('./route'); + +const convert = {}; + +const models = Object.keys(conversions); + +function wrapRaw(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + return fn(args); + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + const wrappedFn = function (...args) { + const arg0 = args[0]; + + if (arg0 === undefined || arg0 === null) { + return arg0; + } + + if (arg0.length > 1) { + args = arg0; + } + + const result = fn(args); + + // We're assuming the result is an array here. + // see notice in conversions.js; don't use box types + // in conversion functions. + if (typeof result === 'object') { + for (let len = result.length, i = 0; i < len; i++) { + result[i] = Math.round(result[i]); + } + } + + return result; + }; + + // Preserve .conversion property if there is one + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +models.forEach(fromModel => { + convert[fromModel] = {}; + + Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); + Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + + const routes = route(fromModel); + const routeModels = Object.keys(routes); + + routeModels.forEach(toModel => { + const fn = routes[toModel]; + + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); + +module.exports = convert; diff --git a/node_modules/color-convert/package.json b/node_modules/color-convert/package.json new file mode 100644 index 0000000..6e48000 --- /dev/null +++ b/node_modules/color-convert/package.json @@ -0,0 +1,48 @@ +{ + "name": "color-convert", + "description": "Plain color conversion functions", + "version": "2.0.1", + "author": "Heather Arthur ", + "license": "MIT", + "repository": "Qix-/color-convert", + "scripts": { + "pretest": "xo", + "test": "node test/basic.js" + }, + "engines": { + "node": ">=7.0.0" + }, + "keywords": [ + "color", + "colour", + "convert", + "converter", + "conversion", + "rgb", + "hsl", + "hsv", + "hwb", + "cmyk", + "ansi", + "ansi16" + ], + "files": [ + "index.js", + "conversions.js", + "route.js" + ], + "xo": { + "rules": { + "default-case": 0, + "no-inline-comments": 0, + "operator-linebreak": 0 + } + }, + "devDependencies": { + "chalk": "^2.4.2", + "xo": "^0.24.0" + }, + "dependencies": { + "color-name": "~1.1.4" + } +} diff --git a/node_modules/color-convert/route.js b/node_modules/color-convert/route.js new file mode 100644 index 0000000..1a08521 --- /dev/null +++ b/node_modules/color-convert/route.js @@ -0,0 +1,97 @@ +const conversions = require('./conversions'); + +/* + This function routes a model to all other models. + + all functions that are routed have a property `.conversion` attached + to the returned synthetic function. This property is an array + of strings, each with the steps in between the 'from' and 'to' + color models (inclusive). + + conversions that are not possible simply are not included. +*/ + +function buildGraph() { + const graph = {}; + // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + const models = Object.keys(conversions); + + for (let len = models.length, i = 0; i < len; i++) { + graph[models[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + + return graph; +} + +// https://en.wikipedia.org/wiki/Breadth-first_search +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions[current]); + + for (let len = adjacents.length, i = 0; i < len; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions[graph[toModel].parent][toModel]; + + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +module.exports = function (fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + + const models = Object.keys(graph); + for (let len = models.length, i = 0; i < len; i++) { + const toModel = models[i]; + const node = graph[toModel]; + + if (node.parent === null) { + // No possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion(toModel, graph); + } + + return conversion; +}; + diff --git a/node_modules/color-name/LICENSE b/node_modules/color-name/LICENSE new file mode 100644 index 0000000..4d9802a --- /dev/null +++ b/node_modules/color-name/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +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/node_modules/color-name/README.md b/node_modules/color-name/README.md new file mode 100644 index 0000000..3611a6b --- /dev/null +++ b/node_modules/color-name/README.md @@ -0,0 +1,11 @@ +A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. + +[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) + + +```js +var colors = require('color-name'); +colors.red //[255,0,0] +``` + + diff --git a/node_modules/color-name/index.js b/node_modules/color-name/index.js new file mode 100644 index 0000000..e42aa68 --- /dev/null +++ b/node_modules/color-name/index.js @@ -0,0 +1,152 @@ +'use strict' + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; diff --git a/node_modules/color-name/package.json b/node_modules/color-name/package.json new file mode 100644 index 0000000..7acc902 --- /dev/null +++ b/node_modules/color-name/package.json @@ -0,0 +1,28 @@ +{ + "name": "color-name", + "version": "1.1.4", + "description": "A list of color names and its values", + "main": "index.js", + "files": [ + "index.js" + ], + "scripts": { + "test": "node test.js" + }, + "repository": { + "type": "git", + "url": "git@github.com:colorjs/color-name.git" + }, + "keywords": [ + "color-name", + "color", + "color-keyword", + "keyword" + ], + "author": "DY ", + "license": "MIT", + "bugs": { + "url": "https://github.com/colorjs/color-name/issues" + }, + "homepage": "https://github.com/colorjs/color-name" +} diff --git a/node_modules/decamelize/index.js b/node_modules/decamelize/index.js new file mode 100644 index 0000000..8d5bab7 --- /dev/null +++ b/node_modules/decamelize/index.js @@ -0,0 +1,13 @@ +'use strict'; +module.exports = function (str, sep) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + sep = typeof sep === 'undefined' ? '_' : sep; + + return str + .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') + .toLowerCase(); +}; diff --git a/node_modules/decamelize/license b/node_modules/decamelize/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/decamelize/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/decamelize/package.json b/node_modules/decamelize/package.json new file mode 100644 index 0000000..ca35790 --- /dev/null +++ b/node_modules/decamelize/package.json @@ -0,0 +1,38 @@ +{ + "name": "decamelize", + "version": "1.2.0", + "description": "Convert a camelized string into a lowercased one with a custom separator: unicornRainbow → unicorn_rainbow", + "license": "MIT", + "repository": "sindresorhus/decamelize", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "xo && ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "decamelize", + "decamelcase", + "camelcase", + "lowercase", + "case", + "dash", + "hyphen", + "string", + "str", + "text", + "convert" + ], + "devDependencies": { + "ava": "*", + "xo": "*" + } +} diff --git a/node_modules/decamelize/readme.md b/node_modules/decamelize/readme.md new file mode 100644 index 0000000..624c7ee --- /dev/null +++ b/node_modules/decamelize/readme.md @@ -0,0 +1,48 @@ +# decamelize [![Build Status](https://travis-ci.org/sindresorhus/decamelize.svg?branch=master)](https://travis-ci.org/sindresorhus/decamelize) + +> Convert a camelized string into a lowercased one with a custom separator
+> Example: `unicornRainbow` → `unicorn_rainbow` + + +## Install + +``` +$ npm install --save decamelize +``` + + +## Usage + +```js +const decamelize = require('decamelize'); + +decamelize('unicornRainbow'); +//=> 'unicorn_rainbow' + +decamelize('unicornRainbow', '-'); +//=> 'unicorn-rainbow' +``` + + +## API + +### decamelize(input, [separator]) + +#### input + +Type: `string` + +#### separator + +Type: `string`
+Default: `_` + + +## Related + +See [`camelcase`](https://github.com/sindresorhus/camelcase) for the inverse. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/dijkstrajs/.travis.yml b/node_modules/dijkstrajs/.travis.yml new file mode 100644 index 0000000..2d63faf --- /dev/null +++ b/node_modules/dijkstrajs/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "stable" +sudo: false diff --git a/node_modules/dijkstrajs/CONTRIBUTING.md b/node_modules/dijkstrajs/CONTRIBUTING.md new file mode 100644 index 0000000..5f25961 --- /dev/null +++ b/node_modules/dijkstrajs/CONTRIBUTING.md @@ -0,0 +1,8 @@ +Contributing +============ + +1. Fork it +2. Create your feature branch (`git checkout -b my-new-feature`) +3. Commit your changes (`git commit -am 'Add some feature'`) +4. Push to the branch (`git push origin my-new-feature`) +5. Create new Pull Request diff --git a/node_modules/dijkstrajs/LICENSE.md b/node_modules/dijkstrajs/LICENSE.md new file mode 100644 index 0000000..b662d80 --- /dev/null +++ b/node_modules/dijkstrajs/LICENSE.md @@ -0,0 +1,19 @@ +``` +Dijkstra path-finding functions. Adapted from the Dijkstar Python project. + +Copyright (C) 2008 + Wyatt Baldwin + All rights reserved + +Licensed under the MIT license. + + http://www.opensource.org/licenses/mit-license.php + +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/node_modules/dijkstrajs/README.md b/node_modules/dijkstrajs/README.md new file mode 100644 index 0000000..77deac7 --- /dev/null +++ b/node_modules/dijkstrajs/README.md @@ -0,0 +1,18 @@ +# dijkstrajs.js + +dijkstrajs is a simple JavaScript implementation of Dijkstra's single-source shortest-paths algorithm. + +The code was originally written by Wyatt Baldwin and turned into a node module by Thomas Cort. + +## Requirements + +* [nodejs](http://nodejs.org/) + +## Installation + + npm install dijkstrajs + +## Examples + +See `test/dijkstra.test.js` in the sources for some example code. + diff --git a/node_modules/dijkstrajs/dijkstra.js b/node_modules/dijkstrajs/dijkstra.js new file mode 100644 index 0000000..4f83f1f --- /dev/null +++ b/node_modules/dijkstrajs/dijkstra.js @@ -0,0 +1,165 @@ +'use strict'; + +/****************************************************************************** + * Created 2008-08-19. + * + * Dijkstra path-finding functions. Adapted from the Dijkstar Python project. + * + * Copyright (C) 2008 + * Wyatt Baldwin + * All rights reserved + * + * Licensed under the MIT license. + * + * http://www.opensource.org/licenses/mit-license.php + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + *****************************************************************************/ +var dijkstra = { + single_source_shortest_paths: function(graph, s, d) { + // Predecessor map for each node that has been encountered. + // node ID => predecessor node ID + var predecessors = {}; + + // Costs of shortest paths from s to all nodes encountered. + // node ID => cost + var costs = {}; + costs[s] = 0; + + // Costs of shortest paths from s to all nodes encountered; differs from + // `costs` in that it provides easy access to the node that currently has + // the known shortest path from s. + // XXX: Do we actually need both `costs` and `open`? + var open = dijkstra.PriorityQueue.make(); + open.push(s, 0); + + var closest, + u, v, + cost_of_s_to_u, + adjacent_nodes, + cost_of_e, + cost_of_s_to_u_plus_cost_of_e, + cost_of_s_to_v, + first_visit; + while (!open.empty()) { + // In the nodes remaining in graph that have a known cost from s, + // find the node, u, that currently has the shortest path from s. + closest = open.pop(); + u = closest.value; + cost_of_s_to_u = closest.cost; + + // Get nodes adjacent to u... + adjacent_nodes = graph[u] || {}; + + // ...and explore the edges that connect u to those nodes, updating + // the cost of the shortest paths to any or all of those nodes as + // necessary. v is the node across the current edge from u. + for (v in adjacent_nodes) { + if (adjacent_nodes.hasOwnProperty(v)) { + // Get the cost of the edge running from u to v. + cost_of_e = adjacent_nodes[v]; + + // Cost of s to u plus the cost of u to v across e--this is *a* + // cost from s to v that may or may not be less than the current + // known cost to v. + cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; + + // If we haven't visited v yet OR if the current known cost from s to + // v is greater than the new cost we just found (cost of s to u plus + // cost of u to v across e), update v's cost in the cost list and + // update v's predecessor in the predecessor list (it's now u). + cost_of_s_to_v = costs[v]; + first_visit = (typeof costs[v] === 'undefined'); + if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { + costs[v] = cost_of_s_to_u_plus_cost_of_e; + open.push(v, cost_of_s_to_u_plus_cost_of_e); + predecessors[v] = u; + } + } + } + } + + if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') { + var msg = ['Could not find a path from ', s, ' to ', d, '.'].join(''); + throw new Error(msg); + } + + return predecessors; + }, + + extract_shortest_path_from_predecessor_list: function(predecessors, d) { + var nodes = []; + var u = d; + var predecessor; + while (u) { + nodes.push(u); + predecessor = predecessors[u]; + u = predecessors[u]; + } + nodes.reverse(); + return nodes; + }, + + find_path: function(graph, s, d) { + var predecessors = dijkstra.single_source_shortest_paths(graph, s, d); + return dijkstra.extract_shortest_path_from_predecessor_list( + predecessors, d); + }, + + /** + * A very naive priority queue implementation. + */ + PriorityQueue: { + make: function (opts) { + var T = dijkstra.PriorityQueue, + t = {}, + key; + opts = opts || {}; + for (key in T) { + if (T.hasOwnProperty(key)) { + t[key] = T[key]; + } + } + t.queue = []; + t.sorter = opts.sorter || T.default_sorter; + return t; + }, + + default_sorter: function (a, b) { + return a.cost - b.cost; + }, + + /** + * Add a new item to the queue and ensure the highest priority element + * is at the front of the queue. + */ + push: function (value, cost) { + var item = {value: value, cost: cost}; + this.queue.push(item); + this.queue.sort(this.sorter); + }, + + /** + * Return the highest priority element in the queue. + */ + pop: function () { + return this.queue.shift(); + }, + + empty: function () { + return this.queue.length === 0; + } + } +}; + + +// node.js module exports +if (typeof module !== 'undefined') { + module.exports = dijkstra; +} diff --git a/node_modules/dijkstrajs/package.json b/node_modules/dijkstrajs/package.json new file mode 100644 index 0000000..67cd76d --- /dev/null +++ b/node_modules/dijkstrajs/package.json @@ -0,0 +1,60 @@ +{ + "name": "dijkstrajs", + "version": "1.0.3", + "description": "A simple JavaScript implementation of Dijkstra's single-source shortest-paths algorithm.", + "main": "dijkstra.js", + "scripts": { + "pretest": "jshint dijkstra.js", + "test": "mocha -R spec" + }, + "repository": { + "type": "git", + "url": "git://github.com/tcort/dijkstrajs" + }, + "keywords": [ + "dijkstra", + "shortest", + "path", + "search", + "graph" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/tcort/dijkstrajs/issues" + }, + "homepage": "https://github.com/tcort/dijkstrajs", + "devDependencies": { + "expect.js": "^0.3.1", + "jshint": "^2.13.6", + "mocha": "^10.2.0" + }, + "jshintConfig": { + "bitwise": true, + "curly": true, + "eqeqeq": true, + "forin": true, + "freeze": true, + "globalstrict": true, + "immed": true, + "indent": 4, + "moz": true, + "newcap": true, + "noarg": true, + "node": true, + "noempty": true, + "nonew": true, + "trailing": true, + "undef": true, + "smarttabs": true, + "strict": true, + "validthis": true, + "globals": { + "describe": false, + "it": false, + "before": false, + "beforeEach": false, + "after": false, + "afterEach": false + } + } +} diff --git a/node_modules/dijkstrajs/test/dijkstra.test.js b/node_modules/dijkstrajs/test/dijkstra.test.js new file mode 100644 index 0000000..865c5a0 --- /dev/null +++ b/node_modules/dijkstrajs/test/dijkstra.test.js @@ -0,0 +1,96 @@ +'use strict'; + +var expect = require('expect.js'); +var dijkstra = require('../dijkstra.js'); +var find_path = dijkstra.find_path; + +describe('dijkstra.js', function () { + + describe('.find_path()', function () { + + it('should find the path between two points, all edges have weight 1', function () { + // A B C + // D E F + // G H I + var graph = { + a: {b: 10, d: 1}, + b: {a: 1, c: 1, e: 1}, + c: {b: 1, f: 1}, + d: {a: 1, e: 1, g: 1}, + e: {b: 1, d: 1, f: 1, h: 1}, + f: {c: 1, e: 1, i: 1}, + g: {d: 1, h: 1}, + h: {e: 1, g: 1, i: 1}, + i: {f: 1, h: 1} + }; + var path = find_path(graph, 'a', 'i'); + expect(path).to.eql(['a', 'd', 'e', 'f', 'i']); + }); + + it('should find the path between two points, weighted edges', function () { + var graph = { + a: {b: 10, c: 100, d: 1}, + b: {c: 10}, + d: {b: 1, e: 1}, + e: {f: 1}, + f: {c: 1}, + g: {b: 1} + }; + + var path = find_path(graph, 'a', 'c'); + expect(path).to.eql(['a', 'd', 'e', 'f', 'c']); + path = find_path(graph, 'd', 'b'); + expect(path).to.eql(['d', 'b']); + }); + + it('should throw on unreachable destination', function () { + var graph = { + a: {b: 10, c: 100, d: 1}, + b: {c: 10}, + d: {b: 1, e: 1}, + e: {f: 1}, + f: {c: 1}, + g: {b: 1} + }; + + expect(function () { find_path(graph, 'c', 'a'); }).to.throwException(); + expect(function () { find_path(graph, 'a', 'g'); }).to.throwException(); + }); + + it('should throw on non-existent destination', function () { + var graph = { + a: {b: 10, c: 100, d: 1}, + b: {c: 10}, + d: {b: 1, e: 1}, + e: {f: 1}, + f: {c: 1}, + g: {b: 1} + }; + + expect(function () { find_path(graph, 'a', 'z'); }).to.throwException(); + }); + }); + + describe('.single_source_shortest_paths()', function () { + it('should find all paths from a node', function () { + var graph = { + a: {b: 10, c: 100, d: 1}, + b: {c: 10}, + d: {b: 1, e: 1}, + e: {f: 1}, + f: {c: 1}, + g: {b: 1} + }; + + // All paths from 'a' + var paths = dijkstra.single_source_shortest_paths(graph, 'a'); + expect(paths).to.eql({ + d: 'a', + b: 'd', + e: 'd', + f: 'e', + c: 'f' + }); + }); + }); +}); diff --git a/node_modules/emoji-regex/LICENSE-MIT.txt b/node_modules/emoji-regex/LICENSE-MIT.txt new file mode 100644 index 0000000..a41e0a7 --- /dev/null +++ b/node_modules/emoji-regex/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/node_modules/emoji-regex/README.md b/node_modules/emoji-regex/README.md new file mode 100644 index 0000000..f10e173 --- /dev/null +++ b/node_modules/emoji-regex/README.md @@ -0,0 +1,73 @@ +# emoji-regex [![Build status](https://travis-ci.org/mathiasbynens/emoji-regex.svg?branch=master)](https://travis-ci.org/mathiasbynens/emoji-regex) + +_emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard. + +This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard. + +## Installation + +Via [npm](https://www.npmjs.com/): + +```bash +npm install emoji-regex +``` + +In [Node.js](https://nodejs.org/): + +```js +const emojiRegex = require('emoji-regex'); +// Note: because the regular expression has the global flag set, this module +// exports a function that returns the regex rather than exporting the regular +// expression itself, to make it impossible to (accidentally) mutate the +// original regular expression. + +const text = ` +\u{231A}: ⌚ default emoji presentation character (Emoji_Presentation) +\u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji +\u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base) +\u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier +`; + +const regex = emojiRegex(); +let match; +while (match = regex.exec(text)) { + const emoji = match[0]; + console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`); +} +``` + +Console output: + +``` +Matched sequence ⌚ — code points: 1 +Matched sequence ⌚ — code points: 1 +Matched sequence ↔️ — code points: 2 +Matched sequence ↔️ — code points: 2 +Matched sequence 👩 — code points: 1 +Matched sequence 👩 — code points: 1 +Matched sequence 👩🏿 — code points: 2 +Matched sequence 👩🏿 — code points: 2 +``` + +To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex: + +```js +const emojiRegex = require('emoji-regex/text.js'); +``` + +Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes: + +```js +const emojiRegex = require('emoji-regex/es2015/index.js'); +const emojiRegexText = require('emoji-regex/es2015/text.js'); +``` + +## Author + +| [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | +|---| +| [Mathias Bynens](https://mathiasbynens.be/) | + +## License + +_emoji-regex_ is available under the [MIT](https://mths.be/mit) license. diff --git a/node_modules/emoji-regex/es2015/index.js b/node_modules/emoji-regex/es2015/index.js new file mode 100644 index 0000000..b4cf3dc --- /dev/null +++ b/node_modules/emoji-regex/es2015/index.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{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u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; +}; diff --git a/node_modules/emoji-regex/es2015/text.js b/node_modules/emoji-regex/es2015/text.js new file mode 100644 index 0000000..780309d --- /dev/null +++ b/node_modules/emoji-regex/es2015/text.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = () => { + // https://mths.be/emoji + return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u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\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu; +}; diff --git a/node_modules/emoji-regex/index.d.ts b/node_modules/emoji-regex/index.d.ts new file mode 100644 index 0000000..1955b47 --- /dev/null +++ b/node_modules/emoji-regex/index.d.ts @@ -0,0 +1,23 @@ +declare module 'emoji-regex' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/text' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/es2015' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} + +declare module 'emoji-regex/es2015/text' { + function emojiRegex(): RegExp; + + export default emojiRegex; +} diff --git a/node_modules/emoji-regex/index.js b/node_modules/emoji-regex/index.js new file mode 100644 index 0000000..d993a3a --- /dev/null +++ b/node_modules/emoji-regex/index.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDD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DC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; diff --git a/node_modules/emoji-regex/package.json b/node_modules/emoji-regex/package.json new file mode 100644 index 0000000..6d32352 --- /dev/null +++ b/node_modules/emoji-regex/package.json @@ -0,0 +1,50 @@ +{ + "name": "emoji-regex", + "version": "8.0.0", + "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.", + "homepage": "https://mths.be/emoji-regex", + "main": "index.js", + "types": "index.d.ts", + "keywords": [ + "unicode", + "regex", + "regexp", + "regular expressions", + "code points", + "symbols", + "characters", + "emoji" + ], + "license": "MIT", + "author": { + "name": "Mathias Bynens", + "url": "https://mathiasbynens.be/" + }, + "repository": { + "type": "git", + "url": "https://github.com/mathiasbynens/emoji-regex.git" + }, + "bugs": "https://github.com/mathiasbynens/emoji-regex/issues", + "files": [ + "LICENSE-MIT.txt", + "index.js", + "index.d.ts", + "text.js", + "es2015/index.js", + "es2015/text.js" + ], + "scripts": { + "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js", + "test": "mocha", + "test:watch": "npm run test -- --watch" + }, + "devDependencies": { + "@babel/cli": "^7.2.3", + "@babel/core": "^7.3.4", + "@babel/plugin-proposal-unicode-property-regex": "^7.2.0", + "@babel/preset-env": "^7.3.4", + "mocha": "^6.0.2", + "regexgen": "^1.3.0", + "unicode-12.0.0": "^0.7.9" + } +} diff --git a/node_modules/emoji-regex/text.js b/node_modules/emoji-regex/text.js new file mode 100644 index 0000000..0a55ce2 --- /dev/null +++ b/node_modules/emoji-regex/text.js @@ -0,0 +1,6 @@ +"use strict"; + +module.exports = function () { + // https://mths.be/emoji + return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uD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C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +}; diff --git a/node_modules/find-up/index.d.ts b/node_modules/find-up/index.d.ts new file mode 100644 index 0000000..41e3192 --- /dev/null +++ b/node_modules/find-up/index.d.ts @@ -0,0 +1,137 @@ +import {Options as LocatePathOptions} from 'locate-path'; + +declare const stop: unique symbol; + +declare namespace findUp { + interface Options extends LocatePathOptions {} + + type StopSymbol = typeof stop; + + type Match = string | StopSymbol | undefined; +} + +declare const findUp: { + /** + Find a file or directory by walking up parent directories. + + @param name - Name of the file or directory to find. Can be multiple. + @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. + + @example + ``` + // / + // └── Users + // └── sindresorhus + // ├── unicorn.png + // └── foo + // └── bar + // ├── baz + // └── example.js + + // example.js + import findUp = require('find-up'); + + (async () => { + console.log(await findUp('unicorn.png')); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(['rainbow.png', 'unicorn.png'])); + //=> '/Users/sindresorhus/unicorn.png' + })(); + ``` + */ + (name: string | string[], options?: findUp.Options): Promise; + + /** + Find a file or directory by walking up parent directories. + + @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. + @returns The first path found or `undefined` if none could be found. + + @example + ``` + import path = require('path'); + import findUp = require('find-up'); + + (async () => { + console.log(await findUp(async directory => { + const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' + })(); + ``` + */ + (matcher: (directory: string) => (findUp.Match | Promise), options?: findUp.Options): Promise; + + sync: { + /** + Synchronously find a file or directory by walking up parent directories. + + @param name - Name of the file or directory to find. Can be multiple. + @returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found. + */ + (name: string | string[], options?: findUp.Options): string | undefined; + + /** + Synchronously find a file or directory by walking up parent directories. + + @param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search. + @returns The first path found or `undefined` if none could be found. + + @example + ``` + import path = require('path'); + import findUp = require('find-up'); + + console.log(findUp.sync(directory => { + const hasUnicorns = findUp.sync.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' + ``` + */ + (matcher: (directory: string) => findUp.Match, options?: findUp.Options): string | undefined; + + /** + Synchronously check if a path exists. + + @param path - Path to the file or directory. + @returns Whether the path exists. + + @example + ``` + import findUp = require('find-up'); + + console.log(findUp.sync.exists('/Users/sindresorhus/unicorn.png')); + //=> true + ``` + */ + exists(path: string): boolean; + } + + /** + Check if a path exists. + + @param path - Path to a file or directory. + @returns Whether the path exists. + + @example + ``` + import findUp = require('find-up'); + + (async () => { + console.log(await findUp.exists('/Users/sindresorhus/unicorn.png')); + //=> true + })(); + ``` + */ + exists(path: string): Promise; + + /** + Return this in a `matcher` function to stop the search and force `findUp` to immediately return `undefined`. + */ + readonly stop: findUp.StopSymbol; +}; + +export = findUp; diff --git a/node_modules/find-up/index.js b/node_modules/find-up/index.js new file mode 100644 index 0000000..ce564e5 --- /dev/null +++ b/node_modules/find-up/index.js @@ -0,0 +1,89 @@ +'use strict'; +const path = require('path'); +const locatePath = require('locate-path'); +const pathExists = require('path-exists'); + +const stop = Symbol('findUp.stop'); + +module.exports = async (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = async locateOptions => { + if (typeof name !== 'function') { + return locatePath(paths, locateOptions); + } + + const foundPath = await name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + // eslint-disable-next-line no-await-in-loop + const foundPath = await runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } +}; + +module.exports.sync = (name, options = {}) => { + let directory = path.resolve(options.cwd || ''); + const {root} = path.parse(directory); + const paths = [].concat(name); + + const runMatcher = locateOptions => { + if (typeof name !== 'function') { + return locatePath.sync(paths, locateOptions); + } + + const foundPath = name(locateOptions.cwd); + if (typeof foundPath === 'string') { + return locatePath.sync([foundPath], locateOptions); + } + + return foundPath; + }; + + // eslint-disable-next-line no-constant-condition + while (true) { + const foundPath = runMatcher({...options, cwd: directory}); + + if (foundPath === stop) { + return; + } + + if (foundPath) { + return path.resolve(directory, foundPath); + } + + if (directory === root) { + return; + } + + directory = path.dirname(directory); + } +}; + +module.exports.exists = pathExists; + +module.exports.sync.exists = pathExists.sync; + +module.exports.stop = stop; diff --git a/node_modules/find-up/license b/node_modules/find-up/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/find-up/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/find-up/package.json b/node_modules/find-up/package.json new file mode 100644 index 0000000..cd50281 --- /dev/null +++ b/node_modules/find-up/package.json @@ -0,0 +1,53 @@ +{ + "name": "find-up", + "version": "4.1.0", + "description": "Find a file or directory by walking up parent directories", + "license": "MIT", + "repository": "sindresorhus/find-up", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "find", + "up", + "find-up", + "findup", + "look-up", + "look", + "file", + "search", + "match", + "package", + "resolve", + "parent", + "parents", + "folder", + "directory", + "walk", + "walking", + "path" + ], + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "devDependencies": { + "ava": "^2.1.0", + "is-path-inside": "^2.1.0", + "tempy": "^0.3.0", + "tsd": "^0.7.3", + "xo": "^0.24.0" + } +} diff --git a/node_modules/find-up/readme.md b/node_modules/find-up/readme.md new file mode 100644 index 0000000..d6a21e5 --- /dev/null +++ b/node_modules/find-up/readme.md @@ -0,0 +1,156 @@ +# find-up [![Build Status](https://travis-ci.org/sindresorhus/find-up.svg?branch=master)](https://travis-ci.org/sindresorhus/find-up) + +> Find a file or directory by walking up parent directories + + +## Install + +``` +$ npm install find-up +``` + + +## Usage + +``` +/ +└── Users + └── sindresorhus + ├── unicorn.png + └── foo + └── bar + ├── baz + └── example.js +``` + +`example.js` + +```js +const path = require('path'); +const findUp = require('find-up'); + +(async () => { + console.log(await findUp('unicorn.png')); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(['rainbow.png', 'unicorn.png'])); + //=> '/Users/sindresorhus/unicorn.png' + + console.log(await findUp(async directory => { + const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png')); + return hasUnicorns && directory; + }, {type: 'directory'})); + //=> '/Users/sindresorhus' +})(); +``` + + +## API + +### findUp(name, options?) +### findUp(matcher, options?) + +Returns a `Promise` for either the path or `undefined` if it couldn't be found. + +### findUp([...name], options?) + +Returns a `Promise` for either the first path found (by respecting the order of the array) or `undefined` if none could be found. + +### findUp.sync(name, options?) +### findUp.sync(matcher, options?) + +Returns a path or `undefined` if it couldn't be found. + +### findUp.sync([...name], options?) + +Returns the first path found (by respecting the order of the array) or `undefined` if none could be found. + +#### name + +Type: `string` + +Name of the file or directory to find. + +#### matcher + +Type: `Function` + +A function that will be called with each directory until it returns a `string` with the path, which stops the search, or the root directory has been reached and nothing was found. Useful if you want to match files with certain patterns, set of permissions, or other advanced use-cases. + +When using async mode, the `matcher` may optionally be an async or promise-returning function that returns the path. + +#### options + +Type: `object` + +##### cwd + +Type: `string`
+Default: `process.cwd()` + +Directory to start from. + +##### type + +Type: `string`
+Default: `'file'`
+Values: `'file'` `'directory'` + +The type of paths that can match. + +##### allowSymlinks + +Type: `boolean`
+Default: `true` + +Allow symbolic links to match if they point to the chosen path type. + +### findUp.exists(path) + +Returns a `Promise` of whether the path exists. + +### findUp.sync.exists(path) + +Returns a `boolean` of whether the path exists. + +#### path + +Type: `string` + +Path to a file or directory. + +### findUp.stop + +A [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that can be returned by a `matcher` function to stop the search and cause `findUp` to immediately return `undefined`. Useful as a performance optimization in case the current working directory is deeply nested in the filesystem. + +```js +const path = require('path'); +const findUp = require('find-up'); + +(async () => { + await findUp(directory => { + return path.basename(directory) === 'work' ? findUp.stop : 'logo.png'; + }); +})(); +``` + + +## Related + +- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module +- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file +- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package +- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module like `require.resolve()` but from a given path + + +--- + +
+ + Get professional support for 'find-up' with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/get-caller-file/LICENSE.md b/node_modules/get-caller-file/LICENSE.md new file mode 100644 index 0000000..bf3e1c0 --- /dev/null +++ b/node_modules/get-caller-file/LICENSE.md @@ -0,0 +1,6 @@ +ISC License (ISC) +Copyright 2018 Stefan Penner + +Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/get-caller-file/README.md b/node_modules/get-caller-file/README.md new file mode 100644 index 0000000..a7d8c07 --- /dev/null +++ b/node_modules/get-caller-file/README.md @@ -0,0 +1,41 @@ +# get-caller-file + +[![Build Status](https://travis-ci.org/stefanpenner/get-caller-file.svg?branch=master)](https://travis-ci.org/stefanpenner/get-caller-file) +[![Build status](https://ci.appveyor.com/api/projects/status/ol2q94g1932cy14a/branch/master?svg=true)](https://ci.appveyor.com/project/embercli/get-caller-file/branch/master) + +This is a utility, which allows a function to figure out from which file it was invoked. It does so by inspecting v8's stack trace at the time it is invoked. + +Inspired by http://stackoverflow.com/questions/13227489 + +*note: this relies on Node/V8 specific APIs, as such other runtimes may not work* + +## Installation + +```bash +yarn add get-caller-file +``` + +## Usage + +Given: + +```js +// ./foo.js +const getCallerFile = require('get-caller-file'); + +module.exports = function() { + return getCallerFile(); // figures out who called it +}; +``` + +```js +// index.js +const foo = require('./foo'); + +foo() // => /full/path/to/this/file/index.js +``` + + +## Options: + +* `getCallerFile(position = 2)`: where position is stack frame whos fileName we want. diff --git a/node_modules/get-caller-file/index.d.ts b/node_modules/get-caller-file/index.d.ts new file mode 100644 index 0000000..babed69 --- /dev/null +++ b/node_modules/get-caller-file/index.d.ts @@ -0,0 +1,2 @@ +declare const _default: (position?: number) => any; +export = _default; diff --git a/node_modules/get-caller-file/index.js b/node_modules/get-caller-file/index.js new file mode 100644 index 0000000..57304f8 --- /dev/null +++ b/node_modules/get-caller-file/index.js @@ -0,0 +1,22 @@ +"use strict"; +// Call this function in a another function to find out the file from +// which that function was called from. (Inspects the v8 stack trace) +// +// Inspired by http://stackoverflow.com/questions/13227489 +module.exports = function getCallerFile(position) { + if (position === void 0) { position = 2; } + if (position >= Error.stackTraceLimit) { + throw new TypeError('getCallerFile(position) requires position be less then Error.stackTraceLimit but position was: `' + position + '` and Error.stackTraceLimit was: `' + Error.stackTraceLimit + '`'); + } + var oldPrepareStackTrace = Error.prepareStackTrace; + Error.prepareStackTrace = function (_, stack) { return stack; }; + var stack = new Error().stack; + Error.prepareStackTrace = oldPrepareStackTrace; + if (stack !== null && typeof stack === 'object') { + // stack[0] holds this file + // stack[1] holds where this function was called + // stack[2] holds the file we're interested in + return stack[position] ? stack[position].getFileName() : undefined; + } +}; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/get-caller-file/index.js.map b/node_modules/get-caller-file/index.js.map new file mode 100644 index 0000000..89c655c --- /dev/null +++ b/node_modules/get-caller-file/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA,qEAAqE;AACrE,qEAAqE;AACrE,EAAE;AACF,0DAA0D;AAE1D,iBAAS,SAAS,aAAa,CAAC,QAAY;IAAZ,yBAAA,EAAA,YAAY;IAC1C,IAAI,QAAQ,IAAI,KAAK,CAAC,eAAe,EAAE;QACrC,MAAM,IAAI,SAAS,CAAC,kGAAkG,GAAG,QAAQ,GAAG,oCAAoC,GAAG,KAAK,CAAC,eAAe,GAAG,GAAG,CAAC,CAAC;KACzM;IAED,IAAM,oBAAoB,GAAG,KAAK,CAAC,iBAAiB,CAAC;IACrD,KAAK,CAAC,iBAAiB,GAAG,UAAC,CAAC,EAAE,KAAK,IAAM,OAAA,KAAK,EAAL,CAAK,CAAC;IAC/C,IAAM,KAAK,GAAG,IAAI,KAAK,EAAE,CAAC,KAAK,CAAC;IAChC,KAAK,CAAC,iBAAiB,GAAG,oBAAoB,CAAC;IAG/C,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;QAC/C,2BAA2B;QAC3B,gDAAgD;QAChD,8CAA8C;QAC9C,OAAO,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAE,KAAK,CAAC,QAAQ,CAAS,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;KAC7E;AACH,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/get-caller-file/package.json b/node_modules/get-caller-file/package.json new file mode 100644 index 0000000..b0dd571 --- /dev/null +++ b/node_modules/get-caller-file/package.json @@ -0,0 +1,42 @@ +{ + "name": "get-caller-file", + "version": "2.0.5", + "description": "", + "main": "index.js", + "directories": { + "test": "tests" + }, + "files": [ + "index.js", + "index.js.map", + "index.d.ts" + ], + "scripts": { + "prepare": "tsc", + "test": "mocha test", + "test:debug": "mocha test" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/stefanpenner/get-caller-file.git" + }, + "author": "Stefan Penner", + "license": "ISC", + "bugs": { + "url": "https://github.com/stefanpenner/get-caller-file/issues" + }, + "homepage": "https://github.com/stefanpenner/get-caller-file#readme", + "devDependencies": { + "@types/chai": "^4.1.7", + "@types/ensure-posix-path": "^1.0.0", + "@types/mocha": "^5.2.6", + "@types/node": "^11.10.5", + "chai": "^4.1.2", + "ensure-posix-path": "^1.0.1", + "mocha": "^5.2.0", + "typescript": "^3.3.3333" + }, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } +} diff --git a/node_modules/is-fullwidth-code-point/index.d.ts b/node_modules/is-fullwidth-code-point/index.d.ts new file mode 100644 index 0000000..729d202 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/index.d.ts @@ -0,0 +1,17 @@ +/** +Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms). + +@param codePoint - The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. + +@example +``` +import isFullwidthCodePoint from 'is-fullwidth-code-point'; + +isFullwidthCodePoint('谢'.codePointAt(0)); +//=> true + +isFullwidthCodePoint('a'.codePointAt(0)); +//=> false +``` +*/ +export default function isFullwidthCodePoint(codePoint: number): boolean; diff --git a/node_modules/is-fullwidth-code-point/index.js b/node_modules/is-fullwidth-code-point/index.js new file mode 100644 index 0000000..671f97f --- /dev/null +++ b/node_modules/is-fullwidth-code-point/index.js @@ -0,0 +1,50 @@ +/* eslint-disable yoda */ +'use strict'; + +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { + return false; + } + + // Code points are derived from: + // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt + if ( + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET + // CJK Radicals Supplement .. Enclosed CJK Letters and Months + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || + // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A + (0x3250 <= codePoint && codePoint <= 0x4DBF) || + // CJK Unified Ideographs .. Yi Radicals + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || + // Hangul Jamo Extended-A + (0xA960 <= codePoint && codePoint <= 0xA97C) || + // Hangul Syllables + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || + // CJK Compatibility Ideographs + (0xF900 <= codePoint && codePoint <= 0xFAFF) || + // Vertical Forms + (0xFE10 <= codePoint && codePoint <= 0xFE19) || + // CJK Compatibility Forms .. Small Form Variants + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || + // Halfwidth and Fullwidth Forms + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || + // Kana Supplement + (0x1B000 <= codePoint && codePoint <= 0x1B001) || + // Enclosed Ideographic Supplement + (0x1F200 <= codePoint && codePoint <= 0x1F251) || + // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane + (0x20000 <= codePoint && codePoint <= 0x3FFFD) + ) + ) { + return true; + } + + return false; +}; + +module.exports = isFullwidthCodePoint; +module.exports.default = isFullwidthCodePoint; diff --git a/node_modules/is-fullwidth-code-point/license b/node_modules/is-fullwidth-code-point/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/is-fullwidth-code-point/package.json b/node_modules/is-fullwidth-code-point/package.json new file mode 100644 index 0000000..2137e88 --- /dev/null +++ b/node_modules/is-fullwidth-code-point/package.json @@ -0,0 +1,42 @@ +{ + "name": "is-fullwidth-code-point", + "version": "3.0.0", + "description": "Check if the character represented by a given Unicode code point is fullwidth", + "license": "MIT", + "repository": "sindresorhus/is-fullwidth-code-point", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "fullwidth", + "full-width", + "full", + "width", + "unicode", + "character", + "string", + "codepoint", + "code", + "point", + "is", + "detect", + "check" + ], + "devDependencies": { + "ava": "^1.3.1", + "tsd-check": "^0.5.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/is-fullwidth-code-point/readme.md b/node_modules/is-fullwidth-code-point/readme.md new file mode 100644 index 0000000..4236bba --- /dev/null +++ b/node_modules/is-fullwidth-code-point/readme.md @@ -0,0 +1,39 @@ +# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) + +> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) + + +## Install + +``` +$ npm install is-fullwidth-code-point +``` + + +## Usage + +```js +const isFullwidthCodePoint = require('is-fullwidth-code-point'); + +isFullwidthCodePoint('谢'.codePointAt(0)); +//=> true + +isFullwidthCodePoint('a'.codePointAt(0)); +//=> false +``` + + +## API + +### isFullwidthCodePoint(codePoint) + +#### codePoint + +Type: `number` + +The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/locate-path/index.d.ts b/node_modules/locate-path/index.d.ts new file mode 100644 index 0000000..fbde526 --- /dev/null +++ b/node_modules/locate-path/index.d.ts @@ -0,0 +1,83 @@ +declare namespace locatePath { + interface Options { + /** + Current working directory. + + @default process.cwd() + */ + readonly cwd?: string; + + /** + Type of path to match. + + @default 'file' + */ + readonly type?: 'file' | 'directory'; + + /** + Allow symbolic links to match if they point to the requested path type. + + @default true + */ + readonly allowSymlinks?: boolean; + } + + interface AsyncOptions extends Options { + /** + Number of concurrently pending promises. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `paths` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +declare const locatePath: { + /** + Get the first path that exists on disk of multiple paths. + + @param paths - Paths to check. + @returns The first path that exists or `undefined` if none exists. + + @example + ``` + import locatePath = require('locate-path'); + + const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' + ]; + + (async () => { + console(await locatePath(files)); + //=> 'rainbow' + })(); + ``` + */ + (paths: Iterable, options?: locatePath.AsyncOptions): Promise< + string | undefined + >; + + /** + Synchronously get the first path that exists on disk of multiple paths. + + @param paths - Paths to check. + @returns The first path that exists or `undefined` if none exists. + */ + sync( + paths: Iterable, + options?: locatePath.Options + ): string | undefined; +}; + +export = locatePath; diff --git a/node_modules/locate-path/index.js b/node_modules/locate-path/index.js new file mode 100644 index 0000000..4604bbf --- /dev/null +++ b/node_modules/locate-path/index.js @@ -0,0 +1,65 @@ +'use strict'; +const path = require('path'); +const fs = require('fs'); +const {promisify} = require('util'); +const pLocate = require('p-locate'); + +const fsStat = promisify(fs.stat); +const fsLStat = promisify(fs.lstat); + +const typeMappings = { + directory: 'isDirectory', + file: 'isFile' +}; + +function checkType({type}) { + if (type in typeMappings) { + return; + } + + throw new Error(`Invalid type specified: ${type}`); +} + +const matchType = (type, stat) => type === undefined || stat[typeMappings[type]](); + +module.exports = async (paths, options) => { + options = { + cwd: process.cwd(), + type: 'file', + allowSymlinks: true, + ...options + }; + checkType(options); + const statFn = options.allowSymlinks ? fsStat : fsLStat; + + return pLocate(paths, async path_ => { + try { + const stat = await statFn(path.resolve(options.cwd, path_)); + return matchType(options.type, stat); + } catch (_) { + return false; + } + }, options); +}; + +module.exports.sync = (paths, options) => { + options = { + cwd: process.cwd(), + allowSymlinks: true, + type: 'file', + ...options + }; + checkType(options); + const statFn = options.allowSymlinks ? fs.statSync : fs.lstatSync; + + for (const path_ of paths) { + try { + const stat = statFn(path.resolve(options.cwd, path_)); + + if (matchType(options.type, stat)) { + return path_; + } + } catch (_) { + } + } +}; diff --git a/node_modules/locate-path/license b/node_modules/locate-path/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/locate-path/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/locate-path/package.json b/node_modules/locate-path/package.json new file mode 100644 index 0000000..063b290 --- /dev/null +++ b/node_modules/locate-path/package.json @@ -0,0 +1,45 @@ +{ + "name": "locate-path", + "version": "5.0.0", + "description": "Get the first path that exists on disk of multiple paths", + "license": "MIT", + "repository": "sindresorhus/locate-path", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "locate", + "path", + "paths", + "file", + "files", + "exists", + "find", + "finder", + "search", + "searcher", + "array", + "iterable", + "iterator" + ], + "dependencies": { + "p-locate": "^4.1.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/locate-path/readme.md b/node_modules/locate-path/readme.md new file mode 100644 index 0000000..2184c6f --- /dev/null +++ b/node_modules/locate-path/readme.md @@ -0,0 +1,122 @@ +# locate-path [![Build Status](https://travis-ci.org/sindresorhus/locate-path.svg?branch=master)](https://travis-ci.org/sindresorhus/locate-path) + +> Get the first path that exists on disk of multiple paths + + +## Install + +``` +$ npm install locate-path +``` + + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const locatePath = require('locate-path'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + console(await locatePath(files)); + //=> 'rainbow' +})(); +``` + + +## API + +### locatePath(paths, [options]) + +Returns a `Promise` for the first path that exists or `undefined` if none exists. + +#### paths + +Type: `Iterable` + +Paths to check. + +#### options + +Type: `Object` + +##### concurrency + +Type: `number`
+Default: `Infinity`
+Minimum: `1` + +Number of concurrently pending promises. + +##### preserveOrder + +Type: `boolean`
+Default: `true` + +Preserve `paths` order when searching. + +Disable this to improve performance if you don't care about the order. + +##### cwd + +Type: `string`
+Default: `process.cwd()` + +Current working directory. + +##### type + +Type: `string`
+Default: `file`
+Values: `file` `directory` + +The type of paths that can match. + +##### allowSymlinks + +Type: `boolean`
+Default: `true` + +Allow symbolic links to match if they point to the chosen path type. + +### locatePath.sync(paths, [options]) + +Returns the first path that exists or `undefined` if none exists. + +#### paths + +Type: `Iterable` + +Paths to check. + +#### options + +Type: `Object` + +##### cwd + +Same as above. + +##### type + +Same as above. + +##### allowSymlinks + +Same as above. + + +## Related + +- [path-exists](https://github.com/sindresorhus/path-exists) - Check if a path exists + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/p-limit/index.d.ts b/node_modules/p-limit/index.d.ts new file mode 100644 index 0000000..6bbfad4 --- /dev/null +++ b/node_modules/p-limit/index.d.ts @@ -0,0 +1,38 @@ +export interface Limit { + /** + @param fn - Promise-returning/async function. + @param arguments - Any arguments to pass through to `fn`. Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a lot of functions. + @returns The promise returned by calling `fn(...arguments)`. + */ + ( + fn: (...arguments: Arguments) => PromiseLike | ReturnType, + ...arguments: Arguments + ): Promise; + + /** + The number of promises that are currently running. + */ + readonly activeCount: number; + + /** + The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + */ + readonly pendingCount: number; + + /** + Discard pending promises that are waiting to run. + + This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + + Note: This does not cancel promises that are already running. + */ + clearQueue(): void; +} + +/** +Run multiple promise-returning & async functions with limited concurrency. + +@param concurrency - Concurrency limit. Minimum: `1`. +@returns A `limit` function. +*/ +export default function pLimit(concurrency: number): Limit; diff --git a/node_modules/p-limit/index.js b/node_modules/p-limit/index.js new file mode 100644 index 0000000..6a72a4c --- /dev/null +++ b/node_modules/p-limit/index.js @@ -0,0 +1,57 @@ +'use strict'; +const pTry = require('p-try'); + +const pLimit = concurrency => { + if (!((Number.isInteger(concurrency) || concurrency === Infinity) && concurrency > 0)) { + return Promise.reject(new TypeError('Expected `concurrency` to be a number from 1 and up')); + } + + const queue = []; + let activeCount = 0; + + const next = () => { + activeCount--; + + if (queue.length > 0) { + queue.shift()(); + } + }; + + const run = (fn, resolve, ...args) => { + activeCount++; + + const result = pTry(fn, ...args); + + resolve(result); + + result.then(next, next); + }; + + const enqueue = (fn, resolve, ...args) => { + if (activeCount < concurrency) { + run(fn, resolve, ...args); + } else { + queue.push(run.bind(null, fn, resolve, ...args)); + } + }; + + const generator = (fn, ...args) => new Promise(resolve => enqueue(fn, resolve, ...args)); + Object.defineProperties(generator, { + activeCount: { + get: () => activeCount + }, + pendingCount: { + get: () => queue.length + }, + clearQueue: { + value: () => { + queue.length = 0; + } + } + }); + + return generator; +}; + +module.exports = pLimit; +module.exports.default = pLimit; diff --git a/node_modules/p-limit/license b/node_modules/p-limit/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/p-limit/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/p-limit/package.json b/node_modules/p-limit/package.json new file mode 100644 index 0000000..99a814f --- /dev/null +++ b/node_modules/p-limit/package.json @@ -0,0 +1,52 @@ +{ + "name": "p-limit", + "version": "2.3.0", + "description": "Run multiple promise-returning & async functions with limited concurrency", + "license": "MIT", + "repository": "sindresorhus/p-limit", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "limit", + "limited", + "concurrency", + "throttle", + "throat", + "rate", + "batch", + "ratelimit", + "task", + "queue", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-try": "^2.0.0" + }, + "devDependencies": { + "ava": "^1.2.1", + "delay": "^4.1.0", + "in-range": "^1.0.0", + "random-int": "^1.0.0", + "time-span": "^2.0.0", + "tsd-check": "^0.3.0", + "xo": "^0.24.0" + } +} diff --git a/node_modules/p-limit/readme.md b/node_modules/p-limit/readme.md new file mode 100644 index 0000000..64aa476 --- /dev/null +++ b/node_modules/p-limit/readme.md @@ -0,0 +1,101 @@ +# p-limit [![Build Status](https://travis-ci.org/sindresorhus/p-limit.svg?branch=master)](https://travis-ci.org/sindresorhus/p-limit) + +> Run multiple promise-returning & async functions with limited concurrency + +## Install + +``` +$ npm install p-limit +``` + +## Usage + +```js +const pLimit = require('p-limit'); + +const limit = pLimit(1); + +const input = [ + limit(() => fetchSomething('foo')), + limit(() => fetchSomething('bar')), + limit(() => doSomething()) +]; + +(async () => { + // Only one promise is run at once + const result = await Promise.all(input); + console.log(result); +})(); +``` + +## API + +### pLimit(concurrency) + +Returns a `limit` function. + +#### concurrency + +Type: `number`\ +Minimum: `1`\ +Default: `Infinity` + +Concurrency limit. + +### limit(fn, ...args) + +Returns the promise returned by calling `fn(...args)`. + +#### fn + +Type: `Function` + +Promise-returning/async function. + +#### args + +Any arguments to pass through to `fn`. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +### limit.activeCount + +The number of promises that are currently running. + +### limit.pendingCount + +The number of promises that are waiting to run (i.e. their internal `fn` was not called yet). + +### limit.clearQueue() + +Discard pending promises that are waiting to run. + +This might be useful if you want to teardown the queue at the end of your program's lifecycle or discard any function calls referencing an intermediary state of your app. + +Note: This does not cancel promises that are already running. + +## FAQ + +### How is this different from the [`p-queue`](https://github.com/sindresorhus/p-queue) package? + +This package is only about limiting the number of concurrent executions, while `p-queue` is a fully featured queue implementation with lots of different options, introspection, and ability to pause the queue. + +## Related + +- [p-queue](https://github.com/sindresorhus/p-queue) - Promise queue with concurrency control +- [p-throttle](https://github.com/sindresorhus/p-throttle) - Throttle promise-returning & async functions +- [p-debounce](https://github.com/sindresorhus/p-debounce) - Debounce promise-returning & async functions +- [p-all](https://github.com/sindresorhus/p-all) - Run promise-returning & async functions concurrently with optional limited concurrency +- [More…](https://github.com/sindresorhus/promise-fun) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/p-locate/index.d.ts b/node_modules/p-locate/index.d.ts new file mode 100644 index 0000000..14115e1 --- /dev/null +++ b/node_modules/p-locate/index.d.ts @@ -0,0 +1,64 @@ +declare namespace pLocate { + interface Options { + /** + Number of concurrently pending promises returned by `tester`. Minimum: `1`. + + @default Infinity + */ + readonly concurrency?: number; + + /** + Preserve `input` order when searching. + + Disable this to improve performance if you don't care about the order. + + @default true + */ + readonly preserveOrder?: boolean; + } +} + +declare const pLocate: { + /** + Get the first fulfilled promise that satisfies the provided testing function. + + @param input - An iterable of promises/values to test. + @param tester - This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + @returns A `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + + @example + ``` + import pathExists = require('path-exists'); + import pLocate = require('p-locate'); + + const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' + ]; + + (async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' + })(); + ``` + */ + ( + input: Iterable | ValueType>, + tester: (element: ValueType) => PromiseLike | boolean, + options?: pLocate.Options + ): Promise; + + // TODO: Remove this for the next major release, refactor the whole definition to: + // declare function pLocate( + // input: Iterable | ValueType>, + // tester: (element: ValueType) => PromiseLike | boolean, + // options?: pLocate.Options + // ): Promise; + // export = pLocate; + default: typeof pLocate; +}; + +export = pLocate; diff --git a/node_modules/p-locate/index.js b/node_modules/p-locate/index.js new file mode 100644 index 0000000..e13ce15 --- /dev/null +++ b/node_modules/p-locate/index.js @@ -0,0 +1,52 @@ +'use strict'; +const pLimit = require('p-limit'); + +class EndError extends Error { + constructor(value) { + super(); + this.value = value; + } +} + +// The input can also be a promise, so we await it +const testElement = async (element, tester) => tester(await element); + +// The input can also be a promise, so we `Promise.all()` them both +const finder = async element => { + const values = await Promise.all(element); + if (values[1] === true) { + throw new EndError(values[0]); + } + + return false; +}; + +const pLocate = async (iterable, tester, options) => { + options = { + concurrency: Infinity, + preserveOrder: true, + ...options + }; + + const limit = pLimit(options.concurrency); + + // Start all the promises concurrently with optional limit + const items = [...iterable].map(element => [element, limit(testElement, element, tester)]); + + // Check the promises either serially or concurrently + const checkLimit = pLimit(options.preserveOrder ? 1 : Infinity); + + try { + await Promise.all(items.map(element => checkLimit(finder, element))); + } catch (error) { + if (error instanceof EndError) { + return error.value; + } + + throw error; + } +}; + +module.exports = pLocate; +// TODO: Remove this for the next major release +module.exports.default = pLocate; diff --git a/node_modules/p-locate/license b/node_modules/p-locate/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/p-locate/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/p-locate/package.json b/node_modules/p-locate/package.json new file mode 100644 index 0000000..e3de275 --- /dev/null +++ b/node_modules/p-locate/package.json @@ -0,0 +1,53 @@ +{ + "name": "p-locate", + "version": "4.1.0", + "description": "Get the first fulfilled promise that satisfies the provided testing function", + "license": "MIT", + "repository": "sindresorhus/p-locate", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "locate", + "find", + "finder", + "search", + "searcher", + "test", + "array", + "collection", + "iterable", + "iterator", + "race", + "fulfilled", + "fastest", + "async", + "await", + "promises", + "bluebird" + ], + "dependencies": { + "p-limit": "^2.2.0" + }, + "devDependencies": { + "ava": "^1.4.1", + "delay": "^4.1.0", + "in-range": "^1.0.0", + "time-span": "^3.0.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/p-locate/readme.md b/node_modules/p-locate/readme.md new file mode 100644 index 0000000..f8e2c2e --- /dev/null +++ b/node_modules/p-locate/readme.md @@ -0,0 +1,90 @@ +# p-locate [![Build Status](https://travis-ci.org/sindresorhus/p-locate.svg?branch=master)](https://travis-ci.org/sindresorhus/p-locate) + +> Get the first fulfilled promise that satisfies the provided testing function + +Think of it like an async version of [`Array#find`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/find). + + +## Install + +``` +$ npm install p-locate +``` + + +## Usage + +Here we find the first file that exists on disk, in array order. + +```js +const pathExists = require('path-exists'); +const pLocate = require('p-locate'); + +const files = [ + 'unicorn.png', + 'rainbow.png', // Only this one actually exists on disk + 'pony.png' +]; + +(async () => { + const foundPath = await pLocate(files, file => pathExists(file)); + + console.log(foundPath); + //=> 'rainbow' +})(); +``` + +*The above is just an example. Use [`locate-path`](https://github.com/sindresorhus/locate-path) if you need this.* + + +## API + +### pLocate(input, tester, [options]) + +Returns a `Promise` that is fulfilled when `tester` resolves to `true` or the iterable is done, or rejects if any of the promises reject. The fulfilled value is the current iterable value or `undefined` if `tester` never resolved to `true`. + +#### input + +Type: `Iterable` + +An iterable of promises/values to test. + +#### tester(element) + +Type: `Function` + +This function will receive resolved values from `input` and is expected to return a `Promise` or `boolean`. + +#### options + +Type: `Object` + +##### concurrency + +Type: `number`
+Default: `Infinity`
+Minimum: `1` + +Number of concurrently pending promises returned by `tester`. + +##### preserveOrder + +Type: `boolean`
+Default: `true` + +Preserve `input` order when searching. + +Disable this to improve performance if you don't care about the order. + + +## Related + +- [p-map](https://github.com/sindresorhus/p-map) - Map over promises concurrently +- [p-filter](https://github.com/sindresorhus/p-filter) - Filter promises concurrently +- [p-any](https://github.com/sindresorhus/p-any) - Wait for any promise to be fulfilled +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/p-try/index.d.ts b/node_modules/p-try/index.d.ts new file mode 100644 index 0000000..2a7319e --- /dev/null +++ b/node_modules/p-try/index.d.ts @@ -0,0 +1,39 @@ +declare const pTry: { + /** + Start a promise chain. + + @param fn - The function to run to start the promise chain. + @param arguments - Arguments to pass to `fn`. + @returns The value of calling `fn(...arguments)`. If the function throws an error, the returned `Promise` will be rejected with that error. + + @example + ``` + import pTry = require('p-try'); + + (async () => { + try { + const value = await pTry(() => { + return synchronousFunctionThatMightThrow(); + }); + console.log(value); + } catch (error) { + console.error(error); + } + })(); + ``` + */ + ( + fn: (...arguments: ArgumentsType) => PromiseLike | ValueType, + ...arguments: ArgumentsType + ): Promise; + + // TODO: remove this in the next major version, refactor the whole definition to: + // declare function pTry( + // fn: (...arguments: ArgumentsType) => PromiseLike | ValueType, + // ...arguments: ArgumentsType + // ): Promise; + // export = pTry; + default: typeof pTry; +}; + +export = pTry; diff --git a/node_modules/p-try/index.js b/node_modules/p-try/index.js new file mode 100644 index 0000000..db858da --- /dev/null +++ b/node_modules/p-try/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const pTry = (fn, ...arguments_) => new Promise(resolve => { + resolve(fn(...arguments_)); +}); + +module.exports = pTry; +// TODO: remove this in the next major version +module.exports.default = pTry; diff --git a/node_modules/p-try/license b/node_modules/p-try/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/p-try/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/p-try/package.json b/node_modules/p-try/package.json new file mode 100644 index 0000000..81c4d32 --- /dev/null +++ b/node_modules/p-try/package.json @@ -0,0 +1,42 @@ +{ + "name": "p-try", + "version": "2.2.0", + "description": "`Start a promise chain", + "license": "MIT", + "repository": "sindresorhus/p-try", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=6" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "promise", + "try", + "resolve", + "function", + "catch", + "async", + "await", + "promises", + "settled", + "ponyfill", + "polyfill", + "shim", + "bluebird" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/p-try/readme.md b/node_modules/p-try/readme.md new file mode 100644 index 0000000..4d7bd64 --- /dev/null +++ b/node_modules/p-try/readme.md @@ -0,0 +1,58 @@ +# p-try [![Build Status](https://travis-ci.org/sindresorhus/p-try.svg?branch=master)](https://travis-ci.org/sindresorhus/p-try) + +> Start a promise chain + +[How is it useful?](http://cryto.net/~joepie91/blog/2016/05/11/what-is-promise-try-and-why-does-it-matter/) + + +## Install + +``` +$ npm install p-try +``` + + +## Usage + +```js +const pTry = require('p-try'); + +(async () => { + try { + const value = await pTry(() => { + return synchronousFunctionThatMightThrow(); + }); + console.log(value); + } catch (error) { + console.error(error); + } +})(); +``` + + +## API + +### pTry(fn, ...arguments) + +Returns a `Promise` resolved with the value of calling `fn(...arguments)`. If the function throws an error, the returned `Promise` will be rejected with that error. + +Support for passing arguments on to the `fn` is provided in order to be able to avoid creating unnecessary closures. You probably don't need this optimization unless you're pushing a *lot* of functions. + +#### fn + +The function to run to start the promise chain. + +#### arguments + +Arguments to pass to `fn`. + + +## Related + +- [p-finally](https://github.com/sindresorhus/p-finally) - `Promise#finally()` ponyfill - Invoked when the promise is settled regardless of outcome +- [More…](https://github.com/sindresorhus/promise-fun) + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/path-exists/index.d.ts b/node_modules/path-exists/index.d.ts new file mode 100644 index 0000000..54b7ab8 --- /dev/null +++ b/node_modules/path-exists/index.d.ts @@ -0,0 +1,28 @@ +declare const pathExists: { + /** + Check if a path exists. + + @returns Whether the path exists. + + @example + ``` + // foo.ts + import pathExists = require('path-exists'); + + (async () => { + console.log(await pathExists('foo.ts')); + //=> true + })(); + ``` + */ + (path: string): Promise; + + /** + Synchronously check if a path exists. + + @returns Whether the path exists. + */ + sync(path: string): boolean; +}; + +export = pathExists; diff --git a/node_modules/path-exists/index.js b/node_modules/path-exists/index.js new file mode 100644 index 0000000..1943921 --- /dev/null +++ b/node_modules/path-exists/index.js @@ -0,0 +1,23 @@ +'use strict'; +const fs = require('fs'); +const {promisify} = require('util'); + +const pAccess = promisify(fs.access); + +module.exports = async path => { + try { + await pAccess(path); + return true; + } catch (_) { + return false; + } +}; + +module.exports.sync = path => { + try { + fs.accessSync(path); + return true; + } catch (_) { + return false; + } +}; diff --git a/node_modules/path-exists/license b/node_modules/path-exists/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/path-exists/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/path-exists/package.json b/node_modules/path-exists/package.json new file mode 100644 index 0000000..0755256 --- /dev/null +++ b/node_modules/path-exists/package.json @@ -0,0 +1,39 @@ +{ + "name": "path-exists", + "version": "4.0.0", + "description": "Check if a path exists", + "license": "MIT", + "repository": "sindresorhus/path-exists", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "path", + "exists", + "exist", + "file", + "filepath", + "fs", + "filesystem", + "file-system", + "access", + "stat" + ], + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + } +} diff --git a/node_modules/path-exists/readme.md b/node_modules/path-exists/readme.md new file mode 100644 index 0000000..81f9845 --- /dev/null +++ b/node_modules/path-exists/readme.md @@ -0,0 +1,52 @@ +# path-exists [![Build Status](https://travis-ci.org/sindresorhus/path-exists.svg?branch=master)](https://travis-ci.org/sindresorhus/path-exists) + +> Check if a path exists + +NOTE: `fs.existsSync` has been un-deprecated in Node.js since 6.8.0. If you only need to check synchronously, this module is not needed. + +While [`fs.exists()`](https://nodejs.org/api/fs.html#fs_fs_exists_path_callback) is being [deprecated](https://github.com/iojs/io.js/issues/103), there's still a genuine use-case of being able to check if a path exists for other purposes than doing IO with it. + +Never use this before handling a file though: + +> In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to `fs.exists()` and `fs.open()`. Just open the file and handle the error when it's not there. + + +## Install + +``` +$ npm install path-exists +``` + + +## Usage + +```js +// foo.js +const pathExists = require('path-exists'); + +(async () => { + console.log(await pathExists('foo.js')); + //=> true +})(); +``` + + +## API + +### pathExists(path) + +Returns a `Promise` of whether the path exists. + +### pathExists.sync(path) + +Returns a `boolean` of whether the path exists. + + +## Related + +- [path-exists-cli](https://github.com/sindresorhus/path-exists-cli) - CLI for this module + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/pg-cloudflare/LICENSE b/node_modules/pg-cloudflare/LICENSE new file mode 100644 index 0000000..5c14056 --- /dev/null +++ b/node_modules/pg-cloudflare/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2010 - 2021 Brian Carlson + +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/node_modules/pg-cloudflare/README.md b/node_modules/pg-cloudflare/README.md new file mode 100644 index 0000000..68663c4 --- /dev/null +++ b/node_modules/pg-cloudflare/README.md @@ -0,0 +1,112 @@ +# pg-cloudflare + +`pg-cloudflare` makes it easier to take an existing package that relies on `tls` and `net`, and make it work in environments where only `connect()` is supported, such as Cloudflare Workers. + +`pg-cloudflare` wraps `connect()`, the [TCP Socket API](https://github.com/wintercg/proposal-sockets-api) proposed within WinterCG, and implemented in [Cloudflare Workers](https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/), and exposes an interface with methods similar to what the `net` and `tls` modules in Node.js expose. (ex: `net.connect(path[, options][, callback])`). This minimizes the number of changes needed in order to make an existing package work across JavaScript runtimes. + +## Installation + +``` +npm i --save-dev pg-cloudflare +``` + +The package uses conditional exports to support bundlers that don't know about +`cloudflare:sockets`, so the consumer code by default imports an empty file. To +enable the package, resolve to the `cloudflare` condition in your bundler's +config. For example: + +- `webpack.config.js` + ```js + export default { + ..., + resolve: { conditionNames: [..., "workerd"] }, + plugins: [ + // ignore cloudflare:sockets imports + new webpack.IgnorePlugin({ + resourceRegExp: /^cloudflare:sockets$/, + }), + ], + } + ``` +- `vite.config.js` + + > [!NOTE] + > If you are using the [Cloudflare Vite plugin](https://www.npmjs.com/package/@cloudflare/vite-plugin) then the following configuration is not necessary. + + ```js + export default defineConfig({ + ..., + resolve: { + conditions: [..., "workerd"], + }, + build: { + ..., + // don't try to bundle cloudflare:sockets + rollupOptions: { + external: [..., 'cloudflare:sockets'], + }, + }, + }) + ``` + +- `rollup.config.js` + ```js + export default defineConfig({ + ..., + plugins: [..., nodeResolve({ exportConditions: [..., 'workerd'] })], + // don't try to bundle cloudflare:sockets + external: [..., 'cloudflare:sockets'], + }) + ``` +- `esbuild.config.js` + ```js + await esbuild.build({ + ..., + conditions: [..., 'workerd'], + }) + ``` + +The concrete examples can be found in `packages/pg-bundler-test`. + +## How to use conditionally, in non-Node.js environments + +As implemented in `pg` [here](https://github.com/brianc/node-postgres/commit/07553428e9c0eacf761a5d4541a3300ff7859578#diff-34588ad868ebcb232660aba7ee6a99d1e02f4bc93f73497d2688c3f074e60533R5-R13), a typical use case might look as follows, where in a Node.js environment the `net` module is used, while in a non-Node.js environment, where `net` is unavailable, `pg-cloudflare` is used instead, providing an equivalent interface: + +```js +module.exports.getStream = function getStream(ssl = false) { + const net = require('net') + if (typeof net.Socket === 'function') { + return net.Socket() + } + const { CloudflareSocket } = require('pg-cloudflare') + return new CloudflareSocket(ssl) +} +``` + +## Node.js implementation of the Socket API proposal + +If you're looking for a way to rely on `connect()` as the interface you use to interact with raw sockets, but need this interface to be available in a Node.js environment, [`@arrowood.dev/socket`](https://github.com/Ethan-Arrowood/socket) provides a Node.js implementation of the Socket API. + +### license + +The MIT License (MIT) + +Copyright (c) 2023 Brian M. Carlson + +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/node_modules/pg-cloudflare/dist/empty.d.ts b/node_modules/pg-cloudflare/dist/empty.d.ts new file mode 100644 index 0000000..d87c485 --- /dev/null +++ b/node_modules/pg-cloudflare/dist/empty.d.ts @@ -0,0 +1,2 @@ +declare const _default: {}; +export default _default; diff --git a/node_modules/pg-cloudflare/dist/empty.js b/node_modules/pg-cloudflare/dist/empty.js new file mode 100644 index 0000000..bd78fc9 --- /dev/null +++ b/node_modules/pg-cloudflare/dist/empty.js @@ -0,0 +1,6 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +// This is an empty module that is served up when outside of a workerd environment +// See the `exports` field in package.json +exports.default = {}; +//# sourceMappingURL=empty.js.map \ No newline at end of file diff --git a/node_modules/pg-cloudflare/dist/empty.js.map b/node_modules/pg-cloudflare/dist/empty.js.map new file mode 100644 index 0000000..3eaa3b1 --- /dev/null +++ b/node_modules/pg-cloudflare/dist/empty.js.map @@ -0,0 +1 @@ +{"version":3,"file":"empty.js","sourceRoot":"","sources":["../src/empty.ts"],"names":[],"mappings":";;AAAA,kFAAkF;AAClF,0CAA0C;AAC1C,kBAAe,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/pg-cloudflare/dist/index.d.ts b/node_modules/pg-cloudflare/dist/index.d.ts new file mode 100644 index 0000000..aeeba2b --- /dev/null +++ b/node_modules/pg-cloudflare/dist/index.d.ts @@ -0,0 +1,29 @@ +import { TlsOptions } from 'cloudflare:sockets'; +import { EventEmitter } from 'events'; +/** + * Wrapper around the Cloudflare built-in socket that can be used by the `Connection`. + */ +export declare class CloudflareSocket extends EventEmitter { + readonly ssl: boolean; + writable: boolean; + destroyed: boolean; + private _upgrading; + private _upgraded; + private _cfSocket; + private _cfWriter; + private _cfReader; + constructor(ssl: boolean); + setNoDelay(): this; + setKeepAlive(): this; + ref(): this; + unref(): this; + connect(port: number, host: string, connectListener?: (...args: unknown[]) => void): Promise; + _listen(): Promise; + _listenOnce(): Promise; + write(data: Uint8Array | string, callback?: (error?: unknown) => void): true | void; + write(data: Uint8Array | string, encoding?: BufferEncoding, callback?: (error?: unknown) => void): true | void; + end(data?: Buffer, encoding?: BufferEncoding, callback?: (...args: unknown[]) => void): this; + destroy(reason: string): this; + startTls(options: TlsOptions): void; + _addClosedHandler(): void; +} diff --git a/node_modules/pg-cloudflare/dist/index.js b/node_modules/pg-cloudflare/dist/index.js new file mode 100644 index 0000000..eb6bbf2 --- /dev/null +++ b/node_modules/pg-cloudflare/dist/index.js @@ -0,0 +1,171 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CloudflareSocket = void 0; +const events_1 = require("events"); +/** + * Wrapper around the Cloudflare built-in socket that can be used by the `Connection`. + */ +class CloudflareSocket extends events_1.EventEmitter { + constructor(ssl) { + super(); + this.ssl = ssl; + this.writable = false; + this.destroyed = false; + this._upgrading = false; + this._upgraded = false; + this._cfSocket = null; + this._cfWriter = null; + this._cfReader = null; + } + setNoDelay() { + return this; + } + setKeepAlive() { + return this; + } + ref() { + return this; + } + unref() { + return this; + } + async connect(port, host, connectListener) { + try { + log('connecting'); + if (connectListener) + this.once('connect', connectListener); + const options = this.ssl ? { secureTransport: 'starttls' } : {}; + const mod = await import('cloudflare:sockets'); + const connect = mod.connect; + this._cfSocket = connect(`${host}:${port}`, options); + this._cfWriter = this._cfSocket.writable.getWriter(); + this._addClosedHandler(); + this._cfReader = this._cfSocket.readable.getReader(); + if (this.ssl) { + this._listenOnce().catch((e) => this.emit('error', e)); + } + else { + this._listen().catch((e) => this.emit('error', e)); + } + await this._cfWriter.ready; + log('socket ready'); + this.writable = true; + this.emit('connect'); + return this; + } + catch (e) { + this.emit('error', e); + } + } + async _listen() { + // eslint-disable-next-line no-constant-condition + while (true) { + log('awaiting receive from CF socket'); + const { done, value } = await this._cfReader.read(); + log('CF socket received:', done, value); + if (done) { + log('done'); + break; + } + this.emit('data', Buffer.from(value)); + } + } + async _listenOnce() { + log('awaiting first receive from CF socket'); + const { done, value } = await this._cfReader.read(); + log('First CF socket received:', done, value); + this.emit('data', Buffer.from(value)); + } + write(data, encodingOrCallback = 'utf8', callback = () => { }) { + const encoding = typeof encodingOrCallback === 'function' ? 'utf8' : encodingOrCallback; + if (typeof encodingOrCallback === 'function') + callback = encodingOrCallback; + if (data.length === 0) + return callback(); + if (typeof data === 'string') + data = Buffer.from(data, encoding); + log('sending data direct:', data); + this._cfWriter.write(data).then(() => { + log('data sent'); + callback(); + }, (err) => { + log('send error', err); + callback(err); + }); + return true; + } + end(data = Buffer.alloc(0), encoding = 'utf8', callback = () => { }) { + log('ending CF socket'); + this.write(data, encoding, (err) => { + const socket = this._cfSocket; + const closePromise = socket?.close(); + closePromise + ?.then(() => { + if (this._cfSocket === socket) { + this._cfSocket = null; + this.emit('close'); + } + }) + .catch((e) => this.emit('error', e)); + if (callback) + callback(err); + }); + return this; + } + destroy(reason) { + log('destroying CF socket', reason); + this.destroyed = true; + return this.end(); + } + startTls(options) { + if (this._upgraded) { + // Don't try to upgrade again. + this.emit('error', 'Cannot call `startTls()` more than once on a socket'); + return; + } + this._cfWriter.releaseLock(); + this._cfReader.releaseLock(); + this._upgrading = true; + this._cfSocket = this._cfSocket.startTls(options); + this._cfWriter = this._cfSocket.writable.getWriter(); + this._cfReader = this._cfSocket.readable.getReader(); + this._addClosedHandler(); + this._listen().catch((e) => this.emit('error', e)); + } + _addClosedHandler() { + const socket = this._cfSocket; + socket.closed + .then(() => { + if (!this._upgrading) { + log('CF socket closed'); + if (this._cfSocket === socket) { + this._cfSocket = null; + this.emit('close'); + } + } + else { + this._upgrading = false; + this._upgraded = true; + } + }) + .catch((e) => this.emit('error', e)); + } +} +exports.CloudflareSocket = CloudflareSocket; +const debug = false; +function dump(data) { + if (data instanceof Uint8Array || data instanceof ArrayBuffer) { + // workaround https://github.com/microsoft/TypeScript/issues/63447 + const buf = data instanceof Uint8Array ? Buffer.from(data) : Buffer.from(data); + const hex = buf.toString('hex'); + const str = new TextDecoder().decode(data); + return `\n>>> STR: "${str.replace(/\n/g, '\\n')}"\n>>> HEX: ${hex}\n`; + } + else { + return data; + } +} +function log(...args) { + debug && console.log(...args.map(dump)); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/pg-cloudflare/dist/index.js.map b/node_modules/pg-cloudflare/dist/index.js.map new file mode 100644 index 0000000..22b7b5e --- /dev/null +++ b/node_modules/pg-cloudflare/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AACA,mCAAqC;AAErC;;GAEG;AACH,MAAa,gBAAiB,SAAQ,qBAA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AAI,CAAC,CAAA;QAE9E,MAAM,GAAG,GAAG,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;QAC/B,MAAM,GAAG,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QAC1C,OAAO,eAAe,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,eAAe,GAAG,IAAI,CAAA;IACvE,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,CAAA;IACb,CAAC;AACH,CAAC;AAED,SAAS,GAAG,CAAC,GAAG,IAAe;IAC7B,KAAK,IAAI,OAAO,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAA;AACzC,CAAC"} \ No newline at end of file diff --git a/node_modules/pg-cloudflare/esm/index.mjs b/node_modules/pg-cloudflare/esm/index.mjs new file mode 100644 index 0000000..6384216 --- /dev/null +++ b/node_modules/pg-cloudflare/esm/index.mjs @@ -0,0 +1,3 @@ +import cf from '../dist/index.js' + +export const CloudflareSocket = cf.CloudflareSocket diff --git a/node_modules/pg-cloudflare/package.json b/node_modules/pg-cloudflare/package.json new file mode 100644 index 0000000..cd32bf7 --- /dev/null +++ b/node_modules/pg-cloudflare/package.json @@ -0,0 +1,39 @@ +{ + "name": "pg-cloudflare", + "version": "1.4.1", + "description": "A socket implementation that can run on Cloudflare Workers using native TCP connections.", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "license": "MIT", + "devDependencies": { + "ts-node": "^8.5.4", + "typescript": "^6.0.3" + }, + "exports": { + ".": { + "workerd": { + "import": "./esm/index.mjs", + "require": "./dist/index.js" + }, + "default": "./dist/empty.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "build": "tsc", + "build:watch": "tsc --watch", + "prepublish": "yarn build", + "test": "echo e2e test in pg package" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianc/node-postgres.git", + "directory": "packages/pg-cloudflare" + }, + "files": [ + "/dist/*{js,ts,map}", + "/src", + "/esm" + ], + "gitHead": "0980cefebe0ae461da8883703be049fe13ca96cf" +} diff --git a/node_modules/pg-cloudflare/src/empty.ts b/node_modules/pg-cloudflare/src/empty.ts new file mode 100644 index 0000000..f1e6740 --- /dev/null +++ b/node_modules/pg-cloudflare/src/empty.ts @@ -0,0 +1,3 @@ +// This is an empty module that is served up when outside of a workerd environment +// See the `exports` field in package.json +export default {} diff --git a/node_modules/pg-cloudflare/src/index.ts b/node_modules/pg-cloudflare/src/index.ts new file mode 100644 index 0000000..527b433 --- /dev/null +++ b/node_modules/pg-cloudflare/src/index.ts @@ -0,0 +1,187 @@ +import { SocketOptions, Socket, TlsOptions } from 'cloudflare:sockets' +import { EventEmitter } from 'events' + +/** + * Wrapper around the Cloudflare built-in socket that can be used by the `Connection`. + */ +export class CloudflareSocket extends EventEmitter { + writable = false + destroyed = false + + private _upgrading = false + private _upgraded = false + private _cfSocket: Socket | null = null + private _cfWriter: WritableStreamDefaultWriter | null = null + private _cfReader: ReadableStreamDefaultReader | null = null + + constructor(readonly ssl: boolean) { + super() + } + + setNoDelay() { + return this + } + setKeepAlive() { + return this + } + ref() { + return this + } + unref() { + return this + } + + async connect(port: number, host: string, connectListener?: (...args: unknown[]) => void) { + try { + log('connecting') + if (connectListener) this.once('connect', connectListener) + + const options: SocketOptions = this.ssl ? { secureTransport: 'starttls' } : {} + const mod = await import('cloudflare:sockets') + const connect = mod.connect + this._cfSocket = connect(`${host}:${port}`, options) + this._cfWriter = this._cfSocket.writable.getWriter() + this._addClosedHandler() + + this._cfReader = this._cfSocket.readable.getReader() + if (this.ssl) { + this._listenOnce().catch((e) => this.emit('error', e)) + } else { + this._listen().catch((e) => this.emit('error', e)) + } + + await this._cfWriter!.ready + log('socket ready') + this.writable = true + this.emit('connect') + + return this + } catch (e) { + this.emit('error', e) + } + } + + async _listen() { + // eslint-disable-next-line no-constant-condition + while (true) { + log('awaiting receive from CF socket') + const { done, value } = await this._cfReader!.read() + log('CF socket received:', done, value) + if (done) { + log('done') + break + } + this.emit('data', Buffer.from(value)) + } + } + + async _listenOnce() { + log('awaiting first receive from CF socket') + const { done, value } = await this._cfReader!.read() + log('First CF socket received:', done, value) + this.emit('data', Buffer.from(value)) + } + + write(data: Uint8Array | string, callback?: (error?: unknown) => void): true | void + write(data: Uint8Array | string, encoding?: BufferEncoding, callback?: (error?: unknown) => void): true | void + write( + data: Uint8Array | string, + encodingOrCallback: BufferEncoding | ((error?: unknown) => void) = 'utf8', + callback: (error?: unknown) => void = () => {} + ): true | void { + const encoding = typeof encodingOrCallback === 'function' ? 'utf8' : encodingOrCallback + if (typeof encodingOrCallback === 'function') callback = encodingOrCallback + if (data.length === 0) return callback() + if (typeof data === 'string') data = Buffer.from(data, encoding) + + log('sending data direct:', data) + this._cfWriter!.write(data).then( + () => { + log('data sent') + callback() + }, + (err) => { + log('send error', err) + callback(err) + } + ) + return true + } + + end(data = Buffer.alloc(0), encoding: BufferEncoding = 'utf8', callback: (...args: unknown[]) => void = () => {}) { + log('ending CF socket') + this.write(data, encoding, (err) => { + const socket = this._cfSocket + const closePromise = socket?.close() + closePromise + ?.then(() => { + if (this._cfSocket === socket) { + this._cfSocket = null + this.emit('close') + } + }) + .catch((e) => this.emit('error', e)) + if (callback) callback(err) + }) + return this + } + + destroy(reason: string) { + log('destroying CF socket', reason) + this.destroyed = true + return this.end() + } + + startTls(options: TlsOptions) { + if (this._upgraded) { + // Don't try to upgrade again. + this.emit('error', 'Cannot call `startTls()` more than once on a socket') + return + } + this._cfWriter!.releaseLock() + this._cfReader!.releaseLock() + this._upgrading = true + this._cfSocket = this._cfSocket!.startTls(options) + this._cfWriter = this._cfSocket.writable.getWriter() + this._cfReader = this._cfSocket.readable.getReader() + this._addClosedHandler() + this._listen().catch((e) => this.emit('error', e)) + } + + _addClosedHandler() { + const socket = this._cfSocket! + socket.closed + .then(() => { + if (!this._upgrading) { + log('CF socket closed') + if (this._cfSocket === socket) { + this._cfSocket = null + this.emit('close') + } + } else { + this._upgrading = false + this._upgraded = true + } + }) + .catch((e) => this.emit('error', e)) + } +} + +const debug = false + +function dump(data: unknown) { + if (data instanceof Uint8Array || data instanceof ArrayBuffer) { + // workaround https://github.com/microsoft/TypeScript/issues/63447 + const buf = data instanceof Uint8Array ? Buffer.from(data) : Buffer.from(data) + + const hex = buf.toString('hex') + const str = new TextDecoder().decode(data) + return `\n>>> STR: "${str.replace(/\n/g, '\\n')}"\n>>> HEX: ${hex}\n` + } else { + return data + } +} + +function log(...args: unknown[]) { + debug && console.log(...args.map(dump)) +} diff --git a/node_modules/pg-cloudflare/src/types.d.ts b/node_modules/pg-cloudflare/src/types.d.ts new file mode 100644 index 0000000..f6f1c3f --- /dev/null +++ b/node_modules/pg-cloudflare/src/types.d.ts @@ -0,0 +1,25 @@ +declare module 'cloudflare:sockets' { + export class Socket { + public readonly readable: any + public readonly writable: any + public readonly closed: Promise + public close(): Promise + public startTls(options: TlsOptions): Socket + } + + export type TlsOptions = { + expectedServerHostname?: string + } + + export type SocketAddress = { + hostname: string + port: number + } + + export type SocketOptions = { + secureTransport?: 'off' | 'on' | 'starttls' + allowHalfOpen?: boolean + } + + export function connect(address: string | SocketAddress, options?: SocketOptions): Socket +} diff --git a/node_modules/pg-connection-string/LICENSE b/node_modules/pg-connection-string/LICENSE new file mode 100644 index 0000000..b068a6c --- /dev/null +++ b/node_modules/pg-connection-string/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Iced Development + +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/node_modules/pg-connection-string/README.md b/node_modules/pg-connection-string/README.md new file mode 100644 index 0000000..5475f63 --- /dev/null +++ b/node_modules/pg-connection-string/README.md @@ -0,0 +1,105 @@ +pg-connection-string +==================== + +[![NPM](https://nodei.co/npm/pg-connection-string.png?compact=true)](https://nodei.co/npm/pg-connection-string/) + +Functions for dealing with a PostgreSQL connection string + +`parse` method taken from [node-postgres](https://github.com/brianc/node-postgres.git) +Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com) +MIT License + +## Usage + +```js +const parse = require('pg-connection-string').parse; + +const config = parse('postgres://someuser:somepassword@somehost:381/somedatabase') +``` + +The resulting config contains a subset of the following properties: + +* `user` - User with which to authenticate to the server +* `password` - Corresponding password +* `host` - Postgres server hostname or, for UNIX domain sockets, the socket filename +* `port` - port on which to connect +* `database` - Database name within the server +* `client_encoding` - string encoding the client will use +* `ssl`, either a boolean or an object with properties + * `rejectUnauthorized` + * `cert` + * `key` + * `ca` +* any other query parameters (for example, `application_name`) are preserved intact. + +### ClientConfig Compatibility for TypeScript + +The pg-connection-string `ConnectionOptions` interface is not compatible with the `ClientConfig` interface that [pg.Client](https://node-postgres.com/apis/client) expects. To remedy this, use the `parseIntoClientConfig` function instead of `parse`: + +```ts +import { ClientConfig } from 'pg'; +import { parseIntoClientConfig } from 'pg-connection-string'; + +const config: ClientConfig = parseIntoClientConfig('postgres://someuser:somepassword@somehost:381/somedatabase') +``` + +You can also use `toClientConfig` to convert an existing `ConnectionOptions` interface into a `ClientConfig` interface: + +```ts +import { ClientConfig } from 'pg'; +import { parse, toClientConfig } from 'pg-connection-string'; + +const config = parse('postgres://someuser:somepassword@somehost:381/somedatabase') +const clientConfig: ClientConfig = toClientConfig(config) +``` + +## Connection Strings + +The short summary of acceptable URLs is: + + * `socket:?` - UNIX domain socket + * `postgres://:@:/?` - TCP connection + +But see below for more details. + +### UNIX Domain Sockets + +When user and password are not given, the socket path follows `socket:`, as in `socket:/var/run/pgsql`. +This form can be shortened to just a path: `/var/run/pgsql`. + +When user and password are given, they are included in the typical URL positions, with an empty `host`, as in `socket://user:pass@/var/run/pgsql`. + +Query parameters follow a `?` character, including the following special query parameters: + + * `db=` - sets the database name (urlencoded) + * `encoding=` - sets the `client_encoding` property + +### TCP Connections + +TCP connections to the Postgres server are indicated with `pg:` or `postgres:` schemes (in fact, any scheme but `socket:` is accepted). +If username and password are included, they should be urlencoded. +The database name, however, should *not* be urlencoded. + +Query parameters follow a `?` character, including the following special query parameters: + * `host=` - sets `host` property, overriding the URL's host + * `encoding=` - sets the `client_encoding` property + * `ssl=1`, `ssl=true`, `ssl=0`, `ssl=false` - sets `ssl` to true or false, accordingly + * `uselibpqcompat=true` - use libpq semantics + * `sslmode=` when `uselibpqcompat=true` is not set + * `sslmode=disable` - sets `ssl` to false + * `sslmode=no-verify` - sets `ssl` to `{ rejectUnauthorized: false }` + * `sslmode=prefer`, `sslmode=require`, `sslmode=verify-ca`, `sslmode=verify-full` - sets `ssl` to true + * `sslmode=` when `uselibpqcompat=true` + * `sslmode=disable` - sets `ssl` to false + * `sslmode=prefer` - sets `ssl` to `{ rejectUnauthorized: false }` + * `sslmode=require` - sets `ssl` to `{ rejectUnauthorized: false }` unless `sslrootcert` is specified, in which case it behaves like `verify-ca` + * `sslmode=verify-ca` - sets `ssl` to `{ checkServerIdentity: no-op }` (verify CA, but not server identity). This verifies the presented certificate against the effective CA specified in sslrootcert. + * `sslmode=verify-full` - sets `ssl` to `{}` (verify CA and server identity) + * `sslcert=` - reads data from the given file and includes the result as `ssl.cert` + * `sslkey=` - reads data from the given file and includes the result as `ssl.key` + * `sslrootcert=` - reads data from the given file and includes the result as `ssl.ca` + +A bare relative URL, such as `salesdata`, will indicate a database name while leaving other properties empty. + +> [!CAUTION] +> Choosing an sslmode other than verify-full has serious security implications. Please read https://www.postgresql.org/docs/current/libpq-ssl.html#LIBPQ-SSL-SSLMODE-STATEMENTS to understand the trade-offs. diff --git a/node_modules/pg-connection-string/esm/index.mjs b/node_modules/pg-connection-string/esm/index.mjs new file mode 100644 index 0000000..7b390c5 --- /dev/null +++ b/node_modules/pg-connection-string/esm/index.mjs @@ -0,0 +1,8 @@ +// ESM wrapper for pg-connection-string +import connectionString from '../index.js' + +// Re-export the parse function +export default connectionString.parse +export const parse = connectionString.parse +export const toClientConfig = connectionString.toClientConfig +export const parseIntoClientConfig = connectionString.parseIntoClientConfig diff --git a/node_modules/pg-connection-string/index.d.ts b/node_modules/pg-connection-string/index.d.ts new file mode 100644 index 0000000..4b30529 --- /dev/null +++ b/node_modules/pg-connection-string/index.d.ts @@ -0,0 +1,37 @@ +import { ClientConfig } from 'pg' + +export function parse(connectionString: string, options?: Options): ConnectionOptions + +export interface Options { + // Use libpq semantics when interpreting the connection string + useLibpqCompat?: boolean +} + +interface SSLConfig { + ca?: string + cert?: string | null + key?: string + rejectUnauthorized?: boolean +} + +export interface ConnectionOptions { + host: string | null + password?: string + user?: string + port?: string | null + database: string | null | undefined + client_encoding?: string + ssl?: boolean | string | SSLConfig + sslnegotiation?: 'postgres' | 'direct' + + application_name?: string + fallback_application_name?: string + options?: string + keepalives?: number + + // We allow any other options to be passed through + [key: string]: unknown +} + +export function toClientConfig(config: ConnectionOptions): ClientConfig +export function parseIntoClientConfig(connectionString: string): ClientConfig diff --git a/node_modules/pg-connection-string/index.js b/node_modules/pg-connection-string/index.js new file mode 100644 index 0000000..139cc17 --- /dev/null +++ b/node_modules/pg-connection-string/index.js @@ -0,0 +1,237 @@ +'use strict' + +//Parse method copied from https://github.com/brianc/node-postgres +//Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com) +//MIT License + +//parses a connection string +function parse(str, options = {}) { + //unix socket + if (str.charAt(0) === '/') { + const config = str.split(' ') + return { host: config[0], database: config[1] } + } + + // Check for empty host in URL + + const config = Object.create(null) + let result + let dummyHost = false + if (/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) { + // Ensure spaces are encoded as %20 + str = encodeURI(str).replace(/%25(\d\d)/g, '%$1') + } + + try { + try { + result = new URL(str, 'postgres://base') + } catch (e) { + // The URL is invalid so try again with a dummy host + result = new URL(str.replace('@/', '@___DUMMY___/'), 'postgres://base') + dummyHost = true + } + } catch (err) { + // Remove the input from the error message to avoid leaking sensitive information + err.input && (err.input = '*****REDACTED*****') + throw err + } + + // We'd like to use Object.fromEntries() here but Node.js 10 does not support it + for (const entry of result.searchParams.entries()) { + config[entry[0]] = entry[1] + } + + config.user = config.user || decodeURIComponent(result.username) + config.password = config.password || decodeURIComponent(result.password) + + if (result.protocol == 'socket:') { + config.host = decodeURI(result.pathname) + config.database = result.searchParams.get('db') + config.client_encoding = result.searchParams.get('encoding') + return config + } + const hostname = (dummyHost ? '' : result.hostname).replace(/^\[(.+)\]$/, '$1') + if (!config.host) { + // Only set the host if there is no equivalent query param. + config.host = decodeURIComponent(hostname) + } else if (hostname && /^%2f/i.test(hostname)) { + // Only prepend the hostname to the pathname if it is not a URL encoded Unix socket host. + result.pathname = hostname + result.pathname + } + if (!config.port) { + // Only set the port if there is no equivalent query param. + config.port = result.port + } + + const pathname = result.pathname.slice(1) || null + config.database = pathname ? decodeURI(pathname) : null + + if (config.ssl === 'true' || config.ssl === '1') { + config.ssl = true + } + + if (config.ssl === '0') { + config.ssl = false + } + + if (config.sslcert || config.sslkey || config.sslrootcert || config.sslmode) { + config.ssl = {} + } + + // sslnegotiation=direct implies SSL is in use (libpq requires sslmode>=require), + // so enable SSL if the connection string did not otherwise configure it. + if (config.sslnegotiation === 'direct' && config.ssl === undefined) { + config.ssl = true + } + + // Only try to load fs if we expect to read from the disk + const fs = config.sslcert || config.sslkey || config.sslrootcert ? require('fs') : null + + if (config.sslcert) { + config.ssl.cert = fs.readFileSync(config.sslcert).toString() + } + + if (config.sslkey) { + config.ssl.key = fs.readFileSync(config.sslkey).toString() + } + + if (config.sslrootcert) { + config.ssl.ca = fs.readFileSync(config.sslrootcert).toString() + } + + if (options.useLibpqCompat && config.uselibpqcompat) { + throw new Error('Both useLibpqCompat and uselibpqcompat are set. Please use only one of them.') + } + + if (config.uselibpqcompat === 'true' || options.useLibpqCompat) { + switch (config.sslmode) { + case 'disable': { + config.ssl = false + break + } + case 'prefer': { + config.ssl.rejectUnauthorized = false + break + } + case 'require': { + if (config.sslrootcert) { + // If a root CA is specified, behavior of `sslmode=require` will be the same as that of `verify-ca` + config.ssl.checkServerIdentity = function () {} + } else { + config.ssl.rejectUnauthorized = false + } + break + } + case 'verify-ca': { + if (!config.ssl.ca) { + throw new Error( + 'SECURITY WARNING: Using sslmode=verify-ca requires specifying a CA with sslrootcert. If a public CA is used, verify-ca allows connections to a server that somebody else may have registered with the CA, making you vulnerable to Man-in-the-Middle attacks. Either specify a custom CA certificate with sslrootcert parameter or use sslmode=verify-full for proper security.' + ) + } + config.ssl.checkServerIdentity = function () {} + break + } + case 'verify-full': { + break + } + } + } else { + switch (config.sslmode) { + case 'disable': { + config.ssl = false + break + } + case 'prefer': + case 'require': + case 'verify-ca': + case 'verify-full': { + if (config.sslmode !== 'verify-full') { + deprecatedSslModeWarning(config.sslmode) + } + break + } + case 'no-verify': { + config.ssl.rejectUnauthorized = false + break + } + } + } + + return config +} + +// convert pg-connection-string ssl config to a ClientConfig.ConnectionOptions +function toConnectionOptions(sslConfig) { + const connectionOptions = Object.entries(sslConfig).reduce((c, [key, value]) => { + // we explicitly check for undefined and null instead of `if (value)` because some + // options accept falsy values. Example: `ssl.rejectUnauthorized = false` + if (value !== undefined && value !== null) { + c[key] = value + } + + return c + }, Object.create(null)) + + return connectionOptions +} + +// convert pg-connection-string config to a ClientConfig +function toClientConfig(config) { + const poolConfig = Object.entries(config).reduce((c, [key, value]) => { + if (key === 'ssl') { + const sslConfig = value + + if (typeof sslConfig === 'boolean') { + c[key] = sslConfig + } + + if (typeof sslConfig === 'object') { + c[key] = toConnectionOptions(sslConfig) + } + } else if (value !== undefined && value !== null) { + if (key === 'port') { + // when port is not specified, it is converted into an empty string + // we want to avoid NaN or empty string as a values in ClientConfig + if (value !== '') { + const v = parseInt(value, 10) + if (isNaN(v)) { + throw new Error(`Invalid ${key}: ${value}`) + } + + c[key] = v + } + } else { + c[key] = value + } + } + + return c + }, Object.create(null)) + + return poolConfig +} + +// parses a connection string into ClientConfig +function parseIntoClientConfig(str) { + return toClientConfig(parse(str)) +} + +function deprecatedSslModeWarning(sslmode) { + if (!deprecatedSslModeWarning.warned && typeof process !== 'undefined' && process.emitWarning) { + deprecatedSslModeWarning.warned = true + process.emitWarning(`SECURITY WARNING: The SSL modes 'prefer', 'require', and 'verify-ca' are treated as aliases for 'verify-full'. +In the next major version (pg-connection-string v3.0.0 and pg v9.0.0), these modes will adopt standard libpq semantics, which have weaker security guarantees. + +To prepare for this change: +- If you want the current behavior, explicitly use 'sslmode=verify-full' +- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${sslmode}' + +See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`) + } +} + +module.exports = parse + +parse.parse = parse +parse.toClientConfig = toClientConfig +parse.parseIntoClientConfig = parseIntoClientConfig diff --git a/node_modules/pg-connection-string/package.json b/node_modules/pg-connection-string/package.json new file mode 100644 index 0000000..bcb9bc6 --- /dev/null +++ b/node_modules/pg-connection-string/package.json @@ -0,0 +1,51 @@ +{ + "name": "pg-connection-string", + "version": "2.14.1", + "description": "Functions for dealing with a PostgreSQL connection string", + "main": "./index.js", + "types": "./index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./esm/index.mjs", + "require": "./index.js", + "default": "./index.js" + } + }, + "scripts": { + "test": "nyc --reporter=lcov mocha && npm run check-coverage", + "check-coverage": "nyc check-coverage --statements 100 --branches 100 --lines 100 --functions 100" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianc/node-postgres.git", + "directory": "packages/pg-connection-string" + }, + "keywords": [ + "pg", + "connection", + "string", + "parse" + ], + "author": "Blaine Bublitz (http://iceddev.com/)", + "license": "MIT", + "bugs": { + "url": "https://github.com/brianc/node-postgres/issues" + }, + "homepage": "https://github.com/brianc/node-postgres/tree/master/packages/pg-connection-string", + "devDependencies": { + "@types/pg": "^8.12.0", + "chai": "^4.1.1", + "coveralls": "^3.0.4", + "mocha": "^11.7.5", + "nyc": "^15", + "tsx": "^4.19.4", + "typescript": "^6.0.3" + }, + "files": [ + "index.js", + "index.d.ts", + "esm" + ], + "gitHead": "0980cefebe0ae461da8883703be049fe13ca96cf" +} diff --git a/node_modules/pg-int8/LICENSE b/node_modules/pg-int8/LICENSE new file mode 100644 index 0000000..c56c973 --- /dev/null +++ b/node_modules/pg-int8/LICENSE @@ -0,0 +1,13 @@ +Copyright © 2017, Charmander <~@charmander.me> + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/pg-int8/README.md b/node_modules/pg-int8/README.md new file mode 100644 index 0000000..ef2e608 --- /dev/null +++ b/node_modules/pg-int8/README.md @@ -0,0 +1,16 @@ +[![Build status][ci image]][ci] + +64-bit big-endian signed integer-to-string conversion designed for [pg][]. + +```js +const readInt8 = require('pg-int8'); + +readInt8(Buffer.from([0, 1, 2, 3, 4, 5, 6, 7])) +// '283686952306183' +``` + + + [pg]: https://github.com/brianc/node-postgres + + [ci]: https://travis-ci.org/charmander/pg-int8 + [ci image]: https://api.travis-ci.org/charmander/pg-int8.svg diff --git a/node_modules/pg-int8/index.js b/node_modules/pg-int8/index.js new file mode 100644 index 0000000..db77975 --- /dev/null +++ b/node_modules/pg-int8/index.js @@ -0,0 +1,100 @@ +'use strict'; + +// selected so (BASE - 1) * 0x100000000 + 0xffffffff is a safe integer +var BASE = 1000000; + +function readInt8(buffer) { + var high = buffer.readInt32BE(0); + var low = buffer.readUInt32BE(4); + var sign = ''; + + if (high < 0) { + high = ~high + (low === 0); + low = (~low + 1) >>> 0; + sign = '-'; + } + + var result = ''; + var carry; + var t; + var digits; + var pad; + var l; + var i; + + { + carry = high % BASE; + high = high / BASE >>> 0; + + t = 0x100000000 * carry + low; + low = t / BASE >>> 0; + digits = '' + (t - BASE * low); + + if (low === 0 && high === 0) { + return sign + digits + result; + } + + pad = ''; + l = 6 - digits.length; + + for (i = 0; i < l; i++) { + pad += '0'; + } + + result = pad + digits + result; + } + + { + carry = high % BASE; + high = high / BASE >>> 0; + + t = 0x100000000 * carry + low; + low = t / BASE >>> 0; + digits = '' + (t - BASE * low); + + if (low === 0 && high === 0) { + return sign + digits + result; + } + + pad = ''; + l = 6 - digits.length; + + for (i = 0; i < l; i++) { + pad += '0'; + } + + result = pad + digits + result; + } + + { + carry = high % BASE; + high = high / BASE >>> 0; + + t = 0x100000000 * carry + low; + low = t / BASE >>> 0; + digits = '' + (t - BASE * low); + + if (low === 0 && high === 0) { + return sign + digits + result; + } + + pad = ''; + l = 6 - digits.length; + + for (i = 0; i < l; i++) { + pad += '0'; + } + + result = pad + digits + result; + } + + { + carry = high % BASE; + t = 0x100000000 * carry + low; + digits = '' + t % BASE; + + return sign + digits + result; + } +} + +module.exports = readInt8; diff --git a/node_modules/pg-int8/package.json b/node_modules/pg-int8/package.json new file mode 100644 index 0000000..4b937e1 --- /dev/null +++ b/node_modules/pg-int8/package.json @@ -0,0 +1,24 @@ +{ + "name": "pg-int8", + "version": "1.0.1", + "description": "64-bit big-endian signed integer-to-string conversion", + "bugs": "https://github.com/charmander/pg-int8/issues", + "license": "ISC", + "files": [ + "index.js" + ], + "repository": { + "type": "git", + "url": "https://github.com/charmander/pg-int8" + }, + "scripts": { + "test": "tap test" + }, + "devDependencies": { + "@charmander/eslint-config-base": "1.0.2", + "tap": "10.7.3" + }, + "engines": { + "node": ">=4.0.0" + } +} diff --git a/node_modules/pg-pool/LICENSE b/node_modules/pg-pool/LICENSE new file mode 100644 index 0000000..4e90581 --- /dev/null +++ b/node_modules/pg-pool/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Brian M. Carlson + +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/node_modules/pg-pool/README.md b/node_modules/pg-pool/README.md new file mode 100644 index 0000000..80c6447 --- /dev/null +++ b/node_modules/pg-pool/README.md @@ -0,0 +1,357 @@ +# pg-pool + +[![Build Status](https://travis-ci.org/brianc/node-pg-pool.svg?branch=master)](https://travis-ci.org/brianc/node-pg-pool) + +A connection pool for node-postgres + +## install + +```sh +npm i pg-pool pg +``` + +## use + +### create + +to use pg-pool you must first create an instance of a pool + +```js +const Pool = require('pg-pool') + +// by default the pool uses the same +// configuration as whatever `pg` version you have installed +const pool = new Pool() + +// you can pass properties to the pool +// these properties are passed unchanged to both the node-postgres Client constructor +// and the pool constructor, allowing you to fully configure the behavior of both +const pool2 = new Pool({ + database: 'postgres', + user: 'brianc', + password: 'secret!', + port: 5432, + ssl: true, + max: 20, // set pool max size to 20 + idleTimeoutMillis: 1000, // close idle clients after 1 second + connectionTimeoutMillis: 1000, // return an error after 1 second if connection could not be established + maxUses: 7500, // close (and replace) a connection after it has been used 7500 times (see below for discussion) +}) + +// you can supply a custom client constructor +// if you want to use the native postgres client +const NativeClient = require('pg').native.Client +const nativePool = new Pool({ Client: NativeClient }) + +// you can even pool pg-native clients directly +const PgNativeClient = require('pg-native') +const pgNativePool = new Pool({ Client: PgNativeClient }) +``` + +##### Note: + +The Pool constructor does not support passing a Database URL as the parameter. To use pg-pool on heroku, for example, you need to parse the URL into a config object. Here is an example of how to parse a Database URL. + +```js +const Pool = require('pg-pool') +const url = require('url') + +const params = url.parse(process.env.DATABASE_URL) +const auth = params.auth.split(':') + +const config = { + user: auth[0], + password: auth[1], + host: params.hostname, + port: params.port, + database: params.pathname.split('/')[1], + ssl: true, +} + +const pool = new Pool(config) + +/* + Transforms, 'postgres://DBuser:secret@DBHost:#####/myDB', into + config = { + user: 'DBuser', + password: 'secret', + host: 'DBHost', + port: '#####', + database: 'myDB', + ssl: true + } +*/ +``` + +### acquire clients with a promise + +pg-pool supports a fully promise-based api for acquiring clients + +```js +const pool = new Pool() +pool.connect().then((client) => { + client + .query('select $1::text as name', ['pg-pool']) + .then((res) => { + client.release() + console.log('hello from', res.rows[0].name) + }) + .catch((e) => { + client.release() + console.error('query error', e.message, e.stack) + }) +}) +``` + +### plays nice with async/await + +this ends up looking much nicer if you're using [co](https://github.com/tj/co) or async/await: + +```js +// with async/await +;(async () => { + const pool = new Pool() + const client = await pool.connect() + try { + const result = await client.query('select $1::text as name', ['brianc']) + console.log('hello from', result.rows[0]) + } finally { + client.release() + } +})().catch((e) => console.error(e.message, e.stack)) + +// with co +co(function* () { + const client = yield pool.connect() + try { + const result = yield client.query('select $1::text as name', ['brianc']) + console.log('hello from', result.rows[0]) + } finally { + client.release() + } +}).catch((e) => console.error(e.message, e.stack)) +``` + +### your new favorite helper method + +because its so common to just run a query and return the client to the pool afterward pg-pool has this built-in: + +```js +const pool = new Pool() +const time = await pool.query('SELECT NOW()') +const name = await pool.query('select $1::text as name', ['brianc']) +console.log(name.rows[0].name, 'says hello at', time.rows[0].now) +``` + +you can also use a callback here if you'd like: + +```js +const pool = new Pool() +pool.query('SELECT $1::text as name', ['brianc'], function (err, res) { + console.log(res.rows[0].name) // brianc +}) +``` + +**pro tip:** unless you need to run a transaction (which requires a single client for multiple queries) or you +have some other edge case like [streaming rows](https://github.com/brianc/node-pg-query-stream) or using a [cursor](https://github.com/brianc/node-pg-cursor) +you should almost always just use `pool.query`. Its easy, it does the right thing :tm:, and wont ever forget to return +clients back to the pool after the query is done. + +### drop-in backwards compatible + +pg-pool still and will always support the traditional callback api for acquiring a client. This is the exact API node-postgres has shipped with for years: + +```js +const pool = new Pool() +pool.connect((err, client, done) => { + if (err) return done(err) + + client.query('SELECT $1::text as name', ['pg-pool'], (err, res) => { + done() + if (err) { + return console.error('query error', err.message, err.stack) + } + console.log('hello from', res.rows[0].name) + }) +}) +``` + +### shut it down + +When you are finished with the pool if all the clients are idle the pool will close them after `config.idleTimeoutMillis` and your app +will shutdown gracefully. If you don't want to wait for the timeout you can end the pool as follows: + +```js +const pool = new Pool() +const client = await pool.connect() +console.log(await client.query('select now()')) +client.release() +await pool.end() +``` + +### a note on instances + +The pool should be a **long-lived object** in your application. Generally you'll want to instantiate one pool when your app starts up and use the same instance of the pool throughout the lifetime of your application. If you are frequently creating a new pool within your code you likely don't have your pool initialization code in the correct place. Example: + +```js +// assume this is a file in your program at ./your-app/lib/db.js + +// correct usage: create the pool and let it live +// 'globally' here, controlling access to it through exported methods +const pool = new pg.Pool() + +// this is the right way to export the query method +module.exports.query = (text, values) => { + console.log('query:', text, values) + return pool.query(text, values) +} + +// this would be the WRONG way to export the connect method +module.exports.connect = () => { + // notice how we would be creating a pool instance here + // every time we called 'connect' to get a new client? + // that's a bad thing & results in creating an unbounded + // number of pools & therefore connections + const aPool = new pg.Pool() + return aPool.connect() +} +``` + +### events + +Every instance of a `Pool` is an event emitter. These instances emit the following events: + +#### error + +Emitted whenever an idle client in the pool encounters an error. This is common when your PostgreSQL server shuts down, reboots, or a network partition otherwise causes it to become unavailable while your pool has connected clients. + +Example: + +```js +const Pool = require('pg-pool') +const pool = new Pool() + +// attach an error handler to the pool for when a connected, idle client +// receives an error by being disconnected, etc +pool.on('error', function (error, client) { + // handle this in the same way you would treat process.on('uncaughtException') + // it is supplied the error as well as the idle client which received the error +}) +``` + +#### connect + +Fired whenever the pool creates a **new** `pg.Client` instance and successfully connects it to the backend. + +Example: + +```js +const Pool = require('pg-pool') +const pool = new Pool() + +const count = 0 + +pool.on('connect', (client) => { + client.count = count++ +}) + +pool + .connect() + .then((client) => { + return client + .query('SELECT $1::int AS "clientCount"', [client.count]) + .then((res) => console.log(res.rows[0].clientCount)) // outputs 0 + .then(() => client) + }) + .then((client) => client.release()) +``` + +#### acquire + +Fired whenever a client is acquired from the pool + +Example: + +This allows you to count the number of clients which have ever been acquired from the pool. + +```js +const Pool = require('pg-pool') +const pool = new Pool() + +const acquireCount = 0 +pool.on('acquire', function (client) { + acquireCount++ +}) + +const connectCount = 0 +pool.on('connect', function () { + connectCount++ +}) + +for (let i = 0; i < 200; i++) { + pool.query('SELECT NOW()') +} + +setTimeout(function () { + console.log('connect count:', connectCount) // output: connect count: 10 + console.log('acquire count:', acquireCount) // output: acquire count: 200 +}, 100) +``` + +### environment variables + +pg-pool & node-postgres support some of the same environment variables as `psql` supports. The most common are: + +``` +PGDATABASE=my_db +PGUSER=username +PGPASSWORD="my awesome password" +PGPORT=5432 +PGSSLMODE=require +``` + +Usually I will export these into my local environment via a `.env` file with environment settings or export them in `~/.bash_profile` or something similar. This way I get configurability which works with both the postgres suite of tools (`psql`, `pg_dump`, `pg_restore`) and node, I can vary the environment variables locally and in production, and it supports the concept of a [12-factor app](http://12factor.net/) out of the box. + +## maxUses and read-replica autoscaling (e.g. AWS Aurora) + +The maxUses config option can help an application instance rebalance load against a replica set that has been auto-scaled after the connection pool is already full of healthy connections. + +The mechanism here is that a connection is considered "expended" after it has been acquired and released `maxUses` number of times. Depending on the load on your system, this means there will be an approximate time in which any given connection will live, thus creating a window for rebalancing. + +Imagine a scenario where you have 10 app instances providing an API running against a replica cluster of 3 that are accessed via a round-robin DNS entry. Each instance runs a connection pool size of 20. With an ambient load of 50 requests per second, the connection pool will likely fill up in a few minutes with healthy connections. + +If you have weekly bursts of traffic which peak at 1,000 requests per second, you might want to grow your replicas to 10 during this period. Without setting `maxUses`, the new replicas will not be adopted by the app servers without an intervention -- namely, restarting each in turn in order to build up new connection pools that are balanced against all the replicas. Adding additional app server instances will help to some extent because they will adopt all the replicas in an even way, but the initial app servers will continue to focus additional load on the original replicas. + +This is where the `maxUses` configuration option comes into play. Setting `maxUses` to 7500 will ensure that over a period of 30 minutes or so the new replicas will be adopted as the pre-existing connections are closed and replaced with new ones, thus creating a window for eventual balance. + +You'll want to test based on your own scenarios, but one way to make a first guess at `maxUses` is to identify an acceptable window for rebalancing and then solve for the value: + +``` +maxUses = rebalanceWindowSeconds * totalRequestsPerSecond / numAppInstances / poolSize +``` + +In the example above, assuming we acquire and release 1 connection per request and we are aiming for a 30 minute rebalancing window: + +``` +maxUses = rebalanceWindowSeconds * totalRequestsPerSecond / numAppInstances / poolSize + 7200 = 1800 * 1000 / 10 / 25 +``` + +## tests + +To run tests clone the repo, `npm i` in the working dir, and then run `npm test` + +## contributions + +I love contributions. Please make sure they have tests, and submit a PR. If you're not sure if the issue is worth it or will be accepted it never hurts to open an issue to begin the conversation. If you're interested in keeping up with node-postgres releated stuff, you can follow me on twitter at [@briancarlson](https://twitter.com/briancarlson) - I generally announce any noteworthy updates there. + +## license + +The MIT License (MIT) +Copyright (c) 2016 Brian M. Carlson + +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/node_modules/pg-pool/esm/index.mjs b/node_modules/pg-pool/esm/index.mjs new file mode 100644 index 0000000..a97fb62 --- /dev/null +++ b/node_modules/pg-pool/esm/index.mjs @@ -0,0 +1,5 @@ +// ESM wrapper for pg-pool +import Pool from '../index.js' + +// Export as default only to match CJS module +export default Pool diff --git a/node_modules/pg-pool/index.js b/node_modules/pg-pool/index.js new file mode 100644 index 0000000..ab514fa --- /dev/null +++ b/node_modules/pg-pool/index.js @@ -0,0 +1,517 @@ +'use strict' +const EventEmitter = require('events').EventEmitter + +const NOOP = function () {} + +const removeWhere = (list, predicate) => { + const i = list.findIndex(predicate) + + return i === -1 ? undefined : list.splice(i, 1)[0] +} + +class IdleItem { + constructor(client, idleListener, timeoutId) { + this.client = client + this.idleListener = idleListener + this.timeoutId = timeoutId + } +} + +class PendingItem { + constructor(callback) { + this.callback = callback + } +} + +function throwOnDoubleRelease() { + throw new Error('Release called on client which has already been released to the pool.') +} + +function promisify(Promise, callback) { + if (callback) { + return { callback: callback, result: undefined } + } + let rej + let res + const cb = function (err, client) { + err ? rej(err) : res(client) + } + const result = new Promise(function (resolve, reject) { + res = resolve + rej = reject + }).catch((err) => { + // replace the stack trace that leads to `TCP.onStreamRead` with one that leads back to the + // application that created the query + Error.captureStackTrace(err) + throw err + }) + return { callback: cb, result: result } +} + +function makeIdleListener(pool, client) { + return function idleListener(err) { + err.client = client + + client.removeListener('error', idleListener) + client.on('error', () => { + pool.log('additional client error after disconnection due to error', err) + }) + pool._remove(client) + // TODO - document that once the pool emits an error + // the client has already been closed & purged and is unusable + pool.emit('error', err, client) + } +} + +class Pool extends EventEmitter { + constructor(options, Client) { + super() + this.options = Object.assign({}, options) + + if (options != null && 'password' in options) { + // "hiding" the password so it doesn't show up in stack traces + // or if the client is console.logged + Object.defineProperty(this.options, 'password', { + configurable: true, + enumerable: false, + writable: true, + value: options.password, + }) + } + if (options != null && options.ssl && options.ssl.key) { + // "hiding" the ssl->key so it doesn't show up in stack traces + // or if the client is console.logged + Object.defineProperty(this.options.ssl, 'key', { + enumerable: false, + }) + } + + this.options.max = this.options.max || this.options.poolSize || 10 + this.options.min = this.options.min || 0 + this.options.maxUses = this.options.maxUses || Infinity + this.options.allowExitOnIdle = this.options.allowExitOnIdle || false + this.options.maxLifetimeSeconds = this.options.maxLifetimeSeconds || 0 + this.log = this.options.log || function () {} + this.Client = this.options.Client || Client || require('pg').Client + this.Promise = this.options.Promise || global.Promise + + if (typeof this.options.idleTimeoutMillis === 'undefined') { + this.options.idleTimeoutMillis = 10000 + } + + this._clients = [] + this._idle = [] + this._expired = new WeakSet() + this._pendingQueue = [] + this._endCallback = undefined + this.ending = false + this.ended = false + } + + _promiseTry(f) { + const Promise = this.Promise + if (typeof Promise.try === 'function') { + return Promise.try(f) + } + return new Promise((resolve) => resolve(f())) + } + + _isFull() { + return this._clients.length >= this.options.max + } + + _isAboveMin() { + return this._clients.length > this.options.min + } + + _pulseQueue() { + this.log('pulse queue') + if (this.ended) { + this.log('pulse queue ended') + return + } + if (this.ending) { + this.log('pulse queue on ending') + if (this._idle.length) { + this._idle.slice().map((item) => { + this._remove(item.client) + }) + } + if (!this._clients.length) { + this.ended = true + this._endCallback() + } + return + } + + // if we don't have any waiting, do nothing + if (!this._pendingQueue.length) { + this.log('no queued requests') + return + } + // if we don't have any idle clients and we have no more room do nothing + if (!this._idle.length && this._isFull()) { + return + } + const pendingItem = this._pendingQueue.shift() + if (this._idle.length) { + const idleItem = this._idle.pop() + clearTimeout(idleItem.timeoutId) + const client = idleItem.client + client.ref && client.ref() + const idleListener = idleItem.idleListener + + return this._acquireClient(client, pendingItem, idleListener, false) + } + if (!this._isFull()) { + return this.newClient(pendingItem) + } + throw new Error('unexpected condition') + } + + _remove(client, callback) { + const removed = removeWhere(this._idle, (item) => item.client === client) + + if (removed !== undefined) { + clearTimeout(removed.timeoutId) + } + + this._clients = this._clients.filter((c) => c !== client) + const context = this + client.end(() => { + context.emit('remove', client) + + if (typeof callback === 'function') { + callback() + } + }) + } + + connect(cb) { + if (this.ending) { + const err = new Error('Cannot use a pool after calling end on the pool') + return cb ? cb(err) : this.Promise.reject(err) + } + + const response = promisify(this.Promise, cb) + const result = response.result + + // if we don't have to connect a new client, don't do so + if (this._isFull() || this._idle.length) { + // if we have idle clients schedule a pulse immediately + if (this._idle.length) { + process.nextTick(() => this._pulseQueue()) + } + + if (!this.options.connectionTimeoutMillis) { + this._pendingQueue.push(new PendingItem(response.callback)) + return result + } + + const queueCallback = (err, res, done) => { + clearTimeout(tid) + response.callback(err, res, done) + } + + const pendingItem = new PendingItem(queueCallback) + + // set connection timeout on checking out an existing client + const tid = setTimeout(() => { + // remove the callback from pending waiters because + // we're going to call it with a timeout error + removeWhere(this._pendingQueue, (i) => i.callback === queueCallback) + pendingItem.timedOut = true + response.callback(new Error('timeout exceeded when trying to connect')) + }, this.options.connectionTimeoutMillis) + + if (tid.unref) { + tid.unref() + } + + this._pendingQueue.push(pendingItem) + return result + } + + this.newClient(new PendingItem(response.callback)) + + return result + } + + newClient(pendingItem) { + const client = new this.Client(this.options) + this._clients.push(client) + const idleListener = makeIdleListener(this, client) + + this.log('checking client timeout') + + // connection timeout logic + let tid + let timeoutHit = false + if (this.options.connectionTimeoutMillis) { + tid = setTimeout(() => { + if (client.connection) { + this.log('ending client due to timeout') + timeoutHit = true + client.connection.stream.destroy() + } else if (!client.isConnected()) { + this.log('ending client due to timeout') + timeoutHit = true + // force kill the node driver, and let libpq do its teardown + client.end() + } + }, this.options.connectionTimeoutMillis) + } + + this.log('connecting new client') + client.connect((err) => { + if (tid) { + clearTimeout(tid) + } + client.on('error', idleListener) + if (err) { + this.log('client failed to connect', err) + // remove the dead client from our list of clients + this._clients = this._clients.filter((c) => c !== client) + if (timeoutHit) { + err = new Error('Connection terminated due to connection timeout', { cause: err }) + } + + // this client won’t be released, so move on immediately + this._pulseQueue() + + if (!pendingItem.timedOut) { + pendingItem.callback(err, undefined, NOOP) + } + } else { + this.log('new client connected') + + if (this.options.onConnect) { + this._promiseTry(() => this.options.onConnect(client)).then( + () => { + this._afterConnect(client, pendingItem, idleListener) + }, + (hookErr) => { + this._clients = this._clients.filter((c) => c !== client) + client.end(() => { + this._pulseQueue() + if (!pendingItem.timedOut) { + pendingItem.callback(hookErr, undefined, NOOP) + } + }) + } + ) + return + } + + return this._afterConnect(client, pendingItem, idleListener) + } + }) + } + + _afterConnect(client, pendingItem, idleListener) { + if (this.options.maxLifetimeSeconds !== 0) { + const maxLifetimeTimeout = setTimeout(() => { + this.log('ending client due to expired lifetime') + this._expired.add(client) + const idleIndex = this._idle.findIndex((idleItem) => idleItem.client === client) + if (idleIndex !== -1) { + this._acquireClient( + client, + new PendingItem((err, client, clientRelease) => clientRelease()), + idleListener, + false + ) + } + }, this.options.maxLifetimeSeconds * 1000) + + maxLifetimeTimeout.unref() + client.once('end', () => clearTimeout(maxLifetimeTimeout)) + } + + return this._acquireClient(client, pendingItem, idleListener, true) + } + + // acquire a client for a pending work item + _acquireClient(client, pendingItem, idleListener, isNew) { + if (isNew) { + this.emit('connect', client) + } + + this.emit('acquire', client) + + client.release = this._releaseOnce(client, idleListener) + + client.removeListener('error', idleListener) + + if (!pendingItem.timedOut) { + if (isNew && this.options.verify) { + this.options.verify(client, (err) => { + if (err) { + client.release(err) + return pendingItem.callback(err, undefined, NOOP) + } + + pendingItem.callback(undefined, client, client.release) + }) + } else { + pendingItem.callback(undefined, client, client.release) + } + } else { + if (isNew && this.options.verify) { + this.options.verify(client, client.release) + } else { + client.release() + } + } + } + + // returns a function that wraps _release and throws if called more than once + _releaseOnce(client, idleListener) { + let released = false + + return (err) => { + if (released) { + throwOnDoubleRelease() + } + + released = true + this._release(client, idleListener, err) + } + } + + // release a client back to the poll, include an error + // to remove it from the pool + _release(client, idleListener, err) { + client.on('error', idleListener) + + client._poolUseCount = (client._poolUseCount || 0) + 1 + + this.emit('release', err, client) + + // TODO(bmc): expose a proper, public interface _queryable and _ending + if (err || this.ending || !client._queryable || client._ending || client._poolUseCount >= this.options.maxUses) { + if (client._poolUseCount >= this.options.maxUses) { + this.log('remove expended client') + } + + return this._remove(client, this._pulseQueue.bind(this)) + } + + const isExpired = this._expired.has(client) + if (isExpired) { + this.log('remove expired client') + this._expired.delete(client) + return this._remove(client, this._pulseQueue.bind(this)) + } + + // idle timeout + let tid + if (this.options.idleTimeoutMillis && this._isAboveMin()) { + tid = setTimeout(() => { + if (this._isAboveMin()) { + this.log('remove idle client') + this._remove(client, this._pulseQueue.bind(this)) + } + }, this.options.idleTimeoutMillis) + + if (this.options.allowExitOnIdle) { + // allow Node to exit if this is all that's left + tid.unref() + } + } + + if (this.options.allowExitOnIdle) { + client.unref() + } + + this._idle.push(new IdleItem(client, idleListener, tid)) + this._pulseQueue() + } + + query(text, values, cb) { + // guard clause against passing a function as the first parameter + if (typeof text === 'function') { + const response = promisify(this.Promise, text) + setImmediate(function () { + return response.callback(new Error('Passing a function as the first parameter to pool.query is not supported')) + }) + return response.result + } + + // allow plain text query without values, but callback + if (typeof values === 'function') { + cb = values + values = undefined + } + const response = promisify(this.Promise, cb) + cb = response.callback + + this.connect((err, client) => { + if (err) { + return cb(err) + } + + let clientReleased = false + const onError = (err) => { + if (clientReleased) { + return + } + clientReleased = true + client.release(err) + cb(err) + } + + client.once('error', onError) + this.log('dispatching query') + try { + client.query(text, values, (err, res) => { + this.log('query dispatched') + client.removeListener('error', onError) + if (clientReleased) { + return + } + clientReleased = true + client.release(err) + if (err) { + return cb(err) + } + return cb(undefined, res) + }) + } catch (err) { + client.release(err) + return cb(err) + } + }) + return response.result + } + + end(cb) { + this.log('ending') + if (this.ending) { + const err = new Error('Called end on pool more than once') + return cb ? cb(err) : this.Promise.reject(err) + } + this.ending = true + const promised = promisify(this.Promise, cb) + this._endCallback = promised.callback + this._pulseQueue() + return promised.result + } + + get waitingCount() { + return this._pendingQueue.length + } + + get idleCount() { + return this._idle.length + } + + get expiredCount() { + return this._clients.reduce((acc, client) => acc + (this._expired.has(client) ? 1 : 0), 0) + } + + get totalCount() { + return this._clients.length + } +} +module.exports = Pool diff --git a/node_modules/pg-pool/package.json b/node_modules/pg-pool/package.json new file mode 100644 index 0000000..16cf295 --- /dev/null +++ b/node_modules/pg-pool/package.json @@ -0,0 +1,51 @@ +{ + "name": "pg-pool", + "version": "3.14.0", + "description": "Connection pool for node-postgres", + "main": "index.js", + "exports": { + ".": { + "import": "./esm/index.mjs", + "require": "./index.js", + "default": "./index.js" + } + }, + "directories": { + "test": "test" + }, + "scripts": { + "test": " node_modules/.bin/mocha" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianc/node-postgres.git", + "directory": "packages/pg-pool" + }, + "keywords": [ + "pg", + "postgres", + "pool", + "database" + ], + "author": "Brian M. Carlson", + "license": "MIT", + "bugs": { + "url": "https://github.com/brianc/node-postgres/issues" + }, + "homepage": "https://github.com/brianc/node-postgres/tree/master/packages/pg-pool#readme", + "devDependencies": { + "bluebird": "3.7.2", + "co": "4.6.0", + "expect.js": "0.3.1", + "lodash": "^4.17.11", + "mocha": "^11.7.5" + }, + "peerDependencies": { + "pg": ">=8.0" + }, + "files": [ + "index.js", + "esm" + ], + "gitHead": "544b1ce8152bc280e398dc1e8a66920abe6a640e" +} diff --git a/node_modules/pg-protocol/LICENSE b/node_modules/pg-protocol/LICENSE new file mode 100644 index 0000000..5c14056 --- /dev/null +++ b/node_modules/pg-protocol/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2010 - 2021 Brian Carlson + +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/node_modules/pg-protocol/README.md b/node_modules/pg-protocol/README.md new file mode 100644 index 0000000..8c52e40 --- /dev/null +++ b/node_modules/pg-protocol/README.md @@ -0,0 +1,3 @@ +# pg-protocol + +Low level postgres wire protocol parser and serializer written in Typescript. Used by node-postgres. Needs more documentation. :smile: diff --git a/node_modules/pg-protocol/dist/b.d.ts b/node_modules/pg-protocol/dist/b.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/pg-protocol/dist/b.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/pg-protocol/dist/b.js b/node_modules/pg-protocol/dist/b.js new file mode 100644 index 0000000..6c47c10 --- /dev/null +++ b/node_modules/pg-protocol/dist/b.js @@ -0,0 +1,23 @@ +"use strict"; +// file for microbenchmarking +Object.defineProperty(exports, "__esModule", { value: true }); +const buffer_reader_1 = require("./buffer-reader"); +const LOOPS = 1000; +let count = 0; +const start = performance.now(); +const reader = new buffer_reader_1.BufferReader(); +const buffer = Buffer.from([33, 33, 33, 33, 33, 33, 33, 0]); +const run = () => { + if (count > LOOPS) { + console.log(performance.now() - start); + return; + } + count++; + for (let i = 0; i < LOOPS; i++) { + reader.setBuffer(0, buffer); + reader.cstring(); + } + setImmediate(run); +}; +run(); +//# sourceMappingURL=b.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/b.js.map b/node_modules/pg-protocol/dist/b.js.map new file mode 100644 index 0000000..f232cfb --- /dev/null +++ b/node_modules/pg-protocol/dist/b.js.map @@ -0,0 +1 @@ +{"version":3,"file":"b.js","sourceRoot":"","sources":["../src/b.ts"],"names":[],"mappings":";AAAA,6BAA6B;;AAE7B,mDAA8C;AAE9C,MAAM,KAAK,GAAG,IAAI,CAAA;AAClB,IAAI,KAAK,GAAG,CAAC,CAAA;AACb,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,EAAE,CAAA;AAE/B,MAAM,MAAM,GAAG,IAAI,4BAAY,EAAE,CAAA;AACjC,MAAM,MAAM,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,CAAC,CAAA;AAE3D,MAAM,GAAG,GAAG,GAAG,EAAE;IACf,IAAI,KAAK,GAAG,KAAK,EAAE,CAAC;QAClB,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,KAAK,CAAC,CAAA;QACtC,OAAM;IACR,CAAC;IACD,KAAK,EAAE,CAAA;IACP,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,EAAE,CAAC,EAAE,EAAE,CAAC;QAC/B,MAAM,CAAC,SAAS,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;QAC3B,MAAM,CAAC,OAAO,EAAE,CAAA;IAClB,CAAC;IACD,YAAY,CAAC,GAAG,CAAC,CAAA;AACnB,CAAC,CAAA;AAED,GAAG,EAAE,CAAA"} \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/buffer-reader.d.ts b/node_modules/pg-protocol/dist/buffer-reader.d.ts new file mode 100644 index 0000000..cf9e44e --- /dev/null +++ b/node_modules/pg-protocol/dist/buffer-reader.d.ts @@ -0,0 +1,14 @@ +export declare class BufferReader { + private offset; + private buffer; + private encoding; + constructor(offset?: number); + setBuffer(offset: number, buffer: Buffer): void; + int16(): number; + byte(): number; + int32(): number; + uint32(): number; + string(length: number): string; + cstring(): string; + bytes(length: number): Buffer; +} diff --git a/node_modules/pg-protocol/dist/buffer-reader.js b/node_modules/pg-protocol/dist/buffer-reader.js new file mode 100644 index 0000000..3358253 --- /dev/null +++ b/node_modules/pg-protocol/dist/buffer-reader.js @@ -0,0 +1,55 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BufferReader = void 0; +class BufferReader { + constructor(offset = 0) { + this.offset = offset; + this.buffer = Buffer.allocUnsafe(0); + // TODO(bmc): support non-utf8 encoding? + this.encoding = 'utf-8'; + } + setBuffer(offset, buffer) { + this.offset = offset; + this.buffer = buffer; + } + int16() { + const result = this.buffer.readInt16BE(this.offset); + this.offset += 2; + return result; + } + byte() { + const result = this.buffer[this.offset]; + this.offset++; + return result; + } + int32() { + const result = this.buffer.readInt32BE(this.offset); + this.offset += 4; + return result; + } + uint32() { + const result = this.buffer.readUInt32BE(this.offset); + this.offset += 4; + return result; + } + string(length) { + const result = this.buffer.toString(this.encoding, this.offset, this.offset + length); + this.offset += length; + return result; + } + cstring() { + const start = this.offset; + let end = start; + // eslint-disable-next-line no-empty + while (this.buffer[end++]) { } + this.offset = end; + return this.buffer.toString(this.encoding, start, end - 1); + } + bytes(length) { + const result = this.buffer.slice(this.offset, this.offset + length); + this.offset += length; + return result; + } +} +exports.BufferReader = BufferReader; +//# sourceMappingURL=buffer-reader.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/buffer-reader.js.map b/node_modules/pg-protocol/dist/buffer-reader.js.map new file mode 100644 index 0000000..477ee41 --- /dev/null +++ b/node_modules/pg-protocol/dist/buffer-reader.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer-reader.js","sourceRoot":"","sources":["../src/buffer-reader.ts"],"names":[],"mappings":";;;AAAA,MAAa,YAAY;IAMvB,YAAoB,SAAiB,CAAC;QAAlB,WAAM,GAAN,MAAM,CAAY;QAL9B,WAAM,GAAW,MAAM,CAAC,WAAW,CAAC,CAAC,CAAC,CAAA;QAE9C,wCAAwC;QAChC,aAAQ,GAAmB,OAAO,CAAA;IAED,CAAC;IAEnC,SAAS,CAAC,MAAc,EAAE,MAAc;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;QACpB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAA;IACtB,CAAC;IAEM,KAAK;QACV,MAAM,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;QACnD,IAAI,CAAC,MAAM,IAAI,CAAC,CAAA;QAChB,OAAO,MAAM,CAAA;IACf,CAAC;IAEM,IAAI;QACT,MAAM,MAAM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AG,MAAM,CAAC,CAAA;QACnE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAA;QACrB,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAzDD,oCAyDC"} \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/buffer-writer.d.ts b/node_modules/pg-protocol/dist/buffer-writer.d.ts new file mode 100644 index 0000000..9f4b5a6 --- /dev/null +++ b/node_modules/pg-protocol/dist/buffer-writer.d.ts @@ -0,0 +1,21 @@ +export declare class Writer { + private size; + buffer: Buffer; + private offset; + private headerPosition; + constructor(size?: number); + private ensure; + addInt32(num: number): Writer; + addInt16(num: number): Writer; + addCString(string: string): Writer; + addString(string?: string): Writer; + addInt32PrefixedString(string: string): Writer; + add(otherBuffer: Buffer): Writer; + /** + * Appends an uninitialized block of {@link size} bytes to the buffer and returns its offset. + */ + reserveUnsafe(size: number): number; + private join; + flush(code?: number): Buffer; + clear(): void; +} diff --git a/node_modules/pg-protocol/dist/buffer-writer.js b/node_modules/pg-protocol/dist/buffer-writer.js new file mode 100644 index 0000000..9495b29 --- /dev/null +++ b/node_modules/pg-protocol/dist/buffer-writer.js @@ -0,0 +1,113 @@ +"use strict"; +//binary data writer tuned for encoding binary specific to the postgres binary protocol +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Writer = void 0; +class Writer { + constructor(size = 256) { + this.size = size; + this.offset = 5; + this.headerPosition = 0; + this.buffer = Buffer.allocUnsafe(size); + } + ensure(size) { + const remaining = this.buffer.length - this.offset; + if (remaining < size) { + const oldBuffer = this.buffer; + // exponential growth factor of around ~ 1.5 + // https://stackoverflow.com/questions/2269063/buffer-growth-strategy + const newSize = oldBuffer.length + (oldBuffer.length >> 1) + size; + this.buffer = Buffer.allocUnsafe(newSize); + oldBuffer.copy(this.buffer, 0, 0, this.offset); + } + } + addInt32(num) { + this.ensure(4); + this.buffer[this.offset++] = (num >>> 24) & 0xff; + this.buffer[this.offset++] = (num >>> 16) & 0xff; + this.buffer[this.offset++] = (num >>> 8) & 0xff; + this.buffer[this.offset++] = (num >>> 0) & 0xff; + return this; + } + addInt16(num) { + this.ensure(2); + this.buffer[this.offset++] = (num >>> 8) & 0xff; + this.buffer[this.offset++] = (num >>> 0) & 0xff; + return this; + } + addCString(string) { + if (!string) { + this.ensure(1); + } + else { + const len = Buffer.byteLength(string); + this.ensure(len + 1); // +1 for null terminator + this.buffer.write(string, this.offset, 'utf-8'); + this.offset += len; + } + this.buffer[this.offset++] = 0; // null terminator + return this; + } + addString(string = '') { + const len = Buffer.byteLength(string); + this.ensure(len); + this.buffer.write(string, this.offset); + this.offset += len; + return this; + } + // Write an Int32 byte-length prefix immediately followed by the string's UTF-8 + // bytes. Postgres' Bind wire format prefixes every parameter with its length, + // and doing it in one method computes Buffer.byteLength ONCE — the previous + // `addInt32(Buffer.byteLength(s)).addString(s)` pairing scanned the string + // three times (byteLength for the prefix, byteLength again inside addString, + // then the encode), which is costly for large text parameters. + addInt32PrefixedString(string) { + const len = Buffer.byteLength(string); + this.ensure(4 + len); + const buffer = this.buffer; + let offset = this.offset; + buffer[offset++] = (len >>> 24) & 0xff; + buffer[offset++] = (len >>> 16) & 0xff; + buffer[offset++] = (len >>> 8) & 0xff; + buffer[offset++] = (len >>> 0) & 0xff; + buffer.write(string, offset, 'utf-8'); + this.offset = offset + len; + return this; + } + add(otherBuffer) { + this.ensure(otherBuffer.length); + otherBuffer.copy(this.buffer, this.offset); + this.offset += otherBuffer.length; + return this; + } + /** + * Appends an uninitialized block of {@link size} bytes to the buffer and returns its offset. + */ + reserveUnsafe(size) { + const offset = this.offset; + this.ensure(size); + this.offset += size; + return offset; + } + join(code) { + if (code) { + this.buffer[this.headerPosition] = code; + //length is everything in this packet minus the code + const length = this.offset - (this.headerPosition + 1); + this.buffer.writeInt32BE(length, this.headerPosition + 1); + } + return this.buffer.slice(code ? 0 : 5, this.offset); + } + flush(code) { + const result = this.join(code); + this.offset = 5; + this.headerPosition = 0; + this.buffer = Buffer.allocUnsafe(this.size); + return result; + } + clear() { + this.offset = 5; + this.headerPosition = 0; + } +} +exports.Writer = Writer; +//# sourceMappingURL=buffer-writer.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/buffer-writer.js.map b/node_modules/pg-protocol/dist/buffer-writer.js.map new file mode 100644 index 0000000..96e0987 --- /dev/null +++ b/node_modules/pg-protocol/dist/buffer-writer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"buffer-writer.js","sourceRoot":"","sources":["../src/buffer-writer.ts"],"names":[],"mappings":";AAAA,uFAAuF;;;AAEvF,MAAa,MAAM;IAIjB,YAAoB,OAAO,GAAG;QAAV,SAAI,GAAJ,IAAI,CAAM;QAFtB,WAAM,GAAW,CAAC,CAAA;QAClB,mBAAc,GAAW,CAAC,CAAA;QAEhC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAA;IACxC,CAAC;IAEO,MAAM,CAAC,IAAY;QACzB,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAA;QAClD,IAAI,SAAS,GAAG,IAAI,EAAE,CAAC;YACrB,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAA;YAC7B,4CAA4C;YAC5C,qEAAqE;YACrE,MAAM,OAAO,GAAG,SAAS,CAAC,MAAM,GAAG,CAAC,SAAS,CAAC,MAAM,IAAI,CAAC,CAAC,GAAG,IAAI,CAAA;YACjE,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,WAAW,CAAC,OAAO,CAAC,CAAA;YACzC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,IAAI,CAAC,MAAM,CAAC,CAAA;QAChD,CAAC;IACH,CAAC;IAEM,QAAQ,CAAC,GAAW;QACzB,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAA;QACd,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,CA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,IAAI,CAAC,CAAA;QAC3C,OAAO,MAAM,CAAA;IACf,CAAC;IAEM,KAAK;QACV,IAAI,CAAC,MAAM,GAAG,CAAC,CAAA;QACf,IAAI,CAAC,cAAc,GAAG,CAAC,CAAA;IACzB,CAAC;CACF;AArHD,wBAqHC"} \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/inbound-parser.test.d.ts b/node_modules/pg-protocol/dist/inbound-parser.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/pg-protocol/dist/inbound-parser.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/pg-protocol/dist/inbound-parser.test.js b/node_modules/pg-protocol/dist/inbound-parser.test.js new file mode 100644 index 0000000..5161fa7 --- /dev/null +++ b/node_modules/pg-protocol/dist/inbound-parser.test.js @@ -0,0 +1,538 @@ +"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()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const test_buffers_1 = __importDefault(require("./testing/test-buffers")); +const buffer_list_1 = __importDefault(require("./testing/buffer-list")); +const _1 = require("."); +const assert_1 = __importDefault(require("assert")); +const stream_1 = require("stream"); +const parser_1 = require("./parser"); +const authOkBuffer = test_buffers_1.default.authenticationOk(); +const paramStatusBuffer = test_buffers_1.default.parameterStatus('client_encoding', 'UTF8'); +const readyForQueryBuffer = test_buffers_1.default.readyForQuery(); +const backendKeyDataBuffer = test_buffers_1.default.backendKeyData(1, 2); +const commandCompleteBuffer = test_buffers_1.default.commandComplete('SELECT 3'); +const parseCompleteBuffer = test_buffers_1.default.parseComplete(); +const bindCompleteBuffer = test_buffers_1.default.bindComplete(); +const portalSuspendedBuffer = test_buffers_1.default.portalSuspended(); +const row1 = { + name: 'id', + tableID: 1, + attributeNumber: 2, + dataTypeID: 3, + dataTypeSize: 4, + typeModifier: 5, + formatCode: 0, +}; +const oneRowDescBuff = test_buffers_1.default.rowDescription([row1]); +row1.name = 'bang'; +const twoRowBuf = test_buffers_1.default.rowDescription([ + row1, + { + name: 'whoah', + tableID: 10, + attributeNumber: 11, + dataTypeID: 12, + dataTypeSize: 13, + typeModifier: 14, + formatCode: 0, + }, +]); +const rowWithBigOids = { + name: 'bigoid', + tableID: 3000000001, + attributeNumber: 2, + dataTypeID: 3000000003, + dataTypeSize: 4, + typeModifier: 5, + formatCode: 0, +}; +const bigOidDescBuff = test_buffers_1.default.rowDescription([rowWithBigOids]); +const emptyRowFieldBuf = test_buffers_1.default.dataRow([]); +const oneFieldBuf = test_buffers_1.default.dataRow(['test']); +const expectedAuthenticationOkayMessage = { + name: 'authenticationOk', + length: 8, +}; +const expectedParameterStatusMessage = { + name: 'parameterStatus', + parameterName: 'client_encoding', + parameterValue: 'UTF8', + length: 25, +}; +const expectedBackendKeyDataMessage = { + name: 'backendKeyData', + processID: 1, + secretKey: 2, +}; +const expectedReadyForQueryMessage = { + name: 'readyForQuery', + length: 5, + status: 'I', +}; +const expectedCommandCompleteMessage = { + name: 'commandComplete', + length: 13, + text: 'SELECT 3', +}; +const emptyRowDescriptionBuffer = new buffer_list_1.default() + .addInt16(0) // number of fields + .join(true, 'T'); +const expectedEmptyRowDescriptionMessage = { + name: 'rowDescription', + length: 6, + fieldCount: 0, + fields: [], +}; +const expectedOneRowMessage = { + name: 'rowDescription', + length: 27, + fieldCount: 1, + fields: [ + { + name: 'id', + tableID: 1, + columnID: 2, + dataTypeID: 3, + dataTypeSize: 4, + dataTypeModifier: 5, + format: 'text', + }, + ], +}; +const expectedTwoRowMessage = { + name: 'rowDescription', + length: 53, + fieldCount: 2, + fields: [ + { + name: 'bang', + tableID: 1, + columnID: 2, + dataTypeID: 3, + dataTypeSize: 4, + dataTypeModifier: 5, + format: 'text', + }, + { + name: 'whoah', + tableID: 10, + columnID: 11, + dataTypeID: 12, + dataTypeSize: 13, + dataTypeModifier: 14, + format: 'text', + }, + ], +}; +const expectedBigOidMessage = { + name: 'rowDescription', + length: 31, + fieldCount: 1, + fields: [ + { + name: 'bigoid', + tableID: 3000000001, + columnID: 2, + dataTypeID: 3000000003, + dataTypeSize: 4, + dataTypeModifier: 5, + format: 'text', + }, + ], +}; +const emptyParameterDescriptionBuffer = new buffer_list_1.default() + .addInt16(0) // number of parameters + .join(true, 't'); +const oneParameterDescBuf = test_buffers_1.default.parameterDescription([1111]); +const twoParameterDescBuf = test_buffers_1.default.parameterDescription([2222, 3333]); +const bigOidParameterDescBuf = test_buffers_1.default.parameterDescription([3000000003]); +const expectedEmptyParameterDescriptionMessage = { + name: 'parameterDescription', + length: 6, + parameterCount: 0, + dataTypeIDs: [], +}; +const expectedOneParameterMessage = { + name: 'parameterDescription', + length: 10, + parameterCount: 1, + dataTypeIDs: [1111], +}; +const expectedTwoParameterMessage = { + name: 'parameterDescription', + length: 14, + parameterCount: 2, + dataTypeIDs: [2222, 3333], +}; +const expectedBigOidParameterMessage = { + name: 'parameterDescription', + length: 10, + parameterCount: 1, + dataTypeIDs: [3000000003], +}; +const testForMessage = function (buffer, expectedMessage) { + it('receives and parses ' + expectedMessage.name, () => __awaiter(this, void 0, void 0, function* () { + const messages = yield parseBuffers([buffer]); + const [lastMessage] = messages; + for (const key in expectedMessage) { + assert_1.default.deepEqual(lastMessage[key], expectedMessage[key]); + } + })); +}; +const plainPasswordBuffer = test_buffers_1.default.authenticationCleartextPassword(); +const md5PasswordBuffer = test_buffers_1.default.authenticationMD5Password(); +const SASLBuffer = test_buffers_1.default.authenticationSASL(); +const SASLContinueBuffer = test_buffers_1.default.authenticationSASLContinue(); +const SASLFinalBuffer = test_buffers_1.default.authenticationSASLFinal(); +const expectedPlainPasswordMessage = { + name: 'authenticationCleartextPassword', +}; +const expectedMD5PasswordMessage = { + name: 'authenticationMD5Password', + salt: Buffer.from([1, 2, 3, 4]), +}; +const expectedSASLMessage = { + name: 'authenticationSASL', + mechanisms: ['SCRAM-SHA-256'], +}; +const expectedSASLContinueMessage = { + name: 'authenticationSASLContinue', + data: 'data', +}; +const expectedSASLFinalMessage = { + name: 'authenticationSASLFinal', + data: 'data', +}; +const notificationResponseBuffer = test_buffers_1.default.notification(4, 'hi', 'boom'); +const expectedNotificationResponseMessage = { + name: 'notification', + processId: 4, + channel: 'hi', + payload: 'boom', +}; +const parseBuffers = (buffers) => __awaiter(void 0, void 0, void 0, function* () { + const stream = new stream_1.PassThrough(); + for (const buffer of buffers) { + stream.write(buffer); + } + stream.end(); + const msgs = []; + yield (0, _1.parse)(stream, (msg) => msgs.push(msg)); + return msgs; +}); +describe('PgPacketStream', function () { + testForMessage(authOkBuffer, expectedAuthenticationOkayMessage); + testForMessage(plainPasswordBuffer, expectedPlainPasswordMessage); + testForMessage(md5PasswordBuffer, expectedMD5PasswordMessage); + testForMessage(SASLBuffer, expectedSASLMessage); + testForMessage(SASLContinueBuffer, expectedSASLContinueMessage); + // this exercises a found bug in the parser: + // https://github.com/brianc/node-postgres/pull/2210#issuecomment-627626084 + // and adds a test which is deterministic, rather than relying on network packet chunking + const extendedSASLContinueBuffer = Buffer.concat([SASLContinueBuffer, Buffer.from([1, 2, 3, 4])]); + testForMessage(extendedSASLContinueBuffer, expectedSASLContinueMessage); + testForMessage(SASLFinalBuffer, expectedSASLFinalMessage); + // this exercises a found bug in the parser: + // https://github.com/brianc/node-postgres/pull/2210#issuecomment-627626084 + // and adds a test which is deterministic, rather than relying on network packet chunking + const extendedSASLFinalBuffer = Buffer.concat([SASLFinalBuffer, Buffer.from([1, 2, 4, 5])]); + testForMessage(extendedSASLFinalBuffer, expectedSASLFinalMessage); + testForMessage(paramStatusBuffer, expectedParameterStatusMessage); + testForMessage(backendKeyDataBuffer, expectedBackendKeyDataMessage); + testForMessage(readyForQueryBuffer, expectedReadyForQueryMessage); + testForMessage(commandCompleteBuffer, expectedCommandCompleteMessage); + testForMessage(notificationResponseBuffer, expectedNotificationResponseMessage); + testForMessage(test_buffers_1.default.emptyQuery(), { + name: 'emptyQuery', + length: 4, + }); + testForMessage(Buffer.from([0x6e, 0, 0, 0, 4]), { + name: 'noData', + }); + describe('rowDescription messages', function () { + testForMessage(emptyRowDescriptionBuffer, expectedEmptyRowDescriptionMessage); + testForMessage(oneRowDescBuff, expectedOneRowMessage); + testForMessage(twoRowBuf, expectedTwoRowMessage); + testForMessage(bigOidDescBuff, expectedBigOidMessage); + }); + describe('parameterDescription messages', function () { + testForMessage(emptyParameterDescriptionBuffer, expectedEmptyParameterDescriptionMessage); + testForMessage(oneParameterDescBuf, expectedOneParameterMessage); + testForMessage(twoParameterDescBuf, expectedTwoParameterMessage); + testForMessage(bigOidParameterDescBuf, expectedBigOidParameterMessage); + }); + describe('parsing rows', function () { + describe('parsing empty row', function () { + testForMessage(emptyRowFieldBuf, { + name: 'dataRow', + fieldCount: 0, + }); + }); + describe('parsing data row with fields', function () { + testForMessage(oneFieldBuf, { + name: 'dataRow', + fieldCount: 1, + fields: ['test'], + }); + }); + }); + describe('notice message', function () { + // this uses the same logic as error message + const buff = test_buffers_1.default.notice([{ type: 'C', value: 'code' }]); + testForMessage(buff, { + name: 'notice', + code: 'code', + }); + }); + testForMessage(test_buffers_1.default.error([]), { + name: 'error', + }); + describe('with all the fields', function () { + const buffer = test_buffers_1.default.error([ + { + type: 'S', + value: 'ERROR', + }, + { + type: 'C', + value: 'code', + }, + { + type: 'M', + value: 'message', + }, + { + type: 'D', + value: 'details', + }, + { + type: 'H', + value: 'hint', + }, + { + type: 'P', + value: '100', + }, + { + type: 'p', + value: '101', + }, + { + type: 'q', + value: 'query', + }, + { + type: 'W', + value: 'where', + }, + { + type: 'F', + value: 'file', + }, + { + type: 'L', + value: 'line', + }, + { + type: 'R', + value: 'routine', + }, + { + type: 'Z', // ignored + value: 'alsdkf', + }, + ]); + testForMessage(buffer, { + name: 'error', + severity: 'ERROR', + code: 'code', + message: 'message', + detail: 'details', + hint: 'hint', + position: '100', + internalPosition: '101', + internalQuery: 'query', + where: 'where', + file: 'file', + line: 'line', + routine: 'routine', + }); + }); + testForMessage(parseCompleteBuffer, { + name: 'parseComplete', + }); + testForMessage(bindCompleteBuffer, { + name: 'bindComplete', + }); + testForMessage(bindCompleteBuffer, { + name: 'bindComplete', + }); + testForMessage(test_buffers_1.default.closeComplete(), { + name: 'closeComplete', + }); + describe('parses portal suspended message', function () { + testForMessage(portalSuspendedBuffer, { + name: 'portalSuspended', + }); + }); + describe('parses replication start message', function () { + testForMessage(Buffer.from([0x57, 0x00, 0x00, 0x00, 0x04]), { + name: 'replicationStart', + length: 4, + }); + }); + describe('copy', () => { + testForMessage(test_buffers_1.default.copyIn(0), { + name: 'copyInResponse', + length: 7, + binary: false, + columnTypes: [], + }); + testForMessage(test_buffers_1.default.copyIn(2), { + name: 'copyInResponse', + length: 11, + binary: false, + columnTypes: [0, 1], + }); + testForMessage(test_buffers_1.default.copyOut(0), { + name: 'copyOutResponse', + length: 7, + binary: false, + columnTypes: [], + }); + testForMessage(test_buffers_1.default.copyOut(3), { + name: 'copyOutResponse', + length: 13, + binary: false, + columnTypes: [0, 1, 2], + }); + testForMessage(test_buffers_1.default.copyDone(), { + name: 'copyDone', + length: 4, + }); + testForMessage(test_buffers_1.default.copyData(Buffer.from([5, 6, 7])), { + name: 'copyData', + length: 7, + chunk: Buffer.from([5, 6, 7]), + }); + }); + // since the data message on a stream can randomly divide the incomming + // tcp packets anywhere, we need to make sure we can parse every single + // split on a tcp message + describe('split buffer, single message parsing', function () { + const fullBuffer = test_buffers_1.default.dataRow([null, 'bang', 'zug zug', null, '!']); + it('parses when full buffer comes in', function () { + return __awaiter(this, void 0, void 0, function* () { + const messages = yield parseBuffers([fullBuffer]); + const message = messages[0]; + assert_1.default.equal(message.fields.length, 5); + assert_1.default.equal(message.fields[0], null); + assert_1.default.equal(message.fields[1], 'bang'); + assert_1.default.equal(message.fields[2], 'zug zug'); + assert_1.default.equal(message.fields[3], null); + assert_1.default.equal(message.fields[4], '!'); + }); + }); + const testMessageReceivedAfterSplitAt = function (split) { + return __awaiter(this, void 0, void 0, function* () { + const firstBuffer = Buffer.alloc(fullBuffer.length - split); + const secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length); + fullBuffer.copy(firstBuffer, 0, 0); + fullBuffer.copy(secondBuffer, 0, firstBuffer.length); + const messages = yield parseBuffers([firstBuffer, secondBuffer]); + const message = messages[0]; + assert_1.default.equal(message.fields.length, 5); + assert_1.default.equal(message.fields[0], null); + assert_1.default.equal(message.fields[1], 'bang'); + assert_1.default.equal(message.fields[2], 'zug zug'); + assert_1.default.equal(message.fields[3], null); + assert_1.default.equal(message.fields[4], '!'); + }); + }; + it('parses when split in the middle', function () { + return testMessageReceivedAfterSplitAt(6); + }); + it('parses when split at end', function () { + return testMessageReceivedAfterSplitAt(2); + }); + it('parses when split at beginning', function () { + return Promise.all([ + testMessageReceivedAfterSplitAt(fullBuffer.length - 2), + testMessageReceivedAfterSplitAt(fullBuffer.length - 1), + testMessageReceivedAfterSplitAt(fullBuffer.length - 5), + ]); + }); + }); + describe('split buffer, multiple message parsing', function () { + const dataRowBuffer = test_buffers_1.default.dataRow(['!']); + const readyForQueryBuffer = test_buffers_1.default.readyForQuery(); + const fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length); + dataRowBuffer.copy(fullBuffer, 0, 0); + readyForQueryBuffer.copy(fullBuffer, dataRowBuffer.length, 0); + const verifyMessages = function (messages) { + assert_1.default.strictEqual(messages.length, 2); + assert_1.default.deepEqual(messages[0], { + name: 'dataRow', + fieldCount: 1, + length: 11, + fields: ['!'], + }); + assert_1.default.equal(messages[0].fields[0], '!'); + assert_1.default.deepEqual(messages[1], { + name: 'readyForQuery', + length: 5, + status: 'I', + }); + }; + // sanity check + it('receives both messages when packet is not split', function () { + return __awaiter(this, void 0, void 0, function* () { + const messages = yield parseBuffers([fullBuffer]); + verifyMessages(messages); + }); + }); + const splitAndVerifyTwoMessages = function (split) { + return __awaiter(this, void 0, void 0, function* () { + const firstBuffer = Buffer.alloc(fullBuffer.length - split); + const secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length); + fullBuffer.copy(firstBuffer, 0, 0); + fullBuffer.copy(secondBuffer, 0, firstBuffer.length); + const messages = yield parseBuffers([firstBuffer, secondBuffer]); + verifyMessages(messages); + }); + }; + describe('receives both messages when packet is split', function () { + it('in the middle', function () { + return splitAndVerifyTwoMessages(11); + }); + it('at the front', function () { + return Promise.all([ + splitAndVerifyTwoMessages(fullBuffer.length - 1), + splitAndVerifyTwoMessages(fullBuffer.length - 4), + splitAndVerifyTwoMessages(fullBuffer.length - 6), + ]); + }); + it('at the end', function () { + return Promise.all([splitAndVerifyTwoMessages(8), splitAndVerifyTwoMessages(1)]); + }); + }); + }); + it('cleans up the reader after handling a packet', function () { + const parser = new parser_1.Parser(); + parser.parse(oneFieldBuf, () => { }); + assert_1.default.strictEqual(parser.reader.buffer.byteLength, 0); + }); +}); +//# sourceMappingURL=inbound-parser.test.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/inbound-parser.test.js.map b/node_modules/pg-protocol/dist/inbound-parser.test.js.map new file mode 100644 index 0000000..37f1637 --- /dev/null +++ b/node_modules/pg-protocol/dist/inbound-parser.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"inbound-parser.test.js","sourceRoot":"","sources":["../src/inbound-parser.test.ts"],"names":[],"mappings":";;;;;;;;;;;;;;AAAA,0EAA4C;AAC5C,wEAA8C;AAC9C,wBAAyB;AACzB,oDAA2B;AAC3B,mCAAoC;AAEpC,qCAAiC;AAEjC,MAAM,YAAY,GAAG,sBAAO,CAA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AC,CAAA;QACJ,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,8CAA8C,EAAE;QACjD,MAAM,MAAM,GAAG,IAAI,eAAM,EAAE,CAAA;QAC3B,MAAM,CAAC,KAAK,CAAC,WAAW,EAAE,GAAG,EAAE,GAAE,CAAC,CAAC,CAAA;QACnC,gBAAM,CAAC,WAAW,CAAE,MAAc,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,CAAC,CAAC,CAAA;IACjE,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/index.d.ts b/node_modules/pg-protocol/dist/index.d.ts new file mode 100644 index 0000000..33d2c06 --- /dev/null +++ b/node_modules/pg-protocol/dist/index.d.ts @@ -0,0 +1,5 @@ +import { DatabaseError } from './messages'; +import { serialize } from './serializer'; +import { MessageCallback } from './parser'; +export declare function parse(stream: NodeJS.ReadableStream, callback: MessageCallback): Promise; +export { serialize, DatabaseError }; diff --git a/node_modules/pg-protocol/dist/index.js b/node_modules/pg-protocol/dist/index.js new file mode 100644 index 0000000..b89eb1f --- /dev/null +++ b/node_modules/pg-protocol/dist/index.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DatabaseError = exports.serialize = void 0; +exports.parse = parse; +const messages_1 = require("./messages"); +Object.defineProperty(exports, "DatabaseError", { enumerable: true, get: function () { return messages_1.DatabaseError; } }); +const serializer_1 = require("./serializer"); +Object.defineProperty(exports, "serialize", { enumerable: true, get: function () { return serializer_1.serialize; } }); +const parser_1 = require("./parser"); +function parse(stream, callback) { + const parser = new parser_1.Parser(); + stream.on('data', (buffer) => parser.parse(buffer, callback)); + return new Promise((resolve) => stream.on('end', () => resolve())); +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/index.js.map b/node_modules/pg-protocol/dist/index.js.map new file mode 100644 index 0000000..1d4f26b --- /dev/null +++ b/node_modules/pg-protocol/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;AAIA,sBAIC;AARD,yCAA0C;AAUtB,8FAVX,wBAAa,OAUW;AATjC,6CAAwC;AAS/B,0FATA,sBAAS,OASA;AARlB,qCAAkD;AAElD,SAAgB,KAAK,CAAC,MAA6B,EAAE,QAAyB;IAC5E,MAAM,MAAM,GAAG,IAAI,eAAM,EAAE,CAAA;IAC3B,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAA;IACrE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,CAAA;AACpE,CAAC"} \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/messages.d.ts b/node_modules/pg-protocol/dist/messages.d.ts new file mode 100644 index 0000000..083fa96 --- /dev/null +++ b/node_modules/pg-protocol/dist/messages.d.ts @@ -0,0 +1,161 @@ +export type Mode = 'text' | 'binary'; +export type MessageName = 'parseComplete' | 'bindComplete' | 'closeComplete' | 'noData' | 'portalSuspended' | 'replicationStart' | 'emptyQuery' | 'copyDone' | 'copyData' | 'rowDescription' | 'parameterDescription' | 'parameterStatus' | 'backendKeyData' | 'notification' | 'readyForQuery' | 'commandComplete' | 'dataRow' | 'copyInResponse' | 'copyOutResponse' | 'authenticationOk' | 'authenticationMD5Password' | 'authenticationCleartextPassword' | 'authenticationSASL' | 'authenticationSASLContinue' | 'authenticationSASLFinal' | 'error' | 'notice'; +export interface BackendMessage { + name: MessageName; + length: number; +} +export declare const parseComplete: BackendMessage; +export declare const bindComplete: BackendMessage; +export declare const closeComplete: BackendMessage; +export declare const noData: BackendMessage; +export declare const portalSuspended: BackendMessage; +export declare const replicationStart: BackendMessage; +export declare const emptyQuery: BackendMessage; +export declare const copyDone: BackendMessage; +interface NoticeOrError { + message: string | undefined; + severity: string | undefined; + code: string | undefined; + detail: string | undefined; + hint: string | undefined; + position: string | undefined; + internalPosition: string | undefined; + internalQuery: string | undefined; + where: string | undefined; + schema: string | undefined; + table: string | undefined; + column: string | undefined; + dataType: string | undefined; + constraint: string | undefined; + file: string | undefined; + line: string | undefined; + routine: string | undefined; +} +export declare class DatabaseError extends Error implements NoticeOrError { + readonly length: number; + readonly name: MessageName; + severity: string | undefined; + code: string | undefined; + detail: string | undefined; + hint: string | undefined; + position: string | undefined; + internalPosition: string | undefined; + internalQuery: string | undefined; + where: string | undefined; + schema: string | undefined; + table: string | undefined; + column: string | undefined; + dataType: string | undefined; + constraint: string | undefined; + file: string | undefined; + line: string | undefined; + routine: string | undefined; + constructor(message: string, length: number, name: MessageName); +} +export declare class CopyDataMessage { + readonly length: number; + readonly chunk: Buffer; + readonly name = "copyData"; + constructor(length: number, chunk: Buffer); +} +export declare class CopyResponse { + readonly length: number; + readonly name: MessageName; + readonly binary: boolean; + readonly columnTypes: number[]; + constructor(length: number, name: MessageName, binary: boolean, columnCount: number); +} +export declare class Field { + readonly name: string; + readonly tableID: number; + readonly columnID: number; + readonly dataTypeID: number; + readonly dataTypeSize: number; + readonly dataTypeModifier: number; + readonly format: Mode; + constructor(name: string, tableID: number, columnID: number, dataTypeID: number, dataTypeSize: number, dataTypeModifier: number, format: Mode); +} +export declare class RowDescriptionMessage { + readonly length: number; + readonly fieldCount: number; + readonly name: MessageName; + readonly fields: Field[]; + constructor(length: number, fieldCount: number); +} +export declare class ParameterDescriptionMessage { + readonly length: number; + readonly parameterCount: number; + readonly name: MessageName; + readonly dataTypeIDs: number[]; + constructor(length: number, parameterCount: number); +} +export declare class ParameterStatusMessage { + readonly length: number; + readonly parameterName: string; + readonly parameterValue: string; + readonly name: MessageName; + constructor(length: number, parameterName: string, parameterValue: string); +} +export declare class AuthenticationMD5Password implements BackendMessage { + readonly length: number; + readonly salt: Buffer; + readonly name: MessageName; + constructor(length: number, salt: Buffer); +} +export declare class BackendKeyDataMessage { + readonly length: number; + readonly processID: number; + readonly secretKey: number; + readonly name: MessageName; + constructor(length: number, processID: number, secretKey: number); +} +export declare class NotificationResponseMessage { + readonly length: number; + readonly processId: number; + readonly channel: string; + readonly payload: string; + readonly name: MessageName; + constructor(length: number, processId: number, channel: string, payload: string); +} +export declare class ReadyForQueryMessage { + readonly length: number; + readonly status: string; + readonly name: MessageName; + constructor(length: number, status: string); +} +export declare class CommandCompleteMessage { + readonly length: number; + readonly text: string; + readonly name: MessageName; + constructor(length: number, text: string); +} +export declare class DataRowMessage { + length: number; + fields: any[]; + readonly fieldCount: number; + readonly name: MessageName; + constructor(length: number, fields: any[]); +} +export declare class NoticeMessage implements BackendMessage, NoticeOrError { + readonly length: number; + readonly message: string | undefined; + constructor(length: number, message: string | undefined); + readonly name = "notice"; + severity: string | undefined; + code: string | undefined; + detail: string | undefined; + hint: string | undefined; + position: string | undefined; + internalPosition: string | undefined; + internalQuery: string | undefined; + where: string | undefined; + schema: string | undefined; + table: string | undefined; + column: string | undefined; + dataType: string | undefined; + constraint: string | undefined; + file: string | undefined; + line: string | undefined; + routine: string | undefined; +} +export {}; diff --git a/node_modules/pg-protocol/dist/messages.js b/node_modules/pg-protocol/dist/messages.js new file mode 100644 index 0000000..b9f2c44 --- /dev/null +++ b/node_modules/pg-protocol/dist/messages.js @@ -0,0 +1,160 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.NoticeMessage = exports.DataRowMessage = exports.CommandCompleteMessage = exports.ReadyForQueryMessage = exports.NotificationResponseMessage = exports.BackendKeyDataMessage = exports.AuthenticationMD5Password = exports.ParameterStatusMessage = exports.ParameterDescriptionMessage = exports.RowDescriptionMessage = exports.Field = exports.CopyResponse = exports.CopyDataMessage = exports.DatabaseError = exports.copyDone = exports.emptyQuery = exports.replicationStart = exports.portalSuspended = exports.noData = exports.closeComplete = exports.bindComplete = exports.parseComplete = void 0; +exports.parseComplete = { + name: 'parseComplete', + length: 5, +}; +exports.bindComplete = { + name: 'bindComplete', + length: 5, +}; +exports.closeComplete = { + name: 'closeComplete', + length: 5, +}; +exports.noData = { + name: 'noData', + length: 5, +}; +exports.portalSuspended = { + name: 'portalSuspended', + length: 5, +}; +exports.replicationStart = { + name: 'replicationStart', + length: 4, +}; +exports.emptyQuery = { + name: 'emptyQuery', + length: 4, +}; +exports.copyDone = { + name: 'copyDone', + length: 4, +}; +class DatabaseError extends Error { + constructor(message, length, name) { + super(message); + this.length = length; + this.name = name; + } +} +exports.DatabaseError = DatabaseError; +class CopyDataMessage { + constructor(length, chunk) { + this.length = length; + this.chunk = chunk; + this.name = 'copyData'; + } +} +exports.CopyDataMessage = CopyDataMessage; +class CopyResponse { + constructor(length, name, binary, columnCount) { + this.length = length; + this.name = name; + this.binary = binary; + this.columnTypes = new Array(columnCount); + } +} +exports.CopyResponse = CopyResponse; +class Field { + constructor(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, format) { + this.name = name; + this.tableID = tableID; + this.columnID = columnID; + this.dataTypeID = dataTypeID; + this.dataTypeSize = dataTypeSize; + this.dataTypeModifier = dataTypeModifier; + this.format = format; + } +} +exports.Field = Field; +class RowDescriptionMessage { + constructor(length, fieldCount) { + this.length = length; + this.fieldCount = fieldCount; + this.name = 'rowDescription'; + this.fields = new Array(this.fieldCount); + } +} +exports.RowDescriptionMessage = RowDescriptionMessage; +class ParameterDescriptionMessage { + constructor(length, parameterCount) { + this.length = length; + this.parameterCount = parameterCount; + this.name = 'parameterDescription'; + this.dataTypeIDs = new Array(this.parameterCount); + } +} +exports.ParameterDescriptionMessage = ParameterDescriptionMessage; +class ParameterStatusMessage { + constructor(length, parameterName, parameterValue) { + this.length = length; + this.parameterName = parameterName; + this.parameterValue = parameterValue; + this.name = 'parameterStatus'; + } +} +exports.ParameterStatusMessage = ParameterStatusMessage; +class AuthenticationMD5Password { + constructor(length, salt) { + this.length = length; + this.salt = salt; + this.name = 'authenticationMD5Password'; + } +} +exports.AuthenticationMD5Password = AuthenticationMD5Password; +class BackendKeyDataMessage { + constructor(length, processID, secretKey) { + this.length = length; + this.processID = processID; + this.secretKey = secretKey; + this.name = 'backendKeyData'; + } +} +exports.BackendKeyDataMessage = BackendKeyDataMessage; +class NotificationResponseMessage { + constructor(length, processId, channel, payload) { + this.length = length; + this.processId = processId; + this.channel = channel; + this.payload = payload; + this.name = 'notification'; + } +} +exports.NotificationResponseMessage = NotificationResponseMessage; +class ReadyForQueryMessage { + constructor(length, status) { + this.length = length; + this.status = status; + this.name = 'readyForQuery'; + } +} +exports.ReadyForQueryMessage = ReadyForQueryMessage; +class CommandCompleteMessage { + constructor(length, text) { + this.length = length; + this.text = text; + this.name = 'commandComplete'; + } +} +exports.CommandCompleteMessage = CommandCompleteMessage; +class DataRowMessage { + constructor(length, fields) { + this.length = length; + this.fields = fields; + this.name = 'dataRow'; + this.fieldCount = fields.length; + } +} +exports.DataRowMessage = DataRowMessage; +class NoticeMessage { + constructor(length, message) { + this.length = length; + this.message = message; + this.name = 'notice'; + } +} +exports.NoticeMessage = NoticeMessage; +//# sourceMappingURL=messages.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/messages.js.map b/node_modules/pg-protocol/dist/messages.js.map new file mode 100644 index 0000000..9cf2581 --- /dev/null +++ b/node_modules/pg-protocol/dist/messages.js.map @@ -0,0 +1 @@ +{"version":3,"file":"messages.js","sourceRoot":"","sources":["../src/messages.ts"],"names":[],"mappings":";;;AAoCa,QAAA,aAAa,GAAmB;IAC3C,IAAI,EAAE,eAAe;IACrB,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,YAAY,GAAmB;IAC1C,IAAI,EAAE,cAAc;IACpB,MAAM,EAAE,CAAC;CACV,CAAA;AAEY,QAAA,aAAa,GAAmB;IAC3C,IAAI,EAAE,eAAe;IACrB,MAAM,EAAE,C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;QACd,cAAS,GAAT,SAAS,CAAQ;QACjB,cAAS,GAAT,SAAS,CAAQ;QAJnB,SAAI,GAAgB,gBAAgB,CAAA;IAKjD,CAAC;CACL;AAPD,sDAOC;AAED,MAAa,2BAA2B;IAEtC,YACkB,MAAc,EACd,SAAiB,EACjB,OAAe,EACf,OAAe;QAHf,WAAM,GAAN,MAAM,CAAQ;QACd,cAAS,GAAT,SAAS,CAAQ;QACjB,YAAO,GAAP,OAAO,CAAQ;QACf,YAAO,GAAP,OAAO,CAAQ;QALjB,SAAI,GAAgB,cAAc,CAAA;IAM/C,CAAC;CACL;AARD,kEAQC;AAED,MAAa,oBAAoB;IAE/B,YACkB,MAAc,EACd,MAAc;QADd,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAQ;QAHhB,SAAI,GAAgB,eAAe,CAAA;IAIhD,CAAC;CACL;AAND,oDAMC;AAED,MAAa,sBAAsB;IAEjC,YACkB,MAAc,EACd,IAAY;QADZ,WAAM,GAAN,MAAM,CAAQ;QACd,SAAI,GAAJ,IAAI,CAAQ;QAHd,SAAI,GAAgB,iBAAiB,CAAA;IAIlD,CAAC;CACL;AAND,wDAMC;AAED,MAAa,cAAc;IAGzB,YACS,MAAc,EACd,MAAa;QADb,WAAM,GAAN,MAAM,CAAQ;QACd,WAAM,GAAN,MAAM,CAAO;QAHN,SAAI,GAAgB,SAAS,CAAA;QAK3C,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,MAAM,CAAA;IACjC,CAAC;CACF;AATD,wCASC;AAED,MAAa,aAAa;IACxB,YACkB,MAAc,EACd,OAA2B;QAD3B,WAAM,GAAN,MAAM,CAAQ;QACd,YAAO,GAAP,OAAO,CAAoB;QAE7B,SAAI,GAAG,QAAQ,CAAA;IAD5B,CAAC;CAkBL;AAtBD,sCAsBC"} \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/outbound-serializer.test.d.ts b/node_modules/pg-protocol/dist/outbound-serializer.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/pg-protocol/dist/outbound-serializer.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/pg-protocol/dist/outbound-serializer.test.js b/node_modules/pg-protocol/dist/outbound-serializer.test.js new file mode 100644 index 0000000..81a6b2e --- /dev/null +++ b/node_modules/pg-protocol/dist/outbound-serializer.test.js @@ -0,0 +1,325 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const assert_1 = __importDefault(require("assert")); +const serializer_1 = require("./serializer"); +const buffer_list_1 = __importDefault(require("./testing/buffer-list")); +describe('serializer', () => { + it('builds startup message', function () { + const actual = serializer_1.serialize.startup({ + user: 'brian', + database: 'bang', + }); + assert_1.default.deepEqual(actual, new buffer_list_1.default() + .addInt16(3) + .addInt16(0) + .addCString('user') + .addCString('brian') + .addCString('database') + .addCString('bang') + .addCString('client_encoding') + .addCString('UTF8') + .addCString('') + .join(true)); + }); + it('builds password message', function () { + const actual = serializer_1.serialize.password('!'); + assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString('!').join(true, 'p')); + }); + it('builds request ssl message', function () { + const actual = serializer_1.serialize.requestSsl(); + const expected = new buffer_list_1.default().addInt32(80877103).join(true); + assert_1.default.deepEqual(actual, expected); + }); + it('builds SASLInitialResponseMessage message', function () { + const actual = serializer_1.serialize.sendSASLInitialResponseMessage('mech', 'data'); + assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString('mech').addInt32(4).addString('data').join(true, 'p')); + }); + it('builds SCRAMClientFinalMessage message', function () { + const actual = serializer_1.serialize.sendSCRAMClientFinalMessage('data'); + assert_1.default.deepEqual(actual, new buffer_list_1.default().addString('data').join(true, 'p')); + }); + it('builds query message', function () { + const txt = 'select * from boom'; + const actual = serializer_1.serialize.query(txt); + assert_1.default.deepEqual(actual, new buffer_list_1.default().addCString(txt).join(true, 'Q')); + }); + describe('parse message', () => { + it('builds parse message', function () { + const actual = serializer_1.serialize.parse({ text: '!' }); + const expected = new buffer_list_1.default().addCString('').addCString('!').addInt16(0).join(true, 'P'); + assert_1.default.deepEqual(actual, expected); + }); + it('builds parse message with named query', function () { + const actual = serializer_1.serialize.parse({ + name: 'boom', + text: 'select * from boom', + types: [], + }); + const expected = new buffer_list_1.default().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P'); + assert_1.default.deepEqual(actual, expected); + }); + it('with multiple parameters', function () { + const actual = serializer_1.serialize.parse({ + name: 'force', + text: 'select * from bang where name = $1', + types: [1, 2, 3, 4], + }); + const expected = new buffer_list_1.default() + .addCString('force') + .addCString('select * from bang where name = $1') + .addInt16(4) + .addInt32(1) + .addInt32(2) + .addInt32(3) + .addInt32(4) + .join(true, 'P'); + assert_1.default.deepEqual(actual, expected); + }); + }); + describe('bind messages', function () { + it('with no values', function () { + const actual = serializer_1.serialize.bind(); + const expectedBuffer = new buffer_list_1.default() + .addCString('') + .addCString('') + .addInt16(0) + .addInt16(0) + .addInt16(1) + .addInt16(0) + .join(true, 'B'); + assert_1.default.deepEqual(actual, expectedBuffer); + }); + it('with named statement, portal, and values', function () { + const actual = serializer_1.serialize.bind({ + portal: 'bang', + statement: 'woo', + values: ['1', 'hi', null, 'zing'], + }); + const expectedBuffer = new buffer_list_1.default() + .addCString('bang') // portal name + .addCString('woo') // statement name + .addInt16(4) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(4) + .addInt32(1) + .add(Buffer.from('1')) + .addInt32(2) + .add(Buffer.from('hi')) + .addInt32(-1) + .addInt32(4) + .add(Buffer.from('zing')) + .addInt16(1) + .addInt16(0) + .join(true, 'B'); + assert_1.default.deepEqual(actual, expectedBuffer); + }); + it('encodes a multi-byte string param with its UTF-8 byte length, not char length', function () { + // Guards the single-pass addInt32PrefixedString write path: the Int32 + // length prefix must be the UTF-8 byte count, not String.length. 'héllo中🎉' + // is 7 code points / 8 UTF-16 code units but 13 UTF-8 bytes. + const value = 'héllo中🎉'; + const bytes = Buffer.from(value, 'utf8'); + assert_1.default.notEqual(bytes.length, value.length); // sanity: the divergence we're testing + const actual = serializer_1.serialize.bind({ values: [value] }); + const expectedBuffer = new buffer_list_1.default() + .addCString('') // portal + .addCString('') // statement + .addInt16(1) // param format code count + .addInt16(0) // format code for the one value (text) + .addInt16(1) // value count + .addInt32(bytes.length) // 13 — the UTF-8 byte length, NOT value.length (8) + .add(bytes) + .addInt16(1) // result format code count + .addInt16(0) // result format (text) + .join(true, 'B'); + assert_1.default.deepEqual(actual, expectedBuffer); + }); + }); + it('with custom valueMapper', function () { + const actual = serializer_1.serialize.bind({ + portal: 'bang', + statement: 'woo', + values: ['1', 'hi', null, 'zing'], + valueMapper: () => null, + }); + const expectedBuffer = new buffer_list_1.default() + .addCString('bang') // portal name + .addCString('woo') // statement name + .addInt16(4) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(4) + .addInt32(-1) + .addInt32(-1) + .addInt32(-1) + .addInt32(-1) + .addInt16(1) + .addInt16(0) + .join(true, 'B'); + assert_1.default.deepEqual(actual, expectedBuffer); + }); + it('with named statement, portal, and buffer value', function () { + const actual = serializer_1.serialize.bind({ + portal: 'bang', + statement: 'woo', + values: ['1', 'hi', null, Buffer.from('zing', 'utf8')], + }); + const expectedBuffer = new buffer_list_1.default() + .addCString('bang') // portal name + .addCString('woo') // statement name + .addInt16(4) // value count + .addInt16(0) // string + .addInt16(0) // string + .addInt16(0) // string + .addInt16(1) // binary + .addInt16(4) + .addInt32(1) + .add(Buffer.from('1')) + .addInt32(2) + .add(Buffer.from('hi')) + .addInt32(-1) + .addInt32(4) + .add(Buffer.from('zing', 'utf-8')) + .addInt16(1) + .addInt16(0) + .join(true, 'B'); + assert_1.default.deepEqual(actual, expectedBuffer); + }); + describe('builds execute message', function () { + it('for unamed portal with no row limit', function () { + const actual = serializer_1.serialize.execute(); + const expectedBuffer = new buffer_list_1.default().addCString('').addInt32(0).join(true, 'E'); + assert_1.default.deepEqual(actual, expectedBuffer); + }); + it('for named portal with row limit', function () { + const actual = serializer_1.serialize.execute({ + portal: 'my favorite portal', + rows: 100, + }); + const expectedBuffer = new buffer_list_1.default().addCString('my favorite portal').addInt32(100).join(true, 'E'); + assert_1.default.deepEqual(actual, expectedBuffer); + }); + }); + it('builds flush command', function () { + const actual = serializer_1.serialize.flush(); + const expected = new buffer_list_1.default().join(true, 'H'); + assert_1.default.deepEqual(actual, expected); + }); + it('builds sync command', function () { + const actual = serializer_1.serialize.sync(); + const expected = new buffer_list_1.default().join(true, 'S'); + assert_1.default.deepEqual(actual, expected); + }); + it('builds end command', function () { + const actual = serializer_1.serialize.end(); + const expected = Buffer.from([0x58, 0, 0, 0, 4]); + assert_1.default.deepEqual(actual, expected); + }); + describe('builds describe command', function () { + it('describe statement', function () { + const actual = serializer_1.serialize.describe({ type: 'S', name: 'bang' }); + const expected = new buffer_list_1.default().addChar('S').addCString('bang').join(true, 'D'); + assert_1.default.deepEqual(actual, expected); + }); + it('describe unnamed portal', function () { + const actual = serializer_1.serialize.describe({ type: 'P' }); + const expected = new buffer_list_1.default().addChar('P').addCString('').join(true, 'D'); + assert_1.default.deepEqual(actual, expected); + }); + }); + describe('builds close command', function () { + it('describe statement', function () { + const actual = serializer_1.serialize.close({ type: 'S', name: 'bang' }); + const expected = new buffer_list_1.default().addChar('S').addCString('bang').join(true, 'C'); + assert_1.default.deepEqual(actual, expected); + }); + it('describe unnamed portal', function () { + const actual = serializer_1.serialize.close({ type: 'P' }); + const expected = new buffer_list_1.default().addChar('P').addCString('').join(true, 'C'); + assert_1.default.deepEqual(actual, expected); + }); + }); + describe('copy messages', function () { + it('builds copyFromChunk', () => { + const actual = serializer_1.serialize.copyData(Buffer.from([1, 2, 3])); + const expected = new buffer_list_1.default().add(Buffer.from([1, 2, 3])).join(true, 'd'); + assert_1.default.deepEqual(actual, expected); + }); + it('builds copy fail', () => { + const actual = serializer_1.serialize.copyFail('err!'); + const expected = new buffer_list_1.default().addCString('err!').join(true, 'f'); + assert_1.default.deepEqual(actual, expected); + }); + it('builds copy done', () => { + const actual = serializer_1.serialize.copyDone(); + const expected = new buffer_list_1.default().join(true, 'c'); + assert_1.default.deepEqual(actual, expected); + }); + }); + it('builds cancel message', () => { + const actual = serializer_1.serialize.cancel(3, 4); + const expected = new buffer_list_1.default().addInt16(1234).addInt16(5678).addInt32(3).addInt32(4).join(true); + assert_1.default.deepEqual(actual, expected); + }); + describe('bind error recovery', () => { + const throwingMapper = () => { + throw new Error('valueMapper error'); + }; + it('produces correct bind output after a valueMapper exception', () => { + assert_1.default.throws(() => { + serializer_1.serialize.bind({ + values: ['fail'], + valueMapper: throwingMapper, + }); + }, /valueMapper error/); + const actual = serializer_1.serialize.bind({ + portal: 'bang', + statement: 'woo', + values: ['1', 'hi', null, 'zing'], + }); + const expectedBuffer = new buffer_list_1.default() + .addCString('bang') + .addCString('woo') + .addInt16(4) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(4) + .addInt32(1) + .add(Buffer.from('1')) + .addInt32(2) + .add(Buffer.from('hi')) + .addInt32(-1) + .addInt32(4) + .add(Buffer.from('zing')) + .addInt16(1) + .addInt16(0) + .join(true, 'B'); + assert_1.default.deepEqual(actual, expectedBuffer); + }); + it('produces correct output from other serializer methods after a failed bind', () => { + assert_1.default.throws(() => { + serializer_1.serialize.bind({ + values: ['fail'], + valueMapper: throwingMapper, + }); + }, /valueMapper error/); + const parseActual = serializer_1.serialize.parse({ text: '!' }); + const parseExpected = new buffer_list_1.default().addCString('').addCString('!').addInt16(0).join(true, 'P'); + assert_1.default.deepEqual(parseActual, parseExpected); + const queryActual = serializer_1.serialize.query('select 1'); + const queryExpected = new buffer_list_1.default().addCString('select 1').join(true, 'Q'); + assert_1.default.deepEqual(queryActual, queryExpected); + }); + }); +}); +//# sourceMappingURL=outbound-serializer.test.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/outbound-serializer.test.js.map b/node_modules/pg-protocol/dist/outbound-serializer.test.js.map new file mode 100644 index 0000000..a9bdab5 --- /dev/null +++ b/node_modules/pg-protocol/dist/outbound-serializer.test.js.map @@ -0,0 +1 @@ +{"version":3,"file":"outbound-serializer.test.js","sourceRoot":"","sources":["../src/outbound-serializer.test.ts"],"names":[],"mappings":";;;;;AAAA,oDAA2B;AAC3B,6CAAwC;AACxC,wEAA8C;AAE9C,QAAQ,CAAC,YAAY,EAAE,GAAG,EAAE;IAC1B,EAAE,CAAC,wBAAwB,EAAE;QAC3B,MAAM,MAAM,GAAG,sBAAS,CAAC,OAAO,CAAC;YAC/B,IAAI,EAAE,OAAO;YACb,QAAQ,EAAE,MAAM;SACjB,CAAC,CAAA;QACF,gBAAM,CAAC,SAAS,CACd,MAAM,EACN,IAAI,qBAAU,EAAE;aACb,QAAQ,CAAC,CAAC,CAAC;aACX,QAAQ,CAAC,CAAC,CAAC;aACX,UAAU,CAAC,MAAM,CAAC;aAClB,UAAU,CAAC,OAAO,CAAC;aACnB,UAAU,CAAC,UAAU,CAAC;aACtB,UAAU,CAAC,MAAM,CAAC;aAClB,UAAU,CAAC,iBAAiB,CAAC;aAC7B,UAAU,CAAC,MAAM,CAAC;aAClB,UAAU,CAAC,EAAE,CAAC;aACd,IAAI,CAAC,IAAI,CAAC,CACd,CAAA;IACH,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,yBAAyB,EAAE;QAC5B,MAAM,MAAM,GAAG,sBAAS,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA;QACtC,gBAAM,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;IAC5E,CAAC,CAAC,CAAA;IAEF,EAAE,CAAC,4BAA4B,EAAE;QAC/B,MAAM,MAAM,GAAG,sBAAS,CAAC,UAAU,EAAE,CAAA;QACrC,MAAM,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G,EAAE;gBACjB,sBAAS,CAAC,IAAI,CAAC;oBACb,MAAM,EAAE,CAAC,MAAM,CAAC;oBAChB,WAAW,EAAE,cAAc;iBAC5B,CAAC,CAAA;YACJ,CAAC,EAAE,mBAAmB,CAAC,CAAA;YAEvB,MAAM,WAAW,GAAG,sBAAS,CAAC,KAAK,CAAC,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC,CAAA;YAClD,MAAM,aAAa,GAAG,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YACjG,gBAAM,CAAC,SAAS,CAAC,WAAW,EAAE,aAAa,CAAC,CAAA;YAE5C,MAAM,WAAW,GAAG,sBAAS,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;YAC/C,MAAM,aAAa,GAAG,IAAI,qBAAU,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;YAC7E,gBAAM,CAAC,SAAS,CAAC,WAAW,EAAE,aAAa,CAAC,CAAA;QAC9C,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/parser.d.ts b/node_modules/pg-protocol/dist/parser.d.ts new file mode 100644 index 0000000..0ce416a --- /dev/null +++ b/node_modules/pg-protocol/dist/parser.d.ts @@ -0,0 +1,22 @@ +import { TransformOptions } from 'stream'; +import { Mode, BackendMessage } from './messages'; +export type Packet = { + code: number; + packet: Buffer; +}; +type StreamOptions = TransformOptions & { + mode: Mode; +}; +export type MessageCallback = (msg: BackendMessage) => void; +export declare class Parser { + private buffer; + private bufferLength; + private bufferOffset; + private reader; + private mode; + constructor(opts?: StreamOptions); + parse(buffer: Buffer, callback: MessageCallback): void; + private mergeBuffer; + private handlePacket; +} +export {}; diff --git a/node_modules/pg-protocol/dist/parser.js b/node_modules/pg-protocol/dist/parser.js new file mode 100644 index 0000000..c602ebb --- /dev/null +++ b/node_modules/pg-protocol/dist/parser.js @@ -0,0 +1,325 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Parser = void 0; +const messages_1 = require("./messages"); +const buffer_reader_1 = require("./buffer-reader"); +// every message is prefixed with a single byte +const CODE_LENGTH = 1; +// every message has an int32 length which includes itself but does +// NOT include the code in the length +const LEN_LENGTH = 4; +const HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH; +// A placeholder for a `BackendMessage`’s length value that will be set after construction. +const LATEINIT_LENGTH = -1; +const emptyBuffer = Buffer.allocUnsafe(0); +class Parser { + constructor(opts) { + this.buffer = emptyBuffer; + this.bufferLength = 0; + this.bufferOffset = 0; + this.reader = new buffer_reader_1.BufferReader(); + if ((opts === null || opts === void 0 ? void 0 : opts.mode) === 'binary') { + throw new Error('Binary mode not supported yet'); + } + this.mode = (opts === null || opts === void 0 ? void 0 : opts.mode) || 'text'; + } + parse(buffer, callback) { + this.mergeBuffer(buffer); + const bufferFullLength = this.bufferOffset + this.bufferLength; + let offset = this.bufferOffset; + while (offset + HEADER_LENGTH <= bufferFullLength) { + // code is 1 byte long - it identifies the message type + const code = this.buffer[offset]; + // length is 1 Uint32BE - it is the length of the message EXCLUDING the code + const length = this.buffer.readUInt32BE(offset + CODE_LENGTH); + const fullMessageLength = CODE_LENGTH + length; + if (fullMessageLength + offset <= bufferFullLength) { + const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer); + callback(message); + offset += fullMessageLength; + } + else { + break; + } + } + if (offset === bufferFullLength) { + // No more use for the buffer + this.buffer = emptyBuffer; + this.bufferLength = 0; + this.bufferOffset = 0; + } + else { + // Adjust the cursors of remainingBuffer + this.bufferLength = bufferFullLength - offset; + this.bufferOffset = offset; + } + } + mergeBuffer(buffer) { + if (this.bufferLength > 0) { + const newLength = this.bufferLength + buffer.byteLength; + const newFullLength = newLength + this.bufferOffset; + if (newFullLength > this.buffer.byteLength) { + // We can't concat the new buffer with the remaining one + let newBuffer; + if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) { + // We can move the relevant part to the beginning of the buffer instead of allocating a new buffer + newBuffer = this.buffer; + } + else { + // Allocate a new larger buffer + let newBufferLength = this.buffer.byteLength * 2; + while (newLength >= newBufferLength) { + newBufferLength *= 2; + } + newBuffer = Buffer.allocUnsafe(newBufferLength); + } + // Move the remaining buffer to the new one + this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength); + this.buffer = newBuffer; + this.bufferOffset = 0; + } + // Concat the new buffer with the remaining one + buffer.copy(this.buffer, this.bufferOffset + this.bufferLength); + this.bufferLength = newLength; + } + else { + this.buffer = buffer; + this.bufferOffset = 0; + this.bufferLength = buffer.byteLength; + } + } + handlePacket(offset, code, length, bytes) { + const { reader } = this; + // NOTE: This undesirably retains the buffer in `this.reader` if the `parse*Message` calls below throw. However, those should only throw in the case of a protocol error, which normally results in the reader being discarded. + reader.setBuffer(offset, bytes); + let message; + switch (code) { + case 50 /* MessageCodes.BindComplete */: + message = messages_1.bindComplete; + break; + case 49 /* MessageCodes.ParseComplete */: + message = messages_1.parseComplete; + break; + case 51 /* MessageCodes.CloseComplete */: + message = messages_1.closeComplete; + break; + case 110 /* MessageCodes.NoData */: + message = messages_1.noData; + break; + case 115 /* MessageCodes.PortalSuspended */: + message = messages_1.portalSuspended; + break; + case 99 /* MessageCodes.CopyDone */: + message = messages_1.copyDone; + break; + case 87 /* MessageCodes.ReplicationStart */: + message = messages_1.replicationStart; + break; + case 73 /* MessageCodes.EmptyQuery */: + message = messages_1.emptyQuery; + break; + case 68 /* MessageCodes.DataRow */: + message = parseDataRowMessage(reader); + break; + case 67 /* MessageCodes.CommandComplete */: + message = parseCommandCompleteMessage(reader); + break; + case 90 /* MessageCodes.ReadyForQuery */: + message = parseReadyForQueryMessage(reader); + break; + case 65 /* MessageCodes.NotificationResponse */: + message = parseNotificationMessage(reader); + break; + case 82 /* MessageCodes.AuthenticationResponse */: + message = parseAuthenticationResponse(reader, length); + break; + case 83 /* MessageCodes.ParameterStatus */: + message = parseParameterStatusMessage(reader); + break; + case 75 /* MessageCodes.BackendKeyData */: + message = parseBackendKeyData(reader); + break; + case 69 /* MessageCodes.ErrorMessage */: + message = parseErrorMessage(reader, 'error'); + break; + case 78 /* MessageCodes.NoticeMessage */: + message = parseErrorMessage(reader, 'notice'); + break; + case 84 /* MessageCodes.RowDescriptionMessage */: + message = parseRowDescriptionMessage(reader); + break; + case 116 /* MessageCodes.ParameterDescriptionMessage */: + message = parseParameterDescriptionMessage(reader); + break; + case 71 /* MessageCodes.CopyIn */: + message = parseCopyInMessage(reader); + break; + case 72 /* MessageCodes.CopyOut */: + message = parseCopyOutMessage(reader); + break; + case 100 /* MessageCodes.CopyData */: + message = parseCopyData(reader, length); + break; + default: + return new messages_1.DatabaseError('received invalid response: ' + code.toString(16), length, 'error'); + } + reader.setBuffer(0, emptyBuffer); + message.length = length; + return message; + } +} +exports.Parser = Parser; +const parseReadyForQueryMessage = (reader) => { + const status = reader.string(1); + return new messages_1.ReadyForQueryMessage(LATEINIT_LENGTH, status); +}; +const parseCommandCompleteMessage = (reader) => { + const text = reader.cstring(); + return new messages_1.CommandCompleteMessage(LATEINIT_LENGTH, text); +}; +const parseCopyData = (reader, length) => { + const chunk = reader.bytes(length - 4); + return new messages_1.CopyDataMessage(LATEINIT_LENGTH, chunk); +}; +const parseCopyInMessage = (reader) => parseCopyMessage(reader, 'copyInResponse'); +const parseCopyOutMessage = (reader) => parseCopyMessage(reader, 'copyOutResponse'); +const parseCopyMessage = (reader, messageName) => { + const isBinary = reader.byte() !== 0; + const columnCount = reader.int16(); + const message = new messages_1.CopyResponse(LATEINIT_LENGTH, messageName, isBinary, columnCount); + for (let i = 0; i < columnCount; i++) { + message.columnTypes[i] = reader.int16(); + } + return message; +}; +const parseNotificationMessage = (reader) => { + const processId = reader.int32(); + const channel = reader.cstring(); + const payload = reader.cstring(); + return new messages_1.NotificationResponseMessage(LATEINIT_LENGTH, processId, channel, payload); +}; +const parseRowDescriptionMessage = (reader) => { + const fieldCount = reader.int16(); + const message = new messages_1.RowDescriptionMessage(LATEINIT_LENGTH, fieldCount); + for (let i = 0; i < fieldCount; i++) { + message.fields[i] = parseField(reader); + } + return message; +}; +const parseField = (reader) => { + const name = reader.cstring(); + const tableID = reader.uint32(); + const columnID = reader.int16(); + const dataTypeID = reader.uint32(); + const dataTypeSize = reader.int16(); + const dataTypeModifier = reader.int32(); + const mode = reader.int16() === 0 ? 'text' : 'binary'; + return new messages_1.Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode); +}; +const parseParameterDescriptionMessage = (reader) => { + const parameterCount = reader.int16(); + const message = new messages_1.ParameterDescriptionMessage(LATEINIT_LENGTH, parameterCount); + for (let i = 0; i < parameterCount; i++) { + // OIDs are unsigned, same as dataTypeID in parseField above + message.dataTypeIDs[i] = reader.uint32(); + } + return message; +}; +const parseDataRowMessage = (reader) => { + const fieldCount = reader.int16(); + const fields = new Array(fieldCount); + for (let i = 0; i < fieldCount; i++) { + const len = reader.int32(); + // a -1 for length means the value of the field is null + fields[i] = len === -1 ? null : reader.string(len); + } + return new messages_1.DataRowMessage(LATEINIT_LENGTH, fields); +}; +const parseParameterStatusMessage = (reader) => { + const name = reader.cstring(); + const value = reader.cstring(); + return new messages_1.ParameterStatusMessage(LATEINIT_LENGTH, name, value); +}; +const parseBackendKeyData = (reader) => { + const processID = reader.int32(); + const secretKey = reader.int32(); + return new messages_1.BackendKeyDataMessage(LATEINIT_LENGTH, processID, secretKey); +}; +const parseAuthenticationResponse = (reader, length) => { + const code = reader.int32(); + // TODO(bmc): maybe better types here + const message = { + name: 'authenticationOk', + length, + }; + switch (code) { + case 0: // AuthenticationOk + break; + case 3: // AuthenticationCleartextPassword + if (message.length === 8) { + message.name = 'authenticationCleartextPassword'; + } + break; + case 5: // AuthenticationMD5Password + if (message.length === 12) { + message.name = 'authenticationMD5Password'; + const salt = reader.bytes(4); + return new messages_1.AuthenticationMD5Password(LATEINIT_LENGTH, salt); + } + break; + case 10: // AuthenticationSASL + { + message.name = 'authenticationSASL'; + message.mechanisms = []; + let mechanism; + do { + mechanism = reader.cstring(); + if (mechanism) { + message.mechanisms.push(mechanism); + } + } while (mechanism); + } + break; + case 11: // AuthenticationSASLContinue + message.name = 'authenticationSASLContinue'; + message.data = reader.string(length - 8); + break; + case 12: // AuthenticationSASLFinal + message.name = 'authenticationSASLFinal'; + message.data = reader.string(length - 8); + break; + default: + throw new Error('Unknown authenticationOk message type ' + code); + } + return message; +}; +const parseErrorMessage = (reader, name) => { + const fields = {}; + let fieldType = reader.string(1); + while (fieldType !== '\0') { + fields[fieldType] = reader.cstring(); + fieldType = reader.string(1); + } + const messageValue = fields.M; + const message = name === 'notice' + ? new messages_1.NoticeMessage(LATEINIT_LENGTH, messageValue) + : new messages_1.DatabaseError(messageValue, LATEINIT_LENGTH, name); + message.severity = fields.S; + message.code = fields.C; + message.detail = fields.D; + message.hint = fields.H; + message.position = fields.P; + message.internalPosition = fields.p; + message.internalQuery = fields.q; + message.where = fields.W; + message.schema = fields.s; + message.table = fields.t; + message.column = fields.c; + message.dataType = fields.d; + message.constraint = fields.n; + message.file = fields.F; + message.line = fields.L; + message.routine = fields.R; + return message; +}; +//# sourceMappingURL=parser.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/parser.js.map b/node_modules/pg-protocol/dist/parser.js.map new file mode 100644 index 0000000..ef0e267 --- /dev/null +++ b/node_modules/pg-protocol/dist/parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parser.js","sourceRoot":"","sources":["../src/parser.ts"],"names":[],"mappings":";;;AACA,yCA0BmB;AACnB,mDAA8C;AAE9C,+CAA+C;AAC/C,MAAM,WAAW,GAAG,CAAC,CAAA;AACrB,mEAAmE;AACnE,qCAAqC;AACrC,MAA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AC,OAAO,GAAG,MAAM,CAAC,CAAC,CAAA;IAC1B,OAAO,OAAO,CAAA;AAChB,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/serializer.d.ts b/node_modules/pg-protocol/dist/serializer.d.ts new file mode 100644 index 0000000..bf8e23c --- /dev/null +++ b/node_modules/pg-protocol/dist/serializer.d.ts @@ -0,0 +1,42 @@ +type ParseOpts = { + name?: string; + types?: number[]; + text: string; +}; +type ValueMapper = (param: any, index: number) => any; +type BindOpts = { + portal?: string; + binary?: boolean; + statement?: string; + values?: any[]; + valueMapper?: ValueMapper; +}; +type ExecOpts = { + portal?: string; + rows?: number; +}; +type PortalOpts = { + type: 'S' | 'P'; + name?: string; +}; +declare const serialize: { + startup: (opts: Record) => Buffer; + password: (password: string) => Buffer; + requestSsl: () => Buffer; + sendSASLInitialResponseMessage: (mechanism: string, initialResponse: string) => Buffer; + sendSCRAMClientFinalMessage: (additionalData: string) => Buffer; + query: (text: string) => Buffer; + parse: (query: ParseOpts) => Buffer; + bind: (config?: BindOpts) => Buffer; + execute: (config?: ExecOpts) => Buffer; + describe: (msg: PortalOpts) => Buffer; + close: (msg: PortalOpts) => Buffer; + flush: () => Buffer; + sync: () => Buffer; + end: () => Buffer; + copyData: (chunk: Buffer) => Buffer; + copyDone: () => Buffer; + copyFail: (message: string) => Buffer; + cancel: (processID: number, secretKey: number) => Buffer; +}; +export { serialize }; diff --git a/node_modules/pg-protocol/dist/serializer.js b/node_modules/pg-protocol/dist/serializer.js new file mode 100644 index 0000000..e857d7a --- /dev/null +++ b/node_modules/pg-protocol/dist/serializer.js @@ -0,0 +1,198 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.serialize = void 0; +const buffer_writer_1 = require("./buffer-writer"); +const writer = new buffer_writer_1.Writer(); +const startup = (opts) => { + // protocol version + writer.addInt16(3).addInt16(0); + for (const key of Object.keys(opts)) { + writer.addCString(key).addCString(opts[key]); + } + writer.addCString('client_encoding').addCString('UTF8'); + const bodyBuffer = writer.addCString('').flush(); + // this message is sent without a code + const length = bodyBuffer.length + 4; + return new buffer_writer_1.Writer().addInt32(length).add(bodyBuffer).flush(); +}; +const requestSsl = () => { + const response = Buffer.allocUnsafe(8); + response.writeInt32BE(8, 0); + response.writeInt32BE(80877103, 4); + return response; +}; +const password = (password) => { + return writer.addCString(password).flush(112 /* code.startup */); +}; +const sendSASLInitialResponseMessage = function (mechanism, initialResponse) { + // 0x70 = 'p' + writer.addCString(mechanism).addInt32PrefixedString(initialResponse); + return writer.flush(112 /* code.startup */); +}; +const sendSCRAMClientFinalMessage = function (additionalData) { + return writer.addString(additionalData).flush(112 /* code.startup */); +}; +const query = (text) => { + return writer.addCString(text).flush(81 /* code.query */); +}; +const emptyArray = []; +const parse = (query) => { + // expect something like this: + // { name: 'queryName', + // text: 'select * from blah', + // types: ['int8', 'bool'] } + // normalize missing query names to allow for null + const name = query.name || ''; + if (name.length > 63) { + console.error('Warning! Postgres only supports 63 characters for query names.'); + console.error('You supplied %s (%s)', name, name.length); + console.error('This can cause conflicts and silent errors executing queries'); + } + const types = query.types || emptyArray; + const len = types.length; + const buffer = writer + .addCString(name) // name of query + .addCString(query.text) // actual query text + .addInt16(len); + for (let i = 0; i < len; i++) { + buffer.addInt32(types[i]); + } + return writer.flush(80 /* code.parse */); +}; +const writeValues = function (values, valueMapper, formatsOffset) { + const len = values.length; + for (let i = 0; i < len; i++) { + const mappedVal = valueMapper ? valueMapper(values[i], i) : values[i]; + let formatByte = 0 /* ParamType.STRING */; + if (mappedVal == null) { + // write -1 to indicate null + writer.addInt32(-1); + } + else if (mappedVal instanceof Buffer) { + formatByte = 1 /* ParamType.BINARY */; + // add the buffer to the param writer + writer.addInt32(mappedVal.length); + writer.add(mappedVal); + } + else { + // length prefix + UTF-8 bytes in one pass (Buffer.byteLength computed once) + writer.addInt32PrefixedString(mappedVal); + } + // beware: `writer` operations can replace `writer.buffer` with a new buffer + const buf = writer.buffer; + buf[formatsOffset++] = 0; + buf[formatsOffset++] = formatByte; + } +}; +const bind = (config = {}) => { + // normalize config + const portal = config.portal || ''; + const statement = config.statement || ''; + const binary = config.binary || false; + const values = config.values || emptyArray; + const len = values.length; + writer.addCString(portal).addCString(statement); + // number of parameter format codes + writer.addInt16(len); + // space for those codes, filled by `writeValues` + const formatsOffset = writer.reserveUnsafe(len * 2); + // number of parameter values + writer.addInt16(len); + try { + writeValues(values, config.valueMapper, formatsOffset); + } + catch (err) { + writer.clear(); + throw err; + } + // all results use the same format code + writer.addInt16(1); + // format code + writer.addInt16(binary ? 1 /* ParamType.BINARY */ : 0 /* ParamType.STRING */); + return writer.flush(66 /* code.bind */); +}; +const emptyExecute = Buffer.from([69 /* code.execute */, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00]); +const execute = (config) => { + // this is the happy path for most queries + if (!config || (!config.portal && !config.rows)) { + return emptyExecute; + } + const portal = config.portal || ''; + const rows = config.rows || 0; + const portalLength = Buffer.byteLength(portal); + const len = 4 + portalLength + 1 + 4; + // one extra bit for code + const buff = Buffer.allocUnsafe(1 + len); + buff[0] = 69 /* code.execute */; + buff.writeInt32BE(len, 1); + buff.write(portal, 5, 'utf-8'); + buff[portalLength + 5] = 0; // null terminate portal cString + buff.writeUInt32BE(rows, buff.length - 4); + return buff; +}; +const cancel = (processID, secretKey) => { + const buffer = Buffer.allocUnsafe(16); + buffer.writeInt32BE(16, 0); + buffer.writeInt16BE(1234, 4); + buffer.writeInt16BE(5678, 6); + buffer.writeInt32BE(processID, 8); + buffer.writeInt32BE(secretKey, 12); + return buffer; +}; +const cstringMessage = (code, string) => { + const stringLen = Buffer.byteLength(string); + const len = 4 + stringLen + 1; + // one extra bit for code + const buffer = Buffer.allocUnsafe(1 + len); + buffer[0] = code; + buffer.writeInt32BE(len, 1); + buffer.write(string, 5, 'utf-8'); + buffer[len] = 0; // null terminate cString + return buffer; +}; +const emptyDescribePortal = writer.addCString('P').flush(68 /* code.describe */); +const emptyDescribeStatement = writer.addCString('S').flush(68 /* code.describe */); +const describe = (msg) => { + return msg.name + ? cstringMessage(68 /* code.describe */, `${msg.type}${msg.name || ''}`) + : msg.type === 'P' + ? emptyDescribePortal + : emptyDescribeStatement; +}; +const close = (msg) => { + const text = `${msg.type}${msg.name || ''}`; + return cstringMessage(67 /* code.close */, text); +}; +const copyData = (chunk) => { + return writer.add(chunk).flush(100 /* code.copyFromChunk */); +}; +const copyFail = (message) => { + return cstringMessage(102 /* code.copyFail */, message); +}; +const codeOnlyBuffer = (code) => Buffer.from([code, 0x00, 0x00, 0x00, 0x04]); +const flushBuffer = codeOnlyBuffer(72 /* code.flush */); +const syncBuffer = codeOnlyBuffer(83 /* code.sync */); +const endBuffer = codeOnlyBuffer(88 /* code.end */); +const copyDoneBuffer = codeOnlyBuffer(99 /* code.copyDone */); +const serialize = { + startup, + password, + requestSsl, + sendSASLInitialResponseMessage, + sendSCRAMClientFinalMessage, + query, + parse, + bind, + execute, + describe, + close, + flush: () => flushBuffer, + sync: () => syncBuffer, + end: () => endBuffer, + copyData, + copyDone: () => copyDoneBuffer, + copyFail, + cancel, +}; +exports.serialize = serialize; +//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/node_modules/pg-protocol/dist/serializer.js.map b/node_modules/pg-protocol/dist/serializer.js.map new file mode 100644 index 0000000..4e188d0 --- /dev/null +++ b/node_modules/pg-protocol/dist/serializer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"serializer.js","sourceRoot":"","sources":["../src/serializer.ts"],"names":[],"mappings":";;;AAAA,mDAAwC;AAkBxC,MAAM,MAAM,GAAG,IAAI,sBAAM,EAAE,CAAA;AAE3B,MAAM,OAAO,GAAG,CAAC,IAA4B,EAAU,EAAE;IACvD,mBAAmB;IACnB,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAA;IAC9B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,C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MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,KAAK,8BAAoB,CAAA;AACpD,CAAC,CAAA;AAED,MAAM,QAAQ,GAAG,CAAC,OAAe,EAAU,EAAE;IAC3C,OAAO,cAAc,0BAAgB,OAAO,CAAC,CAAA;AAC/C,CAAC,CAAA;AAED,MAAM,cAAc,GAAG,CAAC,IAAU,EAAU,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAA;AAE1F,MAAM,WAAW,GAAG,cAAc,qBAAY,CAAA;AAC9C,MAAM,UAAU,GAAG,cAAc,oBAAW,CAAA;AAC5C,MAAM,SAAS,GAAG,cAAc,mBAAU,CAAA;AAC1C,MAAM,cAAc,GAAG,cAAc,wBAAe,CAAA;AAEpD,MAAM,SAAS,GAAG;IAChB,OAAO;IACP,QAAQ;IACR,UAAU;IACV,8BAA8B;IAC9B,2BAA2B;IAC3B,KAAK;IACL,KAAK;IACL,IAAI;IACJ,OAAO;IACP,QAAQ;IACR,KAAK;IACL,KAAK,EAAE,GAAG,EAAE,CAAC,WAAW;IACxB,IAAI,EAAE,GAAG,EAAE,CAAC,UAAU;IACtB,GAAG,EAAE,GAAG,EAAE,CAAC,SAAS;IACpB,QAAQ;IACR,QAAQ,EAAE,GAAG,EAAE,CAAC,cAAc;IAC9B,QAAQ;IACR,MAAM;CACP,CAAA;AAEQ,8BAAS"} \ No newline at end of file diff --git a/node_modules/pg-protocol/esm/index.js b/node_modules/pg-protocol/esm/index.js new file mode 100644 index 0000000..c52807d --- /dev/null +++ b/node_modules/pg-protocol/esm/index.js @@ -0,0 +1,11 @@ +// ESM wrapper for pg-protocol +import * as protocol from '../dist/index.js' + +// Re-export all the properties +export const DatabaseError = protocol.DatabaseError +export const SASL = protocol.SASL +export const serialize = protocol.serialize +export const parse = protocol.parse + +// Re-export the default +export default protocol diff --git a/node_modules/pg-protocol/package.json b/node_modules/pg-protocol/package.json new file mode 100644 index 0000000..fedf6c3 --- /dev/null +++ b/node_modules/pg-protocol/package.json @@ -0,0 +1,44 @@ +{ + "name": "pg-protocol", + "version": "1.16.1", + "description": "The postgres client/server binary protocol, implemented in TypeScript", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "exports": { + ".": { + "import": "./esm/index.js", + "require": "./dist/index.js", + "default": "./dist/index.js" + }, + "./dist/*": "./dist/*.js", + "./dist/*.js": "./dist/*.js" + }, + "license": "MIT", + "devDependencies": { + "@types/chai": "^4.2.7", + "@types/mocha": "^10.0.10", + "@types/node": "^16", + "chai": "^4.2.0", + "mocha": "^11.7.5", + "ts-node": "^8.5.4", + "typescript": "^6.0.3" + }, + "scripts": { + "test": "mocha dist/**/*.test.js", + "build": "tsc", + "build:watch": "tsc --watch", + "prepublish": "yarn build", + "pretest": "yarn build" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianc/node-postgres.git", + "directory": "packages/pg-protocol" + }, + "files": [ + "/dist/*{js,ts,map}", + "/src", + "/esm" + ], + "gitHead": "0980cefebe0ae461da8883703be049fe13ca96cf" +} diff --git a/node_modules/pg-protocol/src/b.ts b/node_modules/pg-protocol/src/b.ts new file mode 100644 index 0000000..c8a2411 --- /dev/null +++ b/node_modules/pg-protocol/src/b.ts @@ -0,0 +1,25 @@ +// file for microbenchmarking + +import { BufferReader } from './buffer-reader' + +const LOOPS = 1000 +let count = 0 +const start = performance.now() + +const reader = new BufferReader() +const buffer = Buffer.from([33, 33, 33, 33, 33, 33, 33, 0]) + +const run = () => { + if (count > LOOPS) { + console.log(performance.now() - start) + return + } + count++ + for (let i = 0; i < LOOPS; i++) { + reader.setBuffer(0, buffer) + reader.cstring() + } + setImmediate(run) +} + +run() diff --git a/node_modules/pg-protocol/src/buffer-reader.ts b/node_modules/pg-protocol/src/buffer-reader.ts new file mode 100644 index 0000000..42a4a23 --- /dev/null +++ b/node_modules/pg-protocol/src/buffer-reader.ts @@ -0,0 +1,58 @@ +export class BufferReader { + private buffer: Buffer = Buffer.allocUnsafe(0) + + // TODO(bmc): support non-utf8 encoding? + private encoding: BufferEncoding = 'utf-8' + + constructor(private offset: number = 0) {} + + public setBuffer(offset: number, buffer: Buffer): void { + this.offset = offset + this.buffer = buffer + } + + public int16(): number { + const result = this.buffer.readInt16BE(this.offset) + this.offset += 2 + return result + } + + public byte(): number { + const result = this.buffer[this.offset] + this.offset++ + return result + } + + public int32(): number { + const result = this.buffer.readInt32BE(this.offset) + this.offset += 4 + return result + } + + public uint32(): number { + const result = this.buffer.readUInt32BE(this.offset) + this.offset += 4 + return result + } + + public string(length: number): string { + const result = this.buffer.toString(this.encoding, this.offset, this.offset + length) + this.offset += length + return result + } + + public cstring(): string { + const start = this.offset + let end = start + // eslint-disable-next-line no-empty + while (this.buffer[end++]) {} + this.offset = end + return this.buffer.toString(this.encoding, start, end - 1) + } + + public bytes(length: number): Buffer { + const result = this.buffer.slice(this.offset, this.offset + length) + this.offset += length + return result + } +} diff --git a/node_modules/pg-protocol/src/buffer-writer.ts b/node_modules/pg-protocol/src/buffer-writer.ts new file mode 100644 index 0000000..eb69cc8 --- /dev/null +++ b/node_modules/pg-protocol/src/buffer-writer.ts @@ -0,0 +1,120 @@ +//binary data writer tuned for encoding binary specific to the postgres binary protocol + +export class Writer { + public buffer: Buffer + private offset: number = 5 + private headerPosition: number = 0 + constructor(private size = 256) { + this.buffer = Buffer.allocUnsafe(size) + } + + private ensure(size: number): void { + const remaining = this.buffer.length - this.offset + if (remaining < size) { + const oldBuffer = this.buffer + // exponential growth factor of around ~ 1.5 + // https://stackoverflow.com/questions/2269063/buffer-growth-strategy + const newSize = oldBuffer.length + (oldBuffer.length >> 1) + size + this.buffer = Buffer.allocUnsafe(newSize) + oldBuffer.copy(this.buffer, 0, 0, this.offset) + } + } + + public addInt32(num: number): Writer { + this.ensure(4) + this.buffer[this.offset++] = (num >>> 24) & 0xff + this.buffer[this.offset++] = (num >>> 16) & 0xff + this.buffer[this.offset++] = (num >>> 8) & 0xff + this.buffer[this.offset++] = (num >>> 0) & 0xff + return this + } + + public addInt16(num: number): Writer { + this.ensure(2) + this.buffer[this.offset++] = (num >>> 8) & 0xff + this.buffer[this.offset++] = (num >>> 0) & 0xff + return this + } + + public addCString(string: string): Writer { + if (!string) { + this.ensure(1) + } else { + const len = Buffer.byteLength(string) + this.ensure(len + 1) // +1 for null terminator + this.buffer.write(string, this.offset, 'utf-8') + this.offset += len + } + + this.buffer[this.offset++] = 0 // null terminator + return this + } + + public addString(string: string = ''): Writer { + const len = Buffer.byteLength(string) + this.ensure(len) + this.buffer.write(string, this.offset) + this.offset += len + return this + } + + // Write an Int32 byte-length prefix immediately followed by the string's UTF-8 + // bytes. Postgres' Bind wire format prefixes every parameter with its length, + // and doing it in one method computes Buffer.byteLength ONCE — the previous + // `addInt32(Buffer.byteLength(s)).addString(s)` pairing scanned the string + // three times (byteLength for the prefix, byteLength again inside addString, + // then the encode), which is costly for large text parameters. + public addInt32PrefixedString(string: string): Writer { + const len = Buffer.byteLength(string) + this.ensure(4 + len) + const buffer = this.buffer + let offset = this.offset + buffer[offset++] = (len >>> 24) & 0xff + buffer[offset++] = (len >>> 16) & 0xff + buffer[offset++] = (len >>> 8) & 0xff + buffer[offset++] = (len >>> 0) & 0xff + buffer.write(string, offset, 'utf-8') + this.offset = offset + len + return this + } + + public add(otherBuffer: Buffer): Writer { + this.ensure(otherBuffer.length) + otherBuffer.copy(this.buffer, this.offset) + this.offset += otherBuffer.length + return this + } + + /** + * Appends an uninitialized block of {@link size} bytes to the buffer and returns its offset. + */ + public reserveUnsafe(size: number): number { + const offset = this.offset + this.ensure(size) + this.offset += size + return offset + } + + private join(code?: number): Buffer { + if (code) { + this.buffer[this.headerPosition] = code + //length is everything in this packet minus the code + const length = this.offset - (this.headerPosition + 1) + this.buffer.writeInt32BE(length, this.headerPosition + 1) + } + return this.buffer.slice(code ? 0 : 5, this.offset) + } + + public flush(code?: number): Buffer { + const result = this.join(code) + this.offset = 5 + this.headerPosition = 0 + this.buffer = Buffer.allocUnsafe(this.size) + return result + } + + public clear(): void { + this.offset = 5 + this.headerPosition = 0 + } +} diff --git a/node_modules/pg-protocol/src/inbound-parser.test.ts b/node_modules/pg-protocol/src/inbound-parser.test.ts new file mode 100644 index 0000000..8687194 --- /dev/null +++ b/node_modules/pg-protocol/src/inbound-parser.test.ts @@ -0,0 +1,585 @@ +import buffers from './testing/test-buffers' +import BufferList from './testing/buffer-list' +import { parse } from '.' +import assert from 'assert' +import { PassThrough } from 'stream' +import { BackendMessage } from './messages' +import { Parser } from './parser' + +const authOkBuffer = buffers.authenticationOk() +const paramStatusBuffer = buffers.parameterStatus('client_encoding', 'UTF8') +const readyForQueryBuffer = buffers.readyForQuery() +const backendKeyDataBuffer = buffers.backendKeyData(1, 2) +const commandCompleteBuffer = buffers.commandComplete('SELECT 3') +const parseCompleteBuffer = buffers.parseComplete() +const bindCompleteBuffer = buffers.bindComplete() +const portalSuspendedBuffer = buffers.portalSuspended() + +const row1 = { + name: 'id', + tableID: 1, + attributeNumber: 2, + dataTypeID: 3, + dataTypeSize: 4, + typeModifier: 5, + formatCode: 0, +} +const oneRowDescBuff = buffers.rowDescription([row1]) +row1.name = 'bang' + +const twoRowBuf = buffers.rowDescription([ + row1, + { + name: 'whoah', + tableID: 10, + attributeNumber: 11, + dataTypeID: 12, + dataTypeSize: 13, + typeModifier: 14, + formatCode: 0, + }, +]) + +const rowWithBigOids = { + name: 'bigoid', + tableID: 3000000001, + attributeNumber: 2, + dataTypeID: 3000000003, + dataTypeSize: 4, + typeModifier: 5, + formatCode: 0, +} +const bigOidDescBuff = buffers.rowDescription([rowWithBigOids]) + +const emptyRowFieldBuf = buffers.dataRow([]) + +const oneFieldBuf = buffers.dataRow(['test']) + +const expectedAuthenticationOkayMessage = { + name: 'authenticationOk', + length: 8, +} + +const expectedParameterStatusMessage = { + name: 'parameterStatus', + parameterName: 'client_encoding', + parameterValue: 'UTF8', + length: 25, +} + +const expectedBackendKeyDataMessage = { + name: 'backendKeyData', + processID: 1, + secretKey: 2, +} + +const expectedReadyForQueryMessage = { + name: 'readyForQuery', + length: 5, + status: 'I', +} + +const expectedCommandCompleteMessage = { + name: 'commandComplete', + length: 13, + text: 'SELECT 3', +} +const emptyRowDescriptionBuffer = new BufferList() + .addInt16(0) // number of fields + .join(true, 'T') + +const expectedEmptyRowDescriptionMessage = { + name: 'rowDescription', + length: 6, + fieldCount: 0, + fields: [], +} +const expectedOneRowMessage = { + name: 'rowDescription', + length: 27, + fieldCount: 1, + fields: [ + { + name: 'id', + tableID: 1, + columnID: 2, + dataTypeID: 3, + dataTypeSize: 4, + dataTypeModifier: 5, + format: 'text', + }, + ], +} + +const expectedTwoRowMessage = { + name: 'rowDescription', + length: 53, + fieldCount: 2, + fields: [ + { + name: 'bang', + tableID: 1, + columnID: 2, + dataTypeID: 3, + dataTypeSize: 4, + dataTypeModifier: 5, + format: 'text', + }, + { + name: 'whoah', + tableID: 10, + columnID: 11, + dataTypeID: 12, + dataTypeSize: 13, + dataTypeModifier: 14, + format: 'text', + }, + ], +} +const expectedBigOidMessage = { + name: 'rowDescription', + length: 31, + fieldCount: 1, + fields: [ + { + name: 'bigoid', + tableID: 3000000001, + columnID: 2, + dataTypeID: 3000000003, + dataTypeSize: 4, + dataTypeModifier: 5, + format: 'text', + }, + ], +} + +const emptyParameterDescriptionBuffer = new BufferList() + .addInt16(0) // number of parameters + .join(true, 't') + +const oneParameterDescBuf = buffers.parameterDescription([1111]) + +const twoParameterDescBuf = buffers.parameterDescription([2222, 3333]) + +const bigOidParameterDescBuf = buffers.parameterDescription([3000000003]) + +const expectedEmptyParameterDescriptionMessage = { + name: 'parameterDescription', + length: 6, + parameterCount: 0, + dataTypeIDs: [], +} + +const expectedOneParameterMessage = { + name: 'parameterDescription', + length: 10, + parameterCount: 1, + dataTypeIDs: [1111], +} + +const expectedTwoParameterMessage = { + name: 'parameterDescription', + length: 14, + parameterCount: 2, + dataTypeIDs: [2222, 3333], +} + +const expectedBigOidParameterMessage = { + name: 'parameterDescription', + length: 10, + parameterCount: 1, + dataTypeIDs: [3000000003], +} + +const testForMessage = function (buffer: Buffer, expectedMessage: any) { + it('receives and parses ' + expectedMessage.name, async () => { + const messages = await parseBuffers([buffer]) + const [lastMessage] = messages + + for (const key in expectedMessage) { + assert.deepEqual((lastMessage as any)[key], expectedMessage[key]) + } + }) +} + +const plainPasswordBuffer = buffers.authenticationCleartextPassword() +const md5PasswordBuffer = buffers.authenticationMD5Password() +const SASLBuffer = buffers.authenticationSASL() +const SASLContinueBuffer = buffers.authenticationSASLContinue() +const SASLFinalBuffer = buffers.authenticationSASLFinal() + +const expectedPlainPasswordMessage = { + name: 'authenticationCleartextPassword', +} + +const expectedMD5PasswordMessage = { + name: 'authenticationMD5Password', + salt: Buffer.from([1, 2, 3, 4]), +} + +const expectedSASLMessage = { + name: 'authenticationSASL', + mechanisms: ['SCRAM-SHA-256'], +} + +const expectedSASLContinueMessage = { + name: 'authenticationSASLContinue', + data: 'data', +} + +const expectedSASLFinalMessage = { + name: 'authenticationSASLFinal', + data: 'data', +} + +const notificationResponseBuffer = buffers.notification(4, 'hi', 'boom') +const expectedNotificationResponseMessage = { + name: 'notification', + processId: 4, + channel: 'hi', + payload: 'boom', +} + +const parseBuffers = async (buffers: Buffer[]): Promise => { + const stream = new PassThrough() + for (const buffer of buffers) { + stream.write(buffer) + } + stream.end() + const msgs: BackendMessage[] = [] + await parse(stream, (msg) => msgs.push(msg)) + return msgs +} + +describe('PgPacketStream', function () { + testForMessage(authOkBuffer, expectedAuthenticationOkayMessage) + testForMessage(plainPasswordBuffer, expectedPlainPasswordMessage) + testForMessage(md5PasswordBuffer, expectedMD5PasswordMessage) + testForMessage(SASLBuffer, expectedSASLMessage) + testForMessage(SASLContinueBuffer, expectedSASLContinueMessage) + + // this exercises a found bug in the parser: + // https://github.com/brianc/node-postgres/pull/2210#issuecomment-627626084 + // and adds a test which is deterministic, rather than relying on network packet chunking + const extendedSASLContinueBuffer = Buffer.concat([SASLContinueBuffer, Buffer.from([1, 2, 3, 4])]) + testForMessage(extendedSASLContinueBuffer, expectedSASLContinueMessage) + + testForMessage(SASLFinalBuffer, expectedSASLFinalMessage) + + // this exercises a found bug in the parser: + // https://github.com/brianc/node-postgres/pull/2210#issuecomment-627626084 + // and adds a test which is deterministic, rather than relying on network packet chunking + const extendedSASLFinalBuffer = Buffer.concat([SASLFinalBuffer, Buffer.from([1, 2, 4, 5])]) + testForMessage(extendedSASLFinalBuffer, expectedSASLFinalMessage) + + testForMessage(paramStatusBuffer, expectedParameterStatusMessage) + testForMessage(backendKeyDataBuffer, expectedBackendKeyDataMessage) + testForMessage(readyForQueryBuffer, expectedReadyForQueryMessage) + testForMessage(commandCompleteBuffer, expectedCommandCompleteMessage) + testForMessage(notificationResponseBuffer, expectedNotificationResponseMessage) + testForMessage(buffers.emptyQuery(), { + name: 'emptyQuery', + length: 4, + }) + + testForMessage(Buffer.from([0x6e, 0, 0, 0, 4]), { + name: 'noData', + }) + + describe('rowDescription messages', function () { + testForMessage(emptyRowDescriptionBuffer, expectedEmptyRowDescriptionMessage) + testForMessage(oneRowDescBuff, expectedOneRowMessage) + testForMessage(twoRowBuf, expectedTwoRowMessage) + testForMessage(bigOidDescBuff, expectedBigOidMessage) + }) + + describe('parameterDescription messages', function () { + testForMessage(emptyParameterDescriptionBuffer, expectedEmptyParameterDescriptionMessage) + testForMessage(oneParameterDescBuf, expectedOneParameterMessage) + testForMessage(twoParameterDescBuf, expectedTwoParameterMessage) + testForMessage(bigOidParameterDescBuf, expectedBigOidParameterMessage) + }) + + describe('parsing rows', function () { + describe('parsing empty row', function () { + testForMessage(emptyRowFieldBuf, { + name: 'dataRow', + fieldCount: 0, + }) + }) + + describe('parsing data row with fields', function () { + testForMessage(oneFieldBuf, { + name: 'dataRow', + fieldCount: 1, + fields: ['test'], + }) + }) + }) + + describe('notice message', function () { + // this uses the same logic as error message + const buff = buffers.notice([{ type: 'C', value: 'code' }]) + testForMessage(buff, { + name: 'notice', + code: 'code', + }) + }) + + testForMessage(buffers.error([]), { + name: 'error', + }) + + describe('with all the fields', function () { + const buffer = buffers.error([ + { + type: 'S', + value: 'ERROR', + }, + { + type: 'C', + value: 'code', + }, + { + type: 'M', + value: 'message', + }, + { + type: 'D', + value: 'details', + }, + { + type: 'H', + value: 'hint', + }, + { + type: 'P', + value: '100', + }, + { + type: 'p', + value: '101', + }, + { + type: 'q', + value: 'query', + }, + { + type: 'W', + value: 'where', + }, + { + type: 'F', + value: 'file', + }, + { + type: 'L', + value: 'line', + }, + { + type: 'R', + value: 'routine', + }, + { + type: 'Z', // ignored + value: 'alsdkf', + }, + ]) + + testForMessage(buffer, { + name: 'error', + severity: 'ERROR', + code: 'code', + message: 'message', + detail: 'details', + hint: 'hint', + position: '100', + internalPosition: '101', + internalQuery: 'query', + where: 'where', + file: 'file', + line: 'line', + routine: 'routine', + }) + }) + + testForMessage(parseCompleteBuffer, { + name: 'parseComplete', + }) + + testForMessage(bindCompleteBuffer, { + name: 'bindComplete', + }) + + testForMessage(bindCompleteBuffer, { + name: 'bindComplete', + }) + + testForMessage(buffers.closeComplete(), { + name: 'closeComplete', + }) + + describe('parses portal suspended message', function () { + testForMessage(portalSuspendedBuffer, { + name: 'portalSuspended', + }) + }) + + describe('parses replication start message', function () { + testForMessage(Buffer.from([0x57, 0x00, 0x00, 0x00, 0x04]), { + name: 'replicationStart', + length: 4, + }) + }) + + describe('copy', () => { + testForMessage(buffers.copyIn(0), { + name: 'copyInResponse', + length: 7, + binary: false, + columnTypes: [], + }) + + testForMessage(buffers.copyIn(2), { + name: 'copyInResponse', + length: 11, + binary: false, + columnTypes: [0, 1], + }) + + testForMessage(buffers.copyOut(0), { + name: 'copyOutResponse', + length: 7, + binary: false, + columnTypes: [], + }) + + testForMessage(buffers.copyOut(3), { + name: 'copyOutResponse', + length: 13, + binary: false, + columnTypes: [0, 1, 2], + }) + + testForMessage(buffers.copyDone(), { + name: 'copyDone', + length: 4, + }) + + testForMessage(buffers.copyData(Buffer.from([5, 6, 7])), { + name: 'copyData', + length: 7, + chunk: Buffer.from([5, 6, 7]), + }) + }) + + // since the data message on a stream can randomly divide the incomming + // tcp packets anywhere, we need to make sure we can parse every single + // split on a tcp message + describe('split buffer, single message parsing', function () { + const fullBuffer = buffers.dataRow([null, 'bang', 'zug zug', null, '!']) + + it('parses when full buffer comes in', async function () { + const messages = await parseBuffers([fullBuffer]) + const message = messages[0] as any + assert.equal(message.fields.length, 5) + assert.equal(message.fields[0], null) + assert.equal(message.fields[1], 'bang') + assert.equal(message.fields[2], 'zug zug') + assert.equal(message.fields[3], null) + assert.equal(message.fields[4], '!') + }) + + const testMessageReceivedAfterSplitAt = async function (split: number) { + const firstBuffer = Buffer.alloc(fullBuffer.length - split) + const secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length) + fullBuffer.copy(firstBuffer, 0, 0) + fullBuffer.copy(secondBuffer, 0, firstBuffer.length) + const messages = await parseBuffers([firstBuffer, secondBuffer]) + const message = messages[0] as any + assert.equal(message.fields.length, 5) + assert.equal(message.fields[0], null) + assert.equal(message.fields[1], 'bang') + assert.equal(message.fields[2], 'zug zug') + assert.equal(message.fields[3], null) + assert.equal(message.fields[4], '!') + } + + it('parses when split in the middle', function () { + return testMessageReceivedAfterSplitAt(6) + }) + + it('parses when split at end', function () { + return testMessageReceivedAfterSplitAt(2) + }) + + it('parses when split at beginning', function () { + return Promise.all([ + testMessageReceivedAfterSplitAt(fullBuffer.length - 2), + testMessageReceivedAfterSplitAt(fullBuffer.length - 1), + testMessageReceivedAfterSplitAt(fullBuffer.length - 5), + ]) + }) + }) + + describe('split buffer, multiple message parsing', function () { + const dataRowBuffer = buffers.dataRow(['!']) + const readyForQueryBuffer = buffers.readyForQuery() + const fullBuffer = Buffer.alloc(dataRowBuffer.length + readyForQueryBuffer.length) + dataRowBuffer.copy(fullBuffer, 0, 0) + readyForQueryBuffer.copy(fullBuffer, dataRowBuffer.length, 0) + + const verifyMessages = function (messages: any[]) { + assert.strictEqual(messages.length, 2) + assert.deepEqual(messages[0], { + name: 'dataRow', + fieldCount: 1, + length: 11, + fields: ['!'], + }) + assert.equal(messages[0].fields[0], '!') + assert.deepEqual(messages[1], { + name: 'readyForQuery', + length: 5, + status: 'I', + }) + } + // sanity check + it('receives both messages when packet is not split', async function () { + const messages = await parseBuffers([fullBuffer]) + verifyMessages(messages) + }) + + const splitAndVerifyTwoMessages = async function (split: number) { + const firstBuffer = Buffer.alloc(fullBuffer.length - split) + const secondBuffer = Buffer.alloc(fullBuffer.length - firstBuffer.length) + fullBuffer.copy(firstBuffer, 0, 0) + fullBuffer.copy(secondBuffer, 0, firstBuffer.length) + const messages = await parseBuffers([firstBuffer, secondBuffer]) + verifyMessages(messages) + } + + describe('receives both messages when packet is split', function () { + it('in the middle', function () { + return splitAndVerifyTwoMessages(11) + }) + it('at the front', function () { + return Promise.all([ + splitAndVerifyTwoMessages(fullBuffer.length - 1), + splitAndVerifyTwoMessages(fullBuffer.length - 4), + splitAndVerifyTwoMessages(fullBuffer.length - 6), + ]) + }) + + it('at the end', function () { + return Promise.all([splitAndVerifyTwoMessages(8), splitAndVerifyTwoMessages(1)]) + }) + }) + }) + + it('cleans up the reader after handling a packet', function () { + const parser = new Parser() + parser.parse(oneFieldBuf, () => {}) + assert.strictEqual((parser as any).reader.buffer.byteLength, 0) + }) +}) diff --git a/node_modules/pg-protocol/src/index.ts b/node_modules/pg-protocol/src/index.ts new file mode 100644 index 0000000..703ff2e --- /dev/null +++ b/node_modules/pg-protocol/src/index.ts @@ -0,0 +1,11 @@ +import { DatabaseError } from './messages' +import { serialize } from './serializer' +import { Parser, MessageCallback } from './parser' + +export function parse(stream: NodeJS.ReadableStream, callback: MessageCallback): Promise { + const parser = new Parser() + stream.on('data', (buffer: Buffer) => parser.parse(buffer, callback)) + return new Promise((resolve) => stream.on('end', () => resolve())) +} + +export { serialize, DatabaseError } diff --git a/node_modules/pg-protocol/src/messages.ts b/node_modules/pg-protocol/src/messages.ts new file mode 100644 index 0000000..c3fbbdd --- /dev/null +++ b/node_modules/pg-protocol/src/messages.ts @@ -0,0 +1,262 @@ +export type Mode = 'text' | 'binary' + +export type MessageName = + | 'parseComplete' + | 'bindComplete' + | 'closeComplete' + | 'noData' + | 'portalSuspended' + | 'replicationStart' + | 'emptyQuery' + | 'copyDone' + | 'copyData' + | 'rowDescription' + | 'parameterDescription' + | 'parameterStatus' + | 'backendKeyData' + | 'notification' + | 'readyForQuery' + | 'commandComplete' + | 'dataRow' + | 'copyInResponse' + | 'copyOutResponse' + | 'authenticationOk' + | 'authenticationMD5Password' + | 'authenticationCleartextPassword' + | 'authenticationSASL' + | 'authenticationSASLContinue' + | 'authenticationSASLFinal' + | 'error' + | 'notice' + +export interface BackendMessage { + name: MessageName + length: number +} + +export const parseComplete: BackendMessage = { + name: 'parseComplete', + length: 5, +} + +export const bindComplete: BackendMessage = { + name: 'bindComplete', + length: 5, +} + +export const closeComplete: BackendMessage = { + name: 'closeComplete', + length: 5, +} + +export const noData: BackendMessage = { + name: 'noData', + length: 5, +} + +export const portalSuspended: BackendMessage = { + name: 'portalSuspended', + length: 5, +} + +export const replicationStart: BackendMessage = { + name: 'replicationStart', + length: 4, +} + +export const emptyQuery: BackendMessage = { + name: 'emptyQuery', + length: 4, +} + +export const copyDone: BackendMessage = { + name: 'copyDone', + length: 4, +} + +interface NoticeOrError { + message: string | undefined + severity: string | undefined + code: string | undefined + detail: string | undefined + hint: string | undefined + position: string | undefined + internalPosition: string | undefined + internalQuery: string | undefined + where: string | undefined + schema: string | undefined + table: string | undefined + column: string | undefined + dataType: string | undefined + constraint: string | undefined + file: string | undefined + line: string | undefined + routine: string | undefined +} + +export class DatabaseError extends Error implements NoticeOrError { + public severity: string | undefined + public code: string | undefined + public detail: string | undefined + public hint: string | undefined + public position: string | undefined + public internalPosition: string | undefined + public internalQuery: string | undefined + public where: string | undefined + public schema: string | undefined + public table: string | undefined + public column: string | undefined + public dataType: string | undefined + public constraint: string | undefined + public file: string | undefined + public line: string | undefined + public routine: string | undefined + constructor( + message: string, + public readonly length: number, + public readonly name: MessageName + ) { + super(message) + } +} + +export class CopyDataMessage { + public readonly name = 'copyData' + constructor( + public readonly length: number, + public readonly chunk: Buffer + ) {} +} + +export class CopyResponse { + public readonly columnTypes: number[] + constructor( + public readonly length: number, + public readonly name: MessageName, + public readonly binary: boolean, + columnCount: number + ) { + this.columnTypes = new Array(columnCount) + } +} + +export class Field { + constructor( + public readonly name: string, + public readonly tableID: number, + public readonly columnID: number, + public readonly dataTypeID: number, + public readonly dataTypeSize: number, + public readonly dataTypeModifier: number, + public readonly format: Mode + ) {} +} + +export class RowDescriptionMessage { + public readonly name: MessageName = 'rowDescription' + public readonly fields: Field[] + constructor( + public readonly length: number, + public readonly fieldCount: number + ) { + this.fields = new Array(this.fieldCount) + } +} + +export class ParameterDescriptionMessage { + public readonly name: MessageName = 'parameterDescription' + public readonly dataTypeIDs: number[] + constructor( + public readonly length: number, + public readonly parameterCount: number + ) { + this.dataTypeIDs = new Array(this.parameterCount) + } +} + +export class ParameterStatusMessage { + public readonly name: MessageName = 'parameterStatus' + constructor( + public readonly length: number, + public readonly parameterName: string, + public readonly parameterValue: string + ) {} +} + +export class AuthenticationMD5Password implements BackendMessage { + public readonly name: MessageName = 'authenticationMD5Password' + constructor( + public readonly length: number, + public readonly salt: Buffer + ) {} +} + +export class BackendKeyDataMessage { + public readonly name: MessageName = 'backendKeyData' + constructor( + public readonly length: number, + public readonly processID: number, + public readonly secretKey: number + ) {} +} + +export class NotificationResponseMessage { + public readonly name: MessageName = 'notification' + constructor( + public readonly length: number, + public readonly processId: number, + public readonly channel: string, + public readonly payload: string + ) {} +} + +export class ReadyForQueryMessage { + public readonly name: MessageName = 'readyForQuery' + constructor( + public readonly length: number, + public readonly status: string + ) {} +} + +export class CommandCompleteMessage { + public readonly name: MessageName = 'commandComplete' + constructor( + public readonly length: number, + public readonly text: string + ) {} +} + +export class DataRowMessage { + public readonly fieldCount: number + public readonly name: MessageName = 'dataRow' + constructor( + public length: number, + public fields: any[] + ) { + this.fieldCount = fields.length + } +} + +export class NoticeMessage implements BackendMessage, NoticeOrError { + constructor( + public readonly length: number, + public readonly message: string | undefined + ) {} + public readonly name = 'notice' + public severity: string | undefined + public code: string | undefined + public detail: string | undefined + public hint: string | undefined + public position: string | undefined + public internalPosition: string | undefined + public internalQuery: string | undefined + public where: string | undefined + public schema: string | undefined + public table: string | undefined + public column: string | undefined + public dataType: string | undefined + public constraint: string | undefined + public file: string | undefined + public line: string | undefined + public routine: string | undefined +} diff --git a/node_modules/pg-protocol/src/outbound-serializer.test.ts b/node_modules/pg-protocol/src/outbound-serializer.test.ts new file mode 100644 index 0000000..aac0c57 --- /dev/null +++ b/node_modules/pg-protocol/src/outbound-serializer.test.ts @@ -0,0 +1,356 @@ +import assert from 'assert' +import { serialize } from './serializer' +import BufferList from './testing/buffer-list' + +describe('serializer', () => { + it('builds startup message', function () { + const actual = serialize.startup({ + user: 'brian', + database: 'bang', + }) + assert.deepEqual( + actual, + new BufferList() + .addInt16(3) + .addInt16(0) + .addCString('user') + .addCString('brian') + .addCString('database') + .addCString('bang') + .addCString('client_encoding') + .addCString('UTF8') + .addCString('') + .join(true) + ) + }) + + it('builds password message', function () { + const actual = serialize.password('!') + assert.deepEqual(actual, new BufferList().addCString('!').join(true, 'p')) + }) + + it('builds request ssl message', function () { + const actual = serialize.requestSsl() + const expected = new BufferList().addInt32(80877103).join(true) + assert.deepEqual(actual, expected) + }) + + it('builds SASLInitialResponseMessage message', function () { + const actual = serialize.sendSASLInitialResponseMessage('mech', 'data') + assert.deepEqual(actual, new BufferList().addCString('mech').addInt32(4).addString('data').join(true, 'p')) + }) + + it('builds SCRAMClientFinalMessage message', function () { + const actual = serialize.sendSCRAMClientFinalMessage('data') + assert.deepEqual(actual, new BufferList().addString('data').join(true, 'p')) + }) + + it('builds query message', function () { + const txt = 'select * from boom' + const actual = serialize.query(txt) + assert.deepEqual(actual, new BufferList().addCString(txt).join(true, 'Q')) + }) + + describe('parse message', () => { + it('builds parse message', function () { + const actual = serialize.parse({ text: '!' }) + const expected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P') + assert.deepEqual(actual, expected) + }) + + it('builds parse message with named query', function () { + const actual = serialize.parse({ + name: 'boom', + text: 'select * from boom', + types: [], + }) + const expected = new BufferList().addCString('boom').addCString('select * from boom').addInt16(0).join(true, 'P') + assert.deepEqual(actual, expected) + }) + + it('with multiple parameters', function () { + const actual = serialize.parse({ + name: 'force', + text: 'select * from bang where name = $1', + types: [1, 2, 3, 4], + }) + const expected = new BufferList() + .addCString('force') + .addCString('select * from bang where name = $1') + .addInt16(4) + .addInt32(1) + .addInt32(2) + .addInt32(3) + .addInt32(4) + .join(true, 'P') + assert.deepEqual(actual, expected) + }) + }) + + describe('bind messages', function () { + it('with no values', function () { + const actual = serialize.bind() + + const expectedBuffer = new BufferList() + .addCString('') + .addCString('') + .addInt16(0) + .addInt16(0) + .addInt16(1) + .addInt16(0) + .join(true, 'B') + assert.deepEqual(actual, expectedBuffer) + }) + + it('with named statement, portal, and values', function () { + const actual = serialize.bind({ + portal: 'bang', + statement: 'woo', + values: ['1', 'hi', null, 'zing'], + }) + const expectedBuffer = new BufferList() + .addCString('bang') // portal name + .addCString('woo') // statement name + .addInt16(4) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(4) + .addInt32(1) + .add(Buffer.from('1')) + .addInt32(2) + .add(Buffer.from('hi')) + .addInt32(-1) + .addInt32(4) + .add(Buffer.from('zing')) + .addInt16(1) + .addInt16(0) + .join(true, 'B') + assert.deepEqual(actual, expectedBuffer) + }) + + it('encodes a multi-byte string param with its UTF-8 byte length, not char length', function () { + // Guards the single-pass addInt32PrefixedString write path: the Int32 + // length prefix must be the UTF-8 byte count, not String.length. 'héllo中🎉' + // is 7 code points / 8 UTF-16 code units but 13 UTF-8 bytes. + const value = 'héllo中🎉' + const bytes = Buffer.from(value, 'utf8') + assert.notEqual(bytes.length, value.length) // sanity: the divergence we're testing + const actual = serialize.bind({ values: [value] }) + const expectedBuffer = new BufferList() + .addCString('') // portal + .addCString('') // statement + .addInt16(1) // param format code count + .addInt16(0) // format code for the one value (text) + .addInt16(1) // value count + .addInt32(bytes.length) // 13 — the UTF-8 byte length, NOT value.length (8) + .add(bytes) + .addInt16(1) // result format code count + .addInt16(0) // result format (text) + .join(true, 'B') + assert.deepEqual(actual, expectedBuffer) + }) + }) + + it('with custom valueMapper', function () { + const actual = serialize.bind({ + portal: 'bang', + statement: 'woo', + values: ['1', 'hi', null, 'zing'], + valueMapper: () => null, + }) + const expectedBuffer = new BufferList() + .addCString('bang') // portal name + .addCString('woo') // statement name + .addInt16(4) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(4) + .addInt32(-1) + .addInt32(-1) + .addInt32(-1) + .addInt32(-1) + .addInt16(1) + .addInt16(0) + .join(true, 'B') + assert.deepEqual(actual, expectedBuffer) + }) + + it('with named statement, portal, and buffer value', function () { + const actual = serialize.bind({ + portal: 'bang', + statement: 'woo', + values: ['1', 'hi', null, Buffer.from('zing', 'utf8')], + }) + const expectedBuffer = new BufferList() + .addCString('bang') // portal name + .addCString('woo') // statement name + .addInt16(4) // value count + .addInt16(0) // string + .addInt16(0) // string + .addInt16(0) // string + .addInt16(1) // binary + .addInt16(4) + .addInt32(1) + .add(Buffer.from('1')) + .addInt32(2) + .add(Buffer.from('hi')) + .addInt32(-1) + .addInt32(4) + .add(Buffer.from('zing', 'utf-8')) + .addInt16(1) + .addInt16(0) + .join(true, 'B') + assert.deepEqual(actual, expectedBuffer) + }) + + describe('builds execute message', function () { + it('for unamed portal with no row limit', function () { + const actual = serialize.execute() + const expectedBuffer = new BufferList().addCString('').addInt32(0).join(true, 'E') + assert.deepEqual(actual, expectedBuffer) + }) + + it('for named portal with row limit', function () { + const actual = serialize.execute({ + portal: 'my favorite portal', + rows: 100, + }) + const expectedBuffer = new BufferList().addCString('my favorite portal').addInt32(100).join(true, 'E') + assert.deepEqual(actual, expectedBuffer) + }) + }) + + it('builds flush command', function () { + const actual = serialize.flush() + const expected = new BufferList().join(true, 'H') + assert.deepEqual(actual, expected) + }) + + it('builds sync command', function () { + const actual = serialize.sync() + const expected = new BufferList().join(true, 'S') + assert.deepEqual(actual, expected) + }) + + it('builds end command', function () { + const actual = serialize.end() + const expected = Buffer.from([0x58, 0, 0, 0, 4]) + assert.deepEqual(actual, expected) + }) + + describe('builds describe command', function () { + it('describe statement', function () { + const actual = serialize.describe({ type: 'S', name: 'bang' }) + const expected = new BufferList().addChar('S').addCString('bang').join(true, 'D') + assert.deepEqual(actual, expected) + }) + + it('describe unnamed portal', function () { + const actual = serialize.describe({ type: 'P' }) + const expected = new BufferList().addChar('P').addCString('').join(true, 'D') + assert.deepEqual(actual, expected) + }) + }) + + describe('builds close command', function () { + it('describe statement', function () { + const actual = serialize.close({ type: 'S', name: 'bang' }) + const expected = new BufferList().addChar('S').addCString('bang').join(true, 'C') + assert.deepEqual(actual, expected) + }) + + it('describe unnamed portal', function () { + const actual = serialize.close({ type: 'P' }) + const expected = new BufferList().addChar('P').addCString('').join(true, 'C') + assert.deepEqual(actual, expected) + }) + }) + + describe('copy messages', function () { + it('builds copyFromChunk', () => { + const actual = serialize.copyData(Buffer.from([1, 2, 3])) + const expected = new BufferList().add(Buffer.from([1, 2, 3])).join(true, 'd') + assert.deepEqual(actual, expected) + }) + + it('builds copy fail', () => { + const actual = serialize.copyFail('err!') + const expected = new BufferList().addCString('err!').join(true, 'f') + assert.deepEqual(actual, expected) + }) + + it('builds copy done', () => { + const actual = serialize.copyDone() + const expected = new BufferList().join(true, 'c') + assert.deepEqual(actual, expected) + }) + }) + + it('builds cancel message', () => { + const actual = serialize.cancel(3, 4) + const expected = new BufferList().addInt16(1234).addInt16(5678).addInt32(3).addInt32(4).join(true) + assert.deepEqual(actual, expected) + }) + + describe('bind error recovery', () => { + const throwingMapper = () => { + throw new Error('valueMapper error') + } + + it('produces correct bind output after a valueMapper exception', () => { + assert.throws(() => { + serialize.bind({ + values: ['fail'], + valueMapper: throwingMapper, + }) + }, /valueMapper error/) + + const actual = serialize.bind({ + portal: 'bang', + statement: 'woo', + values: ['1', 'hi', null, 'zing'], + }) + const expectedBuffer = new BufferList() + .addCString('bang') + .addCString('woo') + .addInt16(4) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(0) + .addInt16(4) + .addInt32(1) + .add(Buffer.from('1')) + .addInt32(2) + .add(Buffer.from('hi')) + .addInt32(-1) + .addInt32(4) + .add(Buffer.from('zing')) + .addInt16(1) + .addInt16(0) + .join(true, 'B') + assert.deepEqual(actual, expectedBuffer) + }) + + it('produces correct output from other serializer methods after a failed bind', () => { + assert.throws(() => { + serialize.bind({ + values: ['fail'], + valueMapper: throwingMapper, + }) + }, /valueMapper error/) + + const parseActual = serialize.parse({ text: '!' }) + const parseExpected = new BufferList().addCString('').addCString('!').addInt16(0).join(true, 'P') + assert.deepEqual(parseActual, parseExpected) + + const queryActual = serialize.query('select 1') + const queryExpected = new BufferList().addCString('select 1').join(true, 'Q') + assert.deepEqual(queryActual, queryExpected) + }) + }) +}) diff --git a/node_modules/pg-protocol/src/parser.ts b/node_modules/pg-protocol/src/parser.ts new file mode 100644 index 0000000..df48ca4 --- /dev/null +++ b/node_modules/pg-protocol/src/parser.ts @@ -0,0 +1,414 @@ +import { TransformOptions } from 'stream' +import { + Mode, + bindComplete, + parseComplete, + closeComplete, + noData, + portalSuspended, + copyDone, + replicationStart, + emptyQuery, + ReadyForQueryMessage, + CommandCompleteMessage, + CopyDataMessage, + CopyResponse, + NotificationResponseMessage, + RowDescriptionMessage, + ParameterDescriptionMessage, + Field, + DataRowMessage, + ParameterStatusMessage, + BackendKeyDataMessage, + DatabaseError, + BackendMessage, + MessageName, + AuthenticationMD5Password, + NoticeMessage, +} from './messages' +import { BufferReader } from './buffer-reader' + +// every message is prefixed with a single byte +const CODE_LENGTH = 1 +// every message has an int32 length which includes itself but does +// NOT include the code in the length +const LEN_LENGTH = 4 + +const HEADER_LENGTH = CODE_LENGTH + LEN_LENGTH + +// A placeholder for a `BackendMessage`’s length value that will be set after construction. +const LATEINIT_LENGTH = -1 + +export type Packet = { + code: number + packet: Buffer +} + +const emptyBuffer = Buffer.allocUnsafe(0) + +type StreamOptions = TransformOptions & { + mode: Mode +} + +const enum MessageCodes { + DataRow = 0x44, // D + ParseComplete = 0x31, // 1 + BindComplete = 0x32, // 2 + CloseComplete = 0x33, // 3 + CommandComplete = 0x43, // C + ReadyForQuery = 0x5a, // Z + NoData = 0x6e, // n + NotificationResponse = 0x41, // A + AuthenticationResponse = 0x52, // R + ParameterStatus = 0x53, // S + BackendKeyData = 0x4b, // K + ErrorMessage = 0x45, // E + NoticeMessage = 0x4e, // N + RowDescriptionMessage = 0x54, // T + ParameterDescriptionMessage = 0x74, // t + PortalSuspended = 0x73, // s + ReplicationStart = 0x57, // W + EmptyQuery = 0x49, // I + CopyIn = 0x47, // G + CopyOut = 0x48, // H + CopyDone = 0x63, // c + CopyData = 0x64, // d +} + +export type MessageCallback = (msg: BackendMessage) => void + +export class Parser { + private buffer: Buffer = emptyBuffer + private bufferLength: number = 0 + private bufferOffset: number = 0 + private reader = new BufferReader() + private mode: Mode + + constructor(opts?: StreamOptions) { + if (opts?.mode === 'binary') { + throw new Error('Binary mode not supported yet') + } + this.mode = opts?.mode || 'text' + } + + public parse(buffer: Buffer, callback: MessageCallback) { + this.mergeBuffer(buffer) + const bufferFullLength = this.bufferOffset + this.bufferLength + let offset = this.bufferOffset + while (offset + HEADER_LENGTH <= bufferFullLength) { + // code is 1 byte long - it identifies the message type + const code = this.buffer[offset] + // length is 1 Uint32BE - it is the length of the message EXCLUDING the code + const length = this.buffer.readUInt32BE(offset + CODE_LENGTH) + const fullMessageLength = CODE_LENGTH + length + if (fullMessageLength + offset <= bufferFullLength) { + const message = this.handlePacket(offset + HEADER_LENGTH, code, length, this.buffer) + callback(message) + offset += fullMessageLength + } else { + break + } + } + if (offset === bufferFullLength) { + // No more use for the buffer + this.buffer = emptyBuffer + this.bufferLength = 0 + this.bufferOffset = 0 + } else { + // Adjust the cursors of remainingBuffer + this.bufferLength = bufferFullLength - offset + this.bufferOffset = offset + } + } + + private mergeBuffer(buffer: Buffer): void { + if (this.bufferLength > 0) { + const newLength = this.bufferLength + buffer.byteLength + const newFullLength = newLength + this.bufferOffset + if (newFullLength > this.buffer.byteLength) { + // We can't concat the new buffer with the remaining one + let newBuffer: Buffer + if (newLength <= this.buffer.byteLength && this.bufferOffset >= this.bufferLength) { + // We can move the relevant part to the beginning of the buffer instead of allocating a new buffer + newBuffer = this.buffer + } else { + // Allocate a new larger buffer + let newBufferLength = this.buffer.byteLength * 2 + while (newLength >= newBufferLength) { + newBufferLength *= 2 + } + newBuffer = Buffer.allocUnsafe(newBufferLength) + } + // Move the remaining buffer to the new one + this.buffer.copy(newBuffer, 0, this.bufferOffset, this.bufferOffset + this.bufferLength) + this.buffer = newBuffer + this.bufferOffset = 0 + } + // Concat the new buffer with the remaining one + buffer.copy(this.buffer, this.bufferOffset + this.bufferLength) + this.bufferLength = newLength + } else { + this.buffer = buffer + this.bufferOffset = 0 + this.bufferLength = buffer.byteLength + } + } + + private handlePacket(offset: number, code: number, length: number, bytes: Buffer): BackendMessage { + const { reader } = this + + // NOTE: This undesirably retains the buffer in `this.reader` if the `parse*Message` calls below throw. However, those should only throw in the case of a protocol error, which normally results in the reader being discarded. + reader.setBuffer(offset, bytes) + + let message: BackendMessage + + switch (code) { + case MessageCodes.BindComplete: + message = bindComplete + break + case MessageCodes.ParseComplete: + message = parseComplete + break + case MessageCodes.CloseComplete: + message = closeComplete + break + case MessageCodes.NoData: + message = noData + break + case MessageCodes.PortalSuspended: + message = portalSuspended + break + case MessageCodes.CopyDone: + message = copyDone + break + case MessageCodes.ReplicationStart: + message = replicationStart + break + case MessageCodes.EmptyQuery: + message = emptyQuery + break + case MessageCodes.DataRow: + message = parseDataRowMessage(reader) + break + case MessageCodes.CommandComplete: + message = parseCommandCompleteMessage(reader) + break + case MessageCodes.ReadyForQuery: + message = parseReadyForQueryMessage(reader) + break + case MessageCodes.NotificationResponse: + message = parseNotificationMessage(reader) + break + case MessageCodes.AuthenticationResponse: + message = parseAuthenticationResponse(reader, length) + break + case MessageCodes.ParameterStatus: + message = parseParameterStatusMessage(reader) + break + case MessageCodes.BackendKeyData: + message = parseBackendKeyData(reader) + break + case MessageCodes.ErrorMessage: + message = parseErrorMessage(reader, 'error') + break + case MessageCodes.NoticeMessage: + message = parseErrorMessage(reader, 'notice') + break + case MessageCodes.RowDescriptionMessage: + message = parseRowDescriptionMessage(reader) + break + case MessageCodes.ParameterDescriptionMessage: + message = parseParameterDescriptionMessage(reader) + break + case MessageCodes.CopyIn: + message = parseCopyInMessage(reader) + break + case MessageCodes.CopyOut: + message = parseCopyOutMessage(reader) + break + case MessageCodes.CopyData: + message = parseCopyData(reader, length) + break + default: + return new DatabaseError('received invalid response: ' + code.toString(16), length, 'error') + } + + reader.setBuffer(0, emptyBuffer) + + message.length = length + return message + } +} + +const parseReadyForQueryMessage = (reader: BufferReader) => { + const status = reader.string(1) + return new ReadyForQueryMessage(LATEINIT_LENGTH, status) +} + +const parseCommandCompleteMessage = (reader: BufferReader) => { + const text = reader.cstring() + return new CommandCompleteMessage(LATEINIT_LENGTH, text) +} + +const parseCopyData = (reader: BufferReader, length: number) => { + const chunk = reader.bytes(length - 4) + return new CopyDataMessage(LATEINIT_LENGTH, chunk) +} + +const parseCopyInMessage = (reader: BufferReader) => parseCopyMessage(reader, 'copyInResponse') + +const parseCopyOutMessage = (reader: BufferReader) => parseCopyMessage(reader, 'copyOutResponse') + +const parseCopyMessage = (reader: BufferReader, messageName: MessageName) => { + const isBinary = reader.byte() !== 0 + const columnCount = reader.int16() + const message = new CopyResponse(LATEINIT_LENGTH, messageName, isBinary, columnCount) + for (let i = 0; i < columnCount; i++) { + message.columnTypes[i] = reader.int16() + } + return message +} + +const parseNotificationMessage = (reader: BufferReader) => { + const processId = reader.int32() + const channel = reader.cstring() + const payload = reader.cstring() + return new NotificationResponseMessage(LATEINIT_LENGTH, processId, channel, payload) +} + +const parseRowDescriptionMessage = (reader: BufferReader) => { + const fieldCount = reader.int16() + const message = new RowDescriptionMessage(LATEINIT_LENGTH, fieldCount) + for (let i = 0; i < fieldCount; i++) { + message.fields[i] = parseField(reader) + } + return message +} + +const parseField = (reader: BufferReader) => { + const name = reader.cstring() + const tableID = reader.uint32() + const columnID = reader.int16() + const dataTypeID = reader.uint32() + const dataTypeSize = reader.int16() + const dataTypeModifier = reader.int32() + const mode = reader.int16() === 0 ? 'text' : 'binary' + return new Field(name, tableID, columnID, dataTypeID, dataTypeSize, dataTypeModifier, mode) +} + +const parseParameterDescriptionMessage = (reader: BufferReader) => { + const parameterCount = reader.int16() + const message = new ParameterDescriptionMessage(LATEINIT_LENGTH, parameterCount) + for (let i = 0; i < parameterCount; i++) { + // OIDs are unsigned, same as dataTypeID in parseField above + message.dataTypeIDs[i] = reader.uint32() + } + return message +} + +const parseDataRowMessage = (reader: BufferReader) => { + const fieldCount = reader.int16() + const fields: any[] = new Array(fieldCount) + for (let i = 0; i < fieldCount; i++) { + const len = reader.int32() + // a -1 for length means the value of the field is null + fields[i] = len === -1 ? null : reader.string(len) + } + return new DataRowMessage(LATEINIT_LENGTH, fields) +} + +const parseParameterStatusMessage = (reader: BufferReader) => { + const name = reader.cstring() + const value = reader.cstring() + return new ParameterStatusMessage(LATEINIT_LENGTH, name, value) +} + +const parseBackendKeyData = (reader: BufferReader) => { + const processID = reader.int32() + const secretKey = reader.int32() + return new BackendKeyDataMessage(LATEINIT_LENGTH, processID, secretKey) +} + +const parseAuthenticationResponse = (reader: BufferReader, length: number) => { + const code = reader.int32() + // TODO(bmc): maybe better types here + const message: BackendMessage & any = { + name: 'authenticationOk', + length, + } + + switch (code) { + case 0: // AuthenticationOk + break + case 3: // AuthenticationCleartextPassword + if (message.length === 8) { + message.name = 'authenticationCleartextPassword' + } + break + case 5: // AuthenticationMD5Password + if (message.length === 12) { + message.name = 'authenticationMD5Password' + const salt = reader.bytes(4) + return new AuthenticationMD5Password(LATEINIT_LENGTH, salt) + } + break + case 10: // AuthenticationSASL + { + message.name = 'authenticationSASL' + message.mechanisms = [] + let mechanism: string + do { + mechanism = reader.cstring() + if (mechanism) { + message.mechanisms.push(mechanism) + } + } while (mechanism) + } + break + case 11: // AuthenticationSASLContinue + message.name = 'authenticationSASLContinue' + message.data = reader.string(length - 8) + break + case 12: // AuthenticationSASLFinal + message.name = 'authenticationSASLFinal' + message.data = reader.string(length - 8) + break + default: + throw new Error('Unknown authenticationOk message type ' + code) + } + return message +} + +const parseErrorMessage = (reader: BufferReader, name: MessageName) => { + const fields: Record = {} + let fieldType = reader.string(1) + while (fieldType !== '\0') { + fields[fieldType] = reader.cstring() + fieldType = reader.string(1) + } + + const messageValue = fields.M + + const message = + name === 'notice' + ? new NoticeMessage(LATEINIT_LENGTH, messageValue) + : new DatabaseError(messageValue, LATEINIT_LENGTH, name) + + message.severity = fields.S + message.code = fields.C + message.detail = fields.D + message.hint = fields.H + message.position = fields.P + message.internalPosition = fields.p + message.internalQuery = fields.q + message.where = fields.W + message.schema = fields.s + message.table = fields.t + message.column = fields.c + message.dataType = fields.d + message.constraint = fields.n + message.file = fields.F + message.line = fields.L + message.routine = fields.R + return message +} diff --git a/node_modules/pg-protocol/src/serializer.ts b/node_modules/pg-protocol/src/serializer.ts new file mode 100644 index 0000000..bbd5962 --- /dev/null +++ b/node_modules/pg-protocol/src/serializer.ts @@ -0,0 +1,286 @@ +import { Writer } from './buffer-writer' + +const enum code { + startup = 0x70, + query = 0x51, + parse = 0x50, + bind = 0x42, + execute = 0x45, + flush = 0x48, + sync = 0x53, + end = 0x58, + close = 0x43, + describe = 0x44, + copyFromChunk = 0x64, + copyDone = 0x63, + copyFail = 0x66, +} + +const writer = new Writer() + +const startup = (opts: Record): Buffer => { + // protocol version + writer.addInt16(3).addInt16(0) + for (const key of Object.keys(opts)) { + writer.addCString(key).addCString(opts[key]) + } + + writer.addCString('client_encoding').addCString('UTF8') + + const bodyBuffer = writer.addCString('').flush() + // this message is sent without a code + + const length = bodyBuffer.length + 4 + + return new Writer().addInt32(length).add(bodyBuffer).flush() +} + +const requestSsl = (): Buffer => { + const response = Buffer.allocUnsafe(8) + response.writeInt32BE(8, 0) + response.writeInt32BE(80877103, 4) + return response +} + +const password = (password: string): Buffer => { + return writer.addCString(password).flush(code.startup) +} + +const sendSASLInitialResponseMessage = function (mechanism: string, initialResponse: string): Buffer { + // 0x70 = 'p' + writer.addCString(mechanism).addInt32PrefixedString(initialResponse) + + return writer.flush(code.startup) +} + +const sendSCRAMClientFinalMessage = function (additionalData: string): Buffer { + return writer.addString(additionalData).flush(code.startup) +} + +const query = (text: string): Buffer => { + return writer.addCString(text).flush(code.query) +} + +type ParseOpts = { + name?: string + types?: number[] + text: string +} + +const emptyArray: any[] = [] + +const parse = (query: ParseOpts): Buffer => { + // expect something like this: + // { name: 'queryName', + // text: 'select * from blah', + // types: ['int8', 'bool'] } + + // normalize missing query names to allow for null + const name = query.name || '' + if (name.length > 63) { + console.error('Warning! Postgres only supports 63 characters for query names.') + console.error('You supplied %s (%s)', name, name.length) + console.error('This can cause conflicts and silent errors executing queries') + } + + const types = query.types || emptyArray + + const len = types.length + + const buffer = writer + .addCString(name) // name of query + .addCString(query.text) // actual query text + .addInt16(len) + + for (let i = 0; i < len; i++) { + buffer.addInt32(types[i]) + } + + return writer.flush(code.parse) +} + +type ValueMapper = (param: any, index: number) => any + +type BindOpts = { + portal?: string + binary?: boolean + statement?: string + values?: any[] + // optional map from JS value to postgres value per parameter + valueMapper?: ValueMapper +} + +// make this a const enum so typescript will inline the value +const enum ParamType { + STRING = 0, + BINARY = 1, +} + +const writeValues = function (values: any[], valueMapper: ValueMapper | undefined, formatsOffset: number): void { + const len = values.length + for (let i = 0; i < len; i++) { + const mappedVal = valueMapper ? valueMapper(values[i], i) : values[i] + let formatByte = ParamType.STRING + + if (mappedVal == null) { + // write -1 to indicate null + writer.addInt32(-1) + } else if (mappedVal instanceof Buffer) { + formatByte = ParamType.BINARY + + // add the buffer to the param writer + writer.addInt32(mappedVal.length) + writer.add(mappedVal) + } else { + // length prefix + UTF-8 bytes in one pass (Buffer.byteLength computed once) + writer.addInt32PrefixedString(mappedVal) + } + + // beware: `writer` operations can replace `writer.buffer` with a new buffer + const buf = writer.buffer + buf[formatsOffset++] = 0 + buf[formatsOffset++] = formatByte + } +} + +const bind = (config: BindOpts = {}): Buffer => { + // normalize config + const portal = config.portal || '' + const statement = config.statement || '' + const binary = config.binary || false + const values = config.values || emptyArray + const len = values.length + + writer.addCString(portal).addCString(statement) + + // number of parameter format codes + writer.addInt16(len) + + // space for those codes, filled by `writeValues` + const formatsOffset = writer.reserveUnsafe(len * 2) + + // number of parameter values + writer.addInt16(len) + + try { + writeValues(values, config.valueMapper, formatsOffset) + } catch (err) { + writer.clear() + throw err + } + + // all results use the same format code + writer.addInt16(1) + // format code + writer.addInt16(binary ? ParamType.BINARY : ParamType.STRING) + return writer.flush(code.bind) +} + +type ExecOpts = { + portal?: string + rows?: number +} + +const emptyExecute = Buffer.from([code.execute, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00]) + +const execute = (config?: ExecOpts): Buffer => { + // this is the happy path for most queries + if (!config || (!config.portal && !config.rows)) { + return emptyExecute + } + + const portal = config.portal || '' + const rows = config.rows || 0 + + const portalLength = Buffer.byteLength(portal) + const len = 4 + portalLength + 1 + 4 + // one extra bit for code + const buff = Buffer.allocUnsafe(1 + len) + buff[0] = code.execute + buff.writeInt32BE(len, 1) + buff.write(portal, 5, 'utf-8') + buff[portalLength + 5] = 0 // null terminate portal cString + buff.writeUInt32BE(rows, buff.length - 4) + return buff +} + +const cancel = (processID: number, secretKey: number): Buffer => { + const buffer = Buffer.allocUnsafe(16) + buffer.writeInt32BE(16, 0) + buffer.writeInt16BE(1234, 4) + buffer.writeInt16BE(5678, 6) + buffer.writeInt32BE(processID, 8) + buffer.writeInt32BE(secretKey, 12) + return buffer +} + +type PortalOpts = { + type: 'S' | 'P' + name?: string +} + +const cstringMessage = (code: code, string: string): Buffer => { + const stringLen = Buffer.byteLength(string) + const len = 4 + stringLen + 1 + // one extra bit for code + const buffer = Buffer.allocUnsafe(1 + len) + buffer[0] = code + buffer.writeInt32BE(len, 1) + buffer.write(string, 5, 'utf-8') + buffer[len] = 0 // null terminate cString + return buffer +} + +const emptyDescribePortal = writer.addCString('P').flush(code.describe) +const emptyDescribeStatement = writer.addCString('S').flush(code.describe) + +const describe = (msg: PortalOpts): Buffer => { + return msg.name + ? cstringMessage(code.describe, `${msg.type}${msg.name || ''}`) + : msg.type === 'P' + ? emptyDescribePortal + : emptyDescribeStatement +} + +const close = (msg: PortalOpts): Buffer => { + const text = `${msg.type}${msg.name || ''}` + return cstringMessage(code.close, text) +} + +const copyData = (chunk: Buffer): Buffer => { + return writer.add(chunk).flush(code.copyFromChunk) +} + +const copyFail = (message: string): Buffer => { + return cstringMessage(code.copyFail, message) +} + +const codeOnlyBuffer = (code: code): Buffer => Buffer.from([code, 0x00, 0x00, 0x00, 0x04]) + +const flushBuffer = codeOnlyBuffer(code.flush) +const syncBuffer = codeOnlyBuffer(code.sync) +const endBuffer = codeOnlyBuffer(code.end) +const copyDoneBuffer = codeOnlyBuffer(code.copyDone) + +const serialize = { + startup, + password, + requestSsl, + sendSASLInitialResponseMessage, + sendSCRAMClientFinalMessage, + query, + parse, + bind, + execute, + describe, + close, + flush: () => flushBuffer, + sync: () => syncBuffer, + end: () => endBuffer, + copyData, + copyDone: () => copyDoneBuffer, + copyFail, + cancel, +} + +export { serialize } diff --git a/node_modules/pg-protocol/src/testing/buffer-list.ts b/node_modules/pg-protocol/src/testing/buffer-list.ts new file mode 100644 index 0000000..bef75d4 --- /dev/null +++ b/node_modules/pg-protocol/src/testing/buffer-list.ts @@ -0,0 +1,67 @@ +export default class BufferList { + constructor(public buffers: Buffer[] = []) {} + + public add(buffer: Buffer, front?: boolean) { + this.buffers[front ? 'unshift' : 'push'](buffer) + return this + } + + public addInt16(val: number, front?: boolean) { + return this.add(Buffer.from([val >>> 8, val >>> 0]), front) + } + + public getByteLength() { + return this.buffers.reduce(function (previous, current) { + return previous + current.length + }, 0) + } + + public addInt32(val: number, first?: boolean) { + return this.add( + Buffer.from([(val >>> 24) & 0xff, (val >>> 16) & 0xff, (val >>> 8) & 0xff, (val >>> 0) & 0xff]), + first + ) + } + + public addCString(val: string, front?: boolean) { + const len = Buffer.byteLength(val) + const buffer = Buffer.alloc(len + 1) + buffer.write(val) + buffer[len] = 0 + return this.add(buffer, front) + } + + public addString(val: string, front?: boolean) { + const len = Buffer.byteLength(val) + const buffer = Buffer.alloc(len) + buffer.write(val) + return this.add(buffer, front) + } + + public addChar(char: string, first?: boolean) { + return this.add(Buffer.from(char, 'utf8'), first) + } + + public addByte(byte: number) { + return this.add(Buffer.from([byte])) + } + + public join(appendLength?: boolean, char?: string): Buffer { + let length = this.getByteLength() + if (appendLength) { + this.addInt32(length + 4, true) + return this.join(false, char) + } + if (char) { + this.addChar(char, true) + length++ + } + const result = Buffer.alloc(length) + let index = 0 + this.buffers.forEach(function (buffer) { + buffer.copy(result, index, 0) + index += buffer.length + }) + return result + } +} diff --git a/node_modules/pg-protocol/src/testing/test-buffers.ts b/node_modules/pg-protocol/src/testing/test-buffers.ts new file mode 100644 index 0000000..1f0d71f --- /dev/null +++ b/node_modules/pg-protocol/src/testing/test-buffers.ts @@ -0,0 +1,166 @@ +// https://www.postgresql.org/docs/current/protocol-message-formats.html +import BufferList from './buffer-list' + +const buffers = { + readyForQuery: function () { + return new BufferList().add(Buffer.from('I')).join(true, 'Z') + }, + + authenticationOk: function () { + return new BufferList().addInt32(0).join(true, 'R') + }, + + authenticationCleartextPassword: function () { + return new BufferList().addInt32(3).join(true, 'R') + }, + + authenticationMD5Password: function () { + return new BufferList() + .addInt32(5) + .add(Buffer.from([1, 2, 3, 4])) + .join(true, 'R') + }, + + authenticationSASL: function () { + return new BufferList().addInt32(10).addCString('SCRAM-SHA-256').addCString('').join(true, 'R') + }, + + authenticationSASLContinue: function () { + return new BufferList().addInt32(11).addString('data').join(true, 'R') + }, + + authenticationSASLFinal: function () { + return new BufferList().addInt32(12).addString('data').join(true, 'R') + }, + + parameterStatus: function (name: string, value: string) { + return new BufferList().addCString(name).addCString(value).join(true, 'S') + }, + + backendKeyData: function (processID: number, secretKey: number) { + return new BufferList().addInt32(processID).addInt32(secretKey).join(true, 'K') + }, + + commandComplete: function (string: string) { + return new BufferList().addCString(string).join(true, 'C') + }, + + rowDescription: function (fields: any[]) { + fields = fields || [] + const buf = new BufferList() + buf.addInt16(fields.length) + fields.forEach(function (field) { + buf + .addCString(field.name) + .addInt32(field.tableID || 0) + .addInt16(field.attributeNumber || 0) + .addInt32(field.dataTypeID || 0) + .addInt16(field.dataTypeSize || 0) + .addInt32(field.typeModifier || 0) + .addInt16(field.formatCode || 0) + }) + return buf.join(true, 'T') + }, + + parameterDescription: function (dataTypeIDs: number[]) { + dataTypeIDs = dataTypeIDs || [] + const buf = new BufferList() + buf.addInt16(dataTypeIDs.length) + dataTypeIDs.forEach(function (dataTypeID) { + buf.addInt32(dataTypeID) + }) + return buf.join(true, 't') + }, + + dataRow: function (columns: any[]) { + columns = columns || [] + const buf = new BufferList() + buf.addInt16(columns.length) + columns.forEach(function (col) { + if (col == null) { + buf.addInt32(-1) + } else { + const strBuf = Buffer.from(col, 'utf8') + buf.addInt32(strBuf.length) + buf.add(strBuf) + } + }) + return buf.join(true, 'D') + }, + + error: function (fields: any) { + return buffers.errorOrNotice(fields).join(true, 'E') + }, + + notice: function (fields: any) { + return buffers.errorOrNotice(fields).join(true, 'N') + }, + + errorOrNotice: function (fields: any) { + fields = fields || [] + const buf = new BufferList() + fields.forEach(function (field: any) { + buf.addChar(field.type) + buf.addCString(field.value) + }) + return buf.add(Buffer.from([0])) // terminator + }, + + parseComplete: function () { + return new BufferList().join(true, '1') + }, + + bindComplete: function () { + return new BufferList().join(true, '2') + }, + + notification: function (id: number, channel: string, payload: string) { + return new BufferList().addInt32(id).addCString(channel).addCString(payload).join(true, 'A') + }, + + emptyQuery: function () { + return new BufferList().join(true, 'I') + }, + + portalSuspended: function () { + return new BufferList().join(true, 's') + }, + + closeComplete: function () { + return new BufferList().join(true, '3') + }, + + copyIn: function (cols: number) { + const list = new BufferList() + // text mode + .addByte(0) + // column count + .addInt16(cols) + for (let i = 0; i < cols; i++) { + list.addInt16(i) + } + return list.join(true, 'G') + }, + + copyOut: function (cols: number) { + const list = new BufferList() + // text mode + .addByte(0) + // column count + .addInt16(cols) + for (let i = 0; i < cols; i++) { + list.addInt16(i) + } + return list.join(true, 'H') + }, + + copyData: function (bytes: Buffer) { + return new BufferList().add(bytes).join(true, 'd') + }, + + copyDone: function () { + return new BufferList().join(true, 'c') + }, +} + +export default buffers diff --git a/node_modules/pg-types/.travis.yml b/node_modules/pg-types/.travis.yml new file mode 100644 index 0000000..dd6b033 --- /dev/null +++ b/node_modules/pg-types/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - '4' + - 'lts/*' + - 'node' +env: + - PGUSER=postgres diff --git a/node_modules/pg-types/Makefile b/node_modules/pg-types/Makefile new file mode 100644 index 0000000..d7ec83d --- /dev/null +++ b/node_modules/pg-types/Makefile @@ -0,0 +1,14 @@ +.PHONY: publish-patch test + +test: + npm test + +patch: test + npm version patch -m "Bump version" + git push origin master --tags + npm publish + +minor: test + npm version minor -m "Bump version" + git push origin master --tags + npm publish diff --git a/node_modules/pg-types/README.md b/node_modules/pg-types/README.md new file mode 100644 index 0000000..54a3f2c --- /dev/null +++ b/node_modules/pg-types/README.md @@ -0,0 +1,75 @@ +# pg-types + +This is the code that turns all the raw text from postgres into JavaScript types for [node-postgres](https://github.com/brianc/node-postgres.git) + +## use + +This module is consumed and exported from the root `pg` object of node-postgres. To access it, do the following: + +```js +var types = require('pg').types +``` + +Generally what you'll want to do is override how a specific data-type is parsed and turned into a JavaScript type. By default the PostgreSQL backend server returns everything as strings. Every data type corresponds to a unique `OID` within the server, and these `OIDs` are sent back with the query response. So, you need to match a particluar `OID` to a function you'd like to use to take the raw text input and produce a valid JavaScript object as a result. `null` values are never parsed. + +Let's do something I commonly like to do on projects: return 64-bit integers `(int8)` as JavaScript integers. Because JavaScript doesn't have support for 64-bit integers node-postgres cannot confidently parse `int8` data type results as numbers because if you have a _huge_ number it will overflow and the result you'd get back from node-postgres would not be the result in the datbase. That would be a __very bad thing__ so node-postgres just returns `int8` results as strings and leaves the parsing up to you. Let's say that you know you don't and wont ever have numbers greater than `int4` in your database, but you're tired of recieving results from the `COUNT(*)` function as strings (because that function returns `int8`). You would do this: + +```js +var types = require('pg').types +types.setTypeParser(20, function(val) { + return parseInt(val) +}) +``` + +__boom__: now you get numbers instead of strings. + +Just as another example -- not saying this is a good idea -- let's say you want to return all dates from your database as [moment](http://momentjs.com/docs/) objects. Okay, do this: + +```js +var types = require('pg').types +var moment = require('moment') +var parseFn = function(val) { + return val === null ? null : moment(val) +} +types.setTypeParser(types.builtins.TIMESTAMPTZ, parseFn) +types.setTypeParser(types.builtins.TIMESTAMP, parseFn) +``` +_note: I've never done that with my dates, and I'm not 100% sure moment can parse all the date strings returned from postgres. It's just an example!_ + +If you're thinking "gee, this seems pretty handy, but how can I get a list of all the OIDs in the database and what they correspond to?!?!?!" worry not: + +```bash +$ psql -c "select typname, oid, typarray from pg_type order by oid" +``` + +If you want to find out the OID of a specific type: + +```bash +$ psql -c "select typname, oid, typarray from pg_type where typname = 'daterange' order by oid" +``` + +:smile: + +## license + +The MIT License (MIT) + +Copyright (c) 2014 Brian M. Carlson + +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/node_modules/pg-types/index.d.ts b/node_modules/pg-types/index.d.ts new file mode 100644 index 0000000..4bebcbe --- /dev/null +++ b/node_modules/pg-types/index.d.ts @@ -0,0 +1,137 @@ +export enum TypeId { + BOOL = 16, + BYTEA = 17, + CHAR = 18, + INT8 = 20, + INT2 = 21, + INT4 = 23, + REGPROC = 24, + TEXT = 25, + OID = 26, + TID = 27, + XID = 28, + CID = 29, + JSON = 114, + XML = 142, + PG_NODE_TREE = 194, + SMGR = 210, + PATH = 602, + POLYGON = 604, + CIDR = 650, + FLOAT4 = 700, + FLOAT8 = 701, + ABSTIME = 702, + RELTIME = 703, + TINTERVAL = 704, + CIRCLE = 718, + MACADDR8 = 774, + MONEY = 790, + MACADDR = 829, + INET = 869, + ACLITEM = 1033, + BPCHAR = 1042, + VARCHAR = 1043, + DATE = 1082, + TIME = 1083, + TIMESTAMP = 1114, + TIMESTAMPTZ = 1184, + INTERVAL = 1186, + TIMETZ = 1266, + BIT = 1560, + VARBIT = 1562, + NUMERIC = 1700, + REFCURSOR = 1790, + REGPROCEDURE = 2202, + REGOPER = 2203, + REGOPERATOR = 2204, + REGCLASS = 2205, + REGTYPE = 2206, + UUID = 2950, + TXID_SNAPSHOT = 2970, + PG_LSN = 3220, + PG_NDISTINCT = 3361, + PG_DEPENDENCIES = 3402, + TSVECTOR = 3614, + TSQUERY = 3615, + GTSVECTOR = 3642, + REGCONFIG = 3734, + REGDICTIONARY = 3769, + JSONB = 3802, + REGNAMESPACE = 4089, + REGROLE = 4096 +} + +export type builtinsTypes = + 'BOOL' | + 'BYTEA' | + 'CHAR' | + 'INT8' | + 'INT2' | + 'INT4' | + 'REGPROC' | + 'TEXT' | + 'OID' | + 'TID' | + 'XID' | + 'CID' | + 'JSON' | + 'XML' | + 'PG_NODE_TREE' | + 'SMGR' | + 'PATH' | + 'POLYGON' | + 'CIDR' | + 'FLOAT4' | + 'FLOAT8' | + 'ABSTIME' | + 'RELTIME' | + 'TINTERVAL' | + 'CIRCLE' | + 'MACADDR8' | + 'MONEY' | + 'MACADDR' | + 'INET' | + 'ACLITEM' | + 'BPCHAR' | + 'VARCHAR' | + 'DATE' | + 'TIME' | + 'TIMESTAMP' | + 'TIMESTAMPTZ' | + 'INTERVAL' | + 'TIMETZ' | + 'BIT' | + 'VARBIT' | + 'NUMERIC' | + 'REFCURSOR' | + 'REGPROCEDURE' | + 'REGOPER' | + 'REGOPERATOR' | + 'REGCLASS' | + 'REGTYPE' | + 'UUID' | + 'TXID_SNAPSHOT' | + 'PG_LSN' | + 'PG_NDISTINCT' | + 'PG_DEPENDENCIES' | + 'TSVECTOR' | + 'TSQUERY' | + 'GTSVECTOR' | + 'REGCONFIG' | + 'REGDICTIONARY' | + 'JSONB' | + 'REGNAMESPACE' | + 'REGROLE'; + +export type TypesBuiltins = {[key in builtinsTypes]: TypeId}; + +export type TypeFormat = 'text' | 'binary'; + +export const builtins: TypesBuiltins; + +export function setTypeParser (id: TypeId, parseFn: ((value: string) => any)): void; +export function setTypeParser (id: TypeId, format: TypeFormat, parseFn: (value: string) => any): void; + +export const getTypeParser: (id: TypeId, format?: TypeFormat) => any + +export const arrayParser: (source: string, transform: (entry: any) => any) => any[]; diff --git a/node_modules/pg-types/index.js b/node_modules/pg-types/index.js new file mode 100644 index 0000000..952d8c2 --- /dev/null +++ b/node_modules/pg-types/index.js @@ -0,0 +1,47 @@ +var textParsers = require('./lib/textParsers'); +var binaryParsers = require('./lib/binaryParsers'); +var arrayParser = require('./lib/arrayParser'); +var builtinTypes = require('./lib/builtins'); + +exports.getTypeParser = getTypeParser; +exports.setTypeParser = setTypeParser; +exports.arrayParser = arrayParser; +exports.builtins = builtinTypes; + +var typeParsers = { + text: {}, + binary: {} +}; + +//the empty parse function +function noParse (val) { + return String(val); +}; + +//returns a function used to convert a specific type (specified by +//oid) into a result javascript type +//note: the oid can be obtained via the following sql query: +//SELECT oid FROM pg_type WHERE typname = 'TYPE_NAME_HERE'; +function getTypeParser (oid, format) { + format = format || 'text'; + if (!typeParsers[format]) { + return noParse; + } + return typeParsers[format][oid] || noParse; +}; + +function setTypeParser (oid, format, parseFn) { + if(typeof format == 'function') { + parseFn = format; + format = 'text'; + } + typeParsers[format][oid] = parseFn; +}; + +textParsers.init(function(oid, converter) { + typeParsers.text[oid] = converter; +}); + +binaryParsers.init(function(oid, converter) { + typeParsers.binary[oid] = converter; +}); diff --git a/node_modules/pg-types/index.test-d.ts b/node_modules/pg-types/index.test-d.ts new file mode 100644 index 0000000..d530e6e --- /dev/null +++ b/node_modules/pg-types/index.test-d.ts @@ -0,0 +1,21 @@ +import * as types from '.'; +import { expectType } from 'tsd'; + +// builtins +expectType(types.builtins); + +// getTypeParser +const noParse = types.getTypeParser(types.builtins.NUMERIC, 'text'); +const numericParser = types.getTypeParser(types.builtins.NUMERIC, 'binary'); +expectType(noParse('noParse')); +expectType(numericParser([200, 1, 0, 15])); + +// getArrayParser +const value = types.arrayParser('{1,2,3}', (num) => parseInt(num)); +expectType(value); + +//setTypeParser +types.setTypeParser(types.builtins.INT8, parseInt); +types.setTypeParser(types.builtins.FLOAT8, parseFloat); +types.setTypeParser(types.builtins.FLOAT8, 'binary', (data) => data[0]); +types.setTypeParser(types.builtins.FLOAT8, 'text', parseFloat); diff --git a/node_modules/pg-types/lib/arrayParser.js b/node_modules/pg-types/lib/arrayParser.js new file mode 100644 index 0000000..81ccffb --- /dev/null +++ b/node_modules/pg-types/lib/arrayParser.js @@ -0,0 +1,11 @@ +var array = require('postgres-array'); + +module.exports = { + create: function (source, transform) { + return { + parse: function() { + return array.parse(source, transform); + } + }; + } +}; diff --git a/node_modules/pg-types/lib/binaryParsers.js b/node_modules/pg-types/lib/binaryParsers.js new file mode 100644 index 0000000..e12c2f4 --- /dev/null +++ b/node_modules/pg-types/lib/binaryParsers.js @@ -0,0 +1,257 @@ +var parseInt64 = require('pg-int8'); + +var parseBits = function(data, bits, offset, invert, callback) { + offset = offset || 0; + invert = invert || false; + callback = callback || function(lastValue, newValue, bits) { return (lastValue * Math.pow(2, bits)) + newValue; }; + var offsetBytes = offset >> 3; + + var inv = function(value) { + if (invert) { + return ~value & 0xff; + } + + return value; + }; + + // read first (maybe partial) byte + var mask = 0xff; + var firstBits = 8 - (offset % 8); + if (bits < firstBits) { + mask = (0xff << (8 - bits)) & 0xff; + firstBits = bits; + } + + if (offset) { + mask = mask >> (offset % 8); + } + + var result = 0; + if ((offset % 8) + bits >= 8) { + result = callback(0, inv(data[offsetBytes]) & mask, firstBits); + } + + // read bytes + var bytes = (bits + offset) >> 3; + for (var i = offsetBytes + 1; i < bytes; i++) { + result = callback(result, inv(data[i]), 8); + } + + // bits to read, that are not a complete byte + var lastBits = (bits + offset) % 8; + if (lastBits > 0) { + result = callback(result, inv(data[bytes]) >> (8 - lastBits), lastBits); + } + + return result; +}; + +var parseFloatFromBits = function(data, precisionBits, exponentBits) { + var bias = Math.pow(2, exponentBits - 1) - 1; + var sign = parseBits(data, 1); + var exponent = parseBits(data, exponentBits, 1); + + if (exponent === 0) { + return 0; + } + + // parse mantissa + var precisionBitsCounter = 1; + var parsePrecisionBits = function(lastValue, newValue, bits) { + if (lastValue === 0) { + lastValue = 1; + } + + for (var i = 1; i <= bits; i++) { + precisionBitsCounter /= 2; + if ((newValue & (0x1 << (bits - i))) > 0) { + lastValue += precisionBitsCounter; + } + } + + return lastValue; + }; + + var mantissa = parseBits(data, precisionBits, exponentBits + 1, false, parsePrecisionBits); + + // special cases + if (exponent == (Math.pow(2, exponentBits + 1) - 1)) { + if (mantissa === 0) { + return (sign === 0) ? Infinity : -Infinity; + } + + return NaN; + } + + // normale number + return ((sign === 0) ? 1 : -1) * Math.pow(2, exponent - bias) * mantissa; +}; + +var parseInt16 = function(value) { + if (parseBits(value, 1) == 1) { + return -1 * (parseBits(value, 15, 1, true) + 1); + } + + return parseBits(value, 15, 1); +}; + +var parseInt32 = function(value) { + if (parseBits(value, 1) == 1) { + return -1 * (parseBits(value, 31, 1, true) + 1); + } + + return parseBits(value, 31, 1); +}; + +var parseFloat32 = function(value) { + return parseFloatFromBits(value, 23, 8); +}; + +var parseFloat64 = function(value) { + return parseFloatFromBits(value, 52, 11); +}; + +var parseNumeric = function(value) { + var sign = parseBits(value, 16, 32); + if (sign == 0xc000) { + return NaN; + } + + var weight = Math.pow(10000, parseBits(value, 16, 16)); + var result = 0; + + var digits = []; + var ndigits = parseBits(value, 16); + for (var i = 0; i < ndigits; i++) { + result += parseBits(value, 16, 64 + (16 * i)) * weight; + weight /= 10000; + } + + var scale = Math.pow(10, parseBits(value, 16, 48)); + return ((sign === 0) ? 1 : -1) * Math.round(result * scale) / scale; +}; + +var parseDate = function(isUTC, value) { + var sign = parseBits(value, 1); + var rawValue = parseBits(value, 63, 1); + + // discard usecs and shift from 2000 to 1970 + var result = new Date((((sign === 0) ? 1 : -1) * rawValue / 1000) + 946684800000); + + if (!isUTC) { + result.setTime(result.getTime() + result.getTimezoneOffset() * 60000); + } + + // add microseconds to the date + result.usec = rawValue % 1000; + result.getMicroSeconds = function() { + return this.usec; + }; + result.setMicroSeconds = function(value) { + this.usec = value; + }; + result.getUTCMicroSeconds = function() { + return this.usec; + }; + + return result; +}; + +var parseArray = function(value) { + var dim = parseBits(value, 32); + + var flags = parseBits(value, 32, 32); + var elementType = parseBits(value, 32, 64); + + var offset = 96; + var dims = []; + for (var i = 0; i < dim; i++) { + // parse dimension + dims[i] = parseBits(value, 32, offset); + offset += 32; + + // ignore lower bounds + offset += 32; + } + + var parseElement = function(elementType) { + // parse content length + var length = parseBits(value, 32, offset); + offset += 32; + + // parse null values + if (length == 0xffffffff) { + return null; + } + + var result; + if ((elementType == 0x17) || (elementType == 0x14)) { + // int/bigint + result = parseBits(value, length * 8, offset); + offset += length * 8; + return result; + } + else if (elementType == 0x19) { + // string + result = value.toString(this.encoding, offset >> 3, (offset += (length << 3)) >> 3); + return result; + } + else { + console.log("ERROR: ElementType not implemented: " + elementType); + } + }; + + var parse = function(dimension, elementType) { + var array = []; + var i; + + if (dimension.length > 1) { + var count = dimension.shift(); + for (i = 0; i < count; i++) { + array[i] = parse(dimension, elementType); + } + dimension.unshift(count); + } + else { + for (i = 0; i < dimension[0]; i++) { + array[i] = parseElement(elementType); + } + } + + return array; + }; + + return parse(dims, elementType); +}; + +var parseText = function(value) { + return value.toString('utf8'); +}; + +var parseBool = function(value) { + if(value === null) return null; + return (parseBits(value, 8) > 0); +}; + +var init = function(register) { + register(20, parseInt64); + register(21, parseInt16); + register(23, parseInt32); + register(26, parseInt32); + register(1700, parseNumeric); + register(700, parseFloat32); + register(701, parseFloat64); + register(16, parseBool); + register(1114, parseDate.bind(null, false)); + register(1184, parseDate.bind(null, true)); + register(1000, parseArray); + register(1007, parseArray); + register(1016, parseArray); + register(1008, parseArray); + register(1009, parseArray); + register(25, parseText); +}; + +module.exports = { + init: init +}; diff --git a/node_modules/pg-types/lib/builtins.js b/node_modules/pg-types/lib/builtins.js new file mode 100644 index 0000000..f0c134a --- /dev/null +++ b/node_modules/pg-types/lib/builtins.js @@ -0,0 +1,73 @@ +/** + * Following query was used to generate this file: + + SELECT json_object_agg(UPPER(PT.typname), PT.oid::int4 ORDER BY pt.oid) + FROM pg_type PT + WHERE typnamespace = (SELECT pgn.oid FROM pg_namespace pgn WHERE nspname = 'pg_catalog') -- Take only builting Postgres types with stable OID (extension types are not guaranted to be stable) + AND typtype = 'b' -- Only basic types + AND typelem = 0 -- Ignore aliases + AND typisdefined -- Ignore undefined types + */ + +module.exports = { + BOOL: 16, + BYTEA: 17, + CHAR: 18, + INT8: 20, + INT2: 21, + INT4: 23, + REGPROC: 24, + TEXT: 25, + OID: 26, + TID: 27, + XID: 28, + CID: 29, + JSON: 114, + XML: 142, + PG_NODE_TREE: 194, + SMGR: 210, + PATH: 602, + POLYGON: 604, + CIDR: 650, + FLOAT4: 700, + FLOAT8: 701, + ABSTIME: 702, + RELTIME: 703, + TINTERVAL: 704, + CIRCLE: 718, + MACADDR8: 774, + MONEY: 790, + MACADDR: 829, + INET: 869, + ACLITEM: 1033, + BPCHAR: 1042, + VARCHAR: 1043, + DATE: 1082, + TIME: 1083, + TIMESTAMP: 1114, + TIMESTAMPTZ: 1184, + INTERVAL: 1186, + TIMETZ: 1266, + BIT: 1560, + VARBIT: 1562, + NUMERIC: 1700, + REFCURSOR: 1790, + REGPROCEDURE: 2202, + REGOPER: 2203, + REGOPERATOR: 2204, + REGCLASS: 2205, + REGTYPE: 2206, + UUID: 2950, + TXID_SNAPSHOT: 2970, + PG_LSN: 3220, + PG_NDISTINCT: 3361, + PG_DEPENDENCIES: 3402, + TSVECTOR: 3614, + TSQUERY: 3615, + GTSVECTOR: 3642, + REGCONFIG: 3734, + REGDICTIONARY: 3769, + JSONB: 3802, + REGNAMESPACE: 4089, + REGROLE: 4096 +}; diff --git a/node_modules/pg-types/lib/textParsers.js b/node_modules/pg-types/lib/textParsers.js new file mode 100644 index 0000000..b1218bf --- /dev/null +++ b/node_modules/pg-types/lib/textParsers.js @@ -0,0 +1,215 @@ +var array = require('postgres-array') +var arrayParser = require('./arrayParser'); +var parseDate = require('postgres-date'); +var parseInterval = require('postgres-interval'); +var parseByteA = require('postgres-bytea'); + +function allowNull (fn) { + return function nullAllowed (value) { + if (value === null) return value + return fn(value) + } +} + +function parseBool (value) { + if (value === null) return value + return value === 'TRUE' || + value === 't' || + value === 'true' || + value === 'y' || + value === 'yes' || + value === 'on' || + value === '1'; +} + +function parseBoolArray (value) { + if (!value) return null + return array.parse(value, parseBool) +} + +function parseBaseTenInt (string) { + return parseInt(string, 10) +} + +function parseIntegerArray (value) { + if (!value) return null + return array.parse(value, allowNull(parseBaseTenInt)) +} + +function parseBigIntegerArray (value) { + if (!value) return null + return array.parse(value, allowNull(function (entry) { + return parseBigInteger(entry).trim() + })) +} + +var parsePointArray = function(value) { + if(!value) { return null; } + var p = arrayParser.create(value, function(entry) { + if(entry !== null) { + entry = parsePoint(entry); + } + return entry; + }); + + return p.parse(); +}; + +var parseFloatArray = function(value) { + if(!value) { return null; } + var p = arrayParser.create(value, function(entry) { + if(entry !== null) { + entry = parseFloat(entry); + } + return entry; + }); + + return p.parse(); +}; + +var parseStringArray = function(value) { + if(!value) { return null; } + + var p = arrayParser.create(value); + return p.parse(); +}; + +var parseDateArray = function(value) { + if (!value) { return null; } + + var p = arrayParser.create(value, function(entry) { + if (entry !== null) { + entry = parseDate(entry); + } + return entry; + }); + + return p.parse(); +}; + +var parseIntervalArray = function(value) { + if (!value) { return null; } + + var p = arrayParser.create(value, function(entry) { + if (entry !== null) { + entry = parseInterval(entry); + } + return entry; + }); + + return p.parse(); +}; + +var parseByteAArray = function(value) { + if (!value) { return null; } + + return array.parse(value, allowNull(parseByteA)); +}; + +var parseInteger = function(value) { + return parseInt(value, 10); +}; + +var parseBigInteger = function(value) { + var valStr = String(value); + if (/^\d+$/.test(valStr)) { return valStr; } + return value; +}; + +var parseJsonArray = function(value) { + if (!value) { return null; } + + return array.parse(value, allowNull(JSON.parse)); +}; + +var parsePoint = function(value) { + if (value[0] !== '(') { return null; } + + value = value.substring( 1, value.length - 1 ).split(','); + + return { + x: parseFloat(value[0]) + , y: parseFloat(value[1]) + }; +}; + +var parseCircle = function(value) { + if (value[0] !== '<' && value[1] !== '(') { return null; } + + var point = '('; + var radius = ''; + var pointParsed = false; + for (var i = 2; i < value.length - 1; i++){ + if (!pointParsed) { + point += value[i]; + } + + if (value[i] === ')') { + pointParsed = true; + continue; + } else if (!pointParsed) { + continue; + } + + if (value[i] === ','){ + continue; + } + + radius += value[i]; + } + var result = parsePoint(point); + result.radius = parseFloat(radius); + + return result; +}; + +var init = function(register) { + register(20, parseBigInteger); // int8 + register(21, parseInteger); // int2 + register(23, parseInteger); // int4 + register(26, parseInteger); // oid + register(700, parseFloat); // float4/real + register(701, parseFloat); // float8/double + register(16, parseBool); + register(1082, parseDate); // date + register(1114, parseDate); // timestamp without timezone + register(1184, parseDate); // timestamp + register(600, parsePoint); // point + register(651, parseStringArray); // cidr[] + register(718, parseCircle); // circle + register(1000, parseBoolArray); + register(1001, parseByteAArray); + register(1005, parseIntegerArray); // _int2 + register(1007, parseIntegerArray); // _int4 + register(1028, parseIntegerArray); // oid[] + register(1016, parseBigIntegerArray); // _int8 + register(1017, parsePointArray); // point[] + register(1021, parseFloatArray); // _float4 + register(1022, parseFloatArray); // _float8 + register(1231, parseFloatArray); // _numeric + register(1014, parseStringArray); //char + register(1015, parseStringArray); //varchar + register(1008, parseStringArray); + register(1009, parseStringArray); + register(1040, parseStringArray); // macaddr[] + register(1041, parseStringArray); // inet[] + register(1115, parseDateArray); // timestamp without time zone[] + register(1182, parseDateArray); // _date + register(1185, parseDateArray); // timestamp with time zone[] + register(1186, parseInterval); + register(1187, parseIntervalArray); + register(17, parseByteA); + register(114, JSON.parse.bind(JSON)); // json + register(3802, JSON.parse.bind(JSON)); // jsonb + register(199, parseJsonArray); // json[] + register(3807, parseJsonArray); // jsonb[] + register(3907, parseStringArray); // numrange[] + register(2951, parseStringArray); // uuid[] + register(791, parseStringArray); // money[] + register(1183, parseStringArray); // time[] + register(1270, parseStringArray); // timetz[] +}; + +module.exports = { + init: init +}; diff --git a/node_modules/pg-types/package.json b/node_modules/pg-types/package.json new file mode 100644 index 0000000..5f18026 --- /dev/null +++ b/node_modules/pg-types/package.json @@ -0,0 +1,42 @@ +{ + "name": "pg-types", + "version": "2.2.0", + "description": "Query result type converters for node-postgres", + "main": "index.js", + "scripts": { + "test": "tape test/*.js | tap-spec && npm run test-ts", + "test-ts": "if-node-version '>= 8' tsd" + }, + "repository": { + "type": "git", + "url": "git://github.com/brianc/node-pg-types.git" + }, + "keywords": [ + "postgres", + "PostgreSQL", + "pg" + ], + "author": "Brian M. Carlson", + "license": "MIT", + "bugs": { + "url": "https://github.com/brianc/node-pg-types/issues" + }, + "homepage": "https://github.com/brianc/node-pg-types", + "devDependencies": { + "if-node-version": "^1.1.1", + "pff": "^1.0.0", + "tap-spec": "^4.0.0", + "tape": "^4.0.0", + "tsd": "^0.7.4" + }, + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } +} diff --git a/node_modules/pg-types/test/index.js b/node_modules/pg-types/test/index.js new file mode 100644 index 0000000..b7d05cd --- /dev/null +++ b/node_modules/pg-types/test/index.js @@ -0,0 +1,24 @@ + +var test = require('tape') +var printf = require('pff') +var getTypeParser = require('../').getTypeParser +var types = require('./types') + +test('types', function (t) { + Object.keys(types).forEach(function (typeName) { + var type = types[typeName] + t.test(typeName, function (t) { + var parser = getTypeParser(type.id, type.format) + type.tests.forEach(function (tests) { + var input = tests[0] + var expected = tests[1] + var result = parser(input) + if (typeof expected === 'function') { + return expected(t, result) + } + t.equal(result, expected) + }) + t.end() + }) + }) +}) diff --git a/node_modules/pg-types/test/types.js b/node_modules/pg-types/test/types.js new file mode 100644 index 0000000..af708a5 --- /dev/null +++ b/node_modules/pg-types/test/types.js @@ -0,0 +1,597 @@ +'use strict' + +exports['string/varchar'] = { + format: 'text', + id: 1043, + tests: [ + ['bang', 'bang'] + ] +} + +exports['integer/int4'] = { + format: 'text', + id: 23, + tests: [ + ['2147483647', 2147483647] + ] +} + +exports['smallint/int2'] = { + format: 'text', + id: 21, + tests: [ + ['32767', 32767] + ] +} + +exports['bigint/int8'] = { + format: 'text', + id: 20, + tests: [ + ['9223372036854775807', '9223372036854775807'] + ] +} + +exports.oid = { + format: 'text', + id: 26, + tests: [ + ['103', 103] + ] +} + +var bignum = '31415926535897932384626433832795028841971693993751058.16180339887498948482045868343656381177203091798057628' +exports.numeric = { + format: 'text', + id: 1700, + tests: [ + [bignum, bignum] + ] +} + +exports['real/float4'] = { + format: 'text', + id: 700, + tests: [ + ['123.456', 123.456] + ] +} + +exports['double precision / float 8'] = { + format: 'text', + id: 701, + tests: [ + ['12345678.12345678', 12345678.12345678] + ] +} + +exports.boolean = { + format: 'text', + id: 16, + tests: [ + ['TRUE', true], + ['t', true], + ['true', true], + ['y', true], + ['yes', true], + ['on', true], + ['1', true], + ['f', false], + [null, null] + ] +} + +exports.timestamptz = { + format: 'text', + id: 1184, + tests: [ + [ + '2010-10-31 14:54:13.74-05:30', + dateEquals(2010, 9, 31, 20, 24, 13, 740) + ], + [ + '2011-01-23 22:05:00.68-06', + dateEquals(2011, 0, 24, 4, 5, 0, 680) + ], + [ + '2010-10-30 14:11:12.730838Z', + dateEquals(2010, 9, 30, 14, 11, 12, 730) + ], + [ + '2010-10-30 13:10:01+05', + dateEquals(2010, 9, 30, 8, 10, 1, 0) + ] + ] +} + +exports.timestamp = { + format: 'text', + id: 1114, + tests: [ + [ + '2010-10-31 00:00:00', + function (t, value) { + t.equal( + value.toUTCString(), + new Date(2010, 9, 31, 0, 0, 0, 0, 0).toUTCString() + ) + t.equal( + value.toString(), + new Date(2010, 9, 31, 0, 0, 0, 0, 0, 0).toString() + ) + } + ] + ] +} + +exports.date = { + format: 'text', + id: 1082, + tests: [ + ['2010-10-31', function (t, value) { + var now = new Date(2010, 9, 31) + dateEquals( + 2010, + now.getUTCMonth(), + now.getUTCDate(), + now.getUTCHours(), 0, 0, 0)(t, value) + t.equal(value.getHours(), now.getHours()) + }] + ] +} + +exports.inet = { + format: 'text', + id: 869, + tests: [ + ['8.8.8.8', '8.8.8.8'], + ['2001:4860:4860::8888', '2001:4860:4860::8888'], + ['127.0.0.1', '127.0.0.1'], + ['fd00:1::40e', 'fd00:1::40e'], + ['1.2.3.4', '1.2.3.4'] + ] +} + +exports.cidr = { + format: 'text', + id: 650, + tests: [ + ['172.16.0.0/12', '172.16.0.0/12'], + ['fe80::/10', 'fe80::/10'], + ['fc00::/7', 'fc00::/7'], + ['192.168.0.0/24', '192.168.0.0/24'], + ['10.0.0.0/8', '10.0.0.0/8'] + ] +} + +exports.macaddr = { + format: 'text', + id: 829, + tests: [ + ['08:00:2b:01:02:03', '08:00:2b:01:02:03'], + ['16:10:9f:0d:66:00', '16:10:9f:0d:66:00'] + ] +} + +exports.numrange = { + format: 'text', + id: 3906, + tests: [ + ['[,]', '[,]'], + ['(,)', '(,)'], + ['(,]', '(,]'], + ['[1,)', '[1,)'], + ['[,1]', '[,1]'], + ['(1,2)', '(1,2)'], + ['(1,20.5]', '(1,20.5]'] + ] +} + +exports.interval = { + format: 'text', + id: 1186, + tests: [ + ['01:02:03', function (t, value) { + t.equal(value.toPostgres(), '3 seconds 2 minutes 1 hours') + t.deepEqual(value, {hours: 1, minutes: 2, seconds: 3}) + }], + ['01:02:03.456', function (t, value) { + t.deepEqual(value, {hours: 1, minutes:2, seconds: 3, milliseconds: 456}) + }], + ['1 year -32 days', function (t, value) { + t.equal(value.toPostgres(), '-32 days 1 years') + t.deepEqual(value, {years: 1, days: -32}) + }], + ['1 day -00:00:03', function (t, value) { + t.equal(value.toPostgres(), '-3 seconds 1 days') + t.deepEqual(value, {days: 1, seconds: -3}) + }] + ] +} + +exports.bytea = { + format: 'text', + id: 17, + tests: [ + ['foo\\000\\200\\\\\\377', function (t, value) { + var buffer = new Buffer([102, 111, 111, 0, 128, 92, 255]) + t.ok(buffer.equals(value)) + }], + ['', function (t, value) { + var buffer = new Buffer(0) + t.ok(buffer.equals(value)) + }] + ] +} + +exports['array/boolean'] = { + format: 'text', + id: 1000, + tests: [ + ['{true,false}', function (t, value) { + t.deepEqual(value, [true, false]) + }] + ] +} + +exports['array/char'] = { + format: 'text', + id: 1014, + tests: [ + ['{foo,bar}', function (t, value) { + t.deepEqual(value, ['foo', 'bar']) + }] + ] +} + +exports['array/varchar'] = { + format: 'text', + id: 1015, + tests: [ + ['{foo,bar}', function (t, value) { + t.deepEqual(value, ['foo', 'bar']) + }] + ] +} + +exports['array/text'] = { + format: 'text', + id: 1008, + tests: [ + ['{foo}', function (t, value) { + t.deepEqual(value, ['foo']) + }] + ] +} + +exports['array/bytea'] = { + format: 'text', + id: 1001, + tests: [ + ['{"\\\\x00000000"}', function (t, value) { + var buffer = new Buffer('00000000', 'hex') + t.ok(Array.isArray(value)) + t.equal(value.length, 1) + t.ok(buffer.equals(value[0])) + }], + ['{NULL,"\\\\x4e554c4c"}', function (t, value) { + var buffer = new Buffer('4e554c4c', 'hex') + t.ok(Array.isArray(value)) + t.equal(value.length, 2) + t.equal(value[0], null) + t.ok(buffer.equals(value[1])) + }], + ] +} + +exports['array/numeric'] = { + format: 'text', + id: 1231, + tests: [ + ['{1.2,3.4}', function (t, value) { + t.deepEqual(value, [1.2, 3.4]) + }] + ] +} + +exports['array/int2'] = { + format: 'text', + id: 1005, + tests: [ + ['{-32768, -32767, 32766, 32767}', function (t, value) { + t.deepEqual(value, [-32768, -32767, 32766, 32767]) + }] + ] +} + +exports['array/int4'] = { + format: 'text', + id: 1005, + tests: [ + ['{-2147483648, -2147483647, 2147483646, 2147483647}', function (t, value) { + t.deepEqual(value, [-2147483648, -2147483647, 2147483646, 2147483647]) + }] + ] +} + +exports['array/int8'] = { + format: 'text', + id: 1016, + tests: [ + [ + '{-9223372036854775808, -9223372036854775807, 9223372036854775806, 9223372036854775807}', + function (t, value) { + t.deepEqual(value, [ + '-9223372036854775808', + '-9223372036854775807', + '9223372036854775806', + '9223372036854775807' + ]) + } + ] + ] +} + +exports['array/json'] = { + format: 'text', + id: 199, + tests: [ + [ + '{{1,2},{[3],"[4,5]"},{null,NULL}}', + function (t, value) { + t.deepEqual(value, [ + [1, 2], + [[3], [4, 5]], + [null, null], + ]) + } + ] + ] +} + +exports['array/jsonb'] = { + format: 'text', + id: 3807, + tests: exports['array/json'].tests +} + +exports['array/point'] = { + format: 'text', + id: 1017, + tests: [ + ['{"(25.1,50.5)","(10.1,40)"}', function (t, value) { + t.deepEqual(value, [{x: 25.1, y: 50.5}, {x: 10.1, y: 40}]) + }] + ] +} + +exports['array/oid'] = { + format: 'text', + id: 1028, + tests: [ + ['{25864,25860}', function (t, value) { + t.deepEqual(value, [25864, 25860]) + }] + ] +} + +exports['array/float4'] = { + format: 'text', + id: 1021, + tests: [ + ['{1.2, 3.4}', function (t, value) { + t.deepEqual(value, [1.2, 3.4]) + }] + ] +} + +exports['array/float8'] = { + format: 'text', + id: 1022, + tests: [ + ['{-12345678.1234567, 12345678.12345678}', function (t, value) { + t.deepEqual(value, [-12345678.1234567, 12345678.12345678]) + }] + ] +} + +exports['array/date'] = { + format: 'text', + id: 1182, + tests: [ + ['{2014-01-01,2015-12-31}', function (t, value) { + var expecteds = [new Date(2014, 0, 1), new Date(2015, 11, 31)] + t.equal(value.length, 2) + value.forEach(function (date, index) { + var expected = expecteds[index] + dateEquals( + expected.getUTCFullYear(), + expected.getUTCMonth(), + expected.getUTCDate(), + expected.getUTCHours(), 0, 0, 0)(t, date) + }) + }] + ] +} + +exports['array/interval'] = { + format: 'text', + id: 1187, + tests: [ + ['{01:02:03,1 day -00:00:03}', function (t, value) { + var expecteds = [{hours: 1, minutes: 2, seconds: 3}, + {days: 1, seconds: -3}] + t.equal(value.length, 2) + t.deepEqual(value, expecteds); + }] + ] +} + +exports['array/inet'] = { + format: 'text', + id: 1041, + tests: [ + ['{8.8.8.8}', function (t, value) { + t.deepEqual(value, ['8.8.8.8']); + }], + ['{2001:4860:4860::8888}', function (t, value) { + t.deepEqual(value, ['2001:4860:4860::8888']); + }], + ['{127.0.0.1,fd00:1::40e,1.2.3.4}', function (t, value) { + t.deepEqual(value, ['127.0.0.1', 'fd00:1::40e', '1.2.3.4']); + }] + ] +} + +exports['array/cidr'] = { + format: 'text', + id: 651, + tests: [ + ['{172.16.0.0/12}', function (t, value) { + t.deepEqual(value, ['172.16.0.0/12']); + }], + ['{fe80::/10}', function (t, value) { + t.deepEqual(value, ['fe80::/10']); + }], + ['{10.0.0.0/8,fc00::/7,192.168.0.0/24}', function (t, value) { + t.deepEqual(value, ['10.0.0.0/8', 'fc00::/7', '192.168.0.0/24']); + }] + ] +} + +exports['array/macaddr'] = { + format: 'text', + id: 1040, + tests: [ + ['{08:00:2b:01:02:03,16:10:9f:0d:66:00}', function (t, value) { + t.deepEqual(value, ['08:00:2b:01:02:03', '16:10:9f:0d:66:00']); + }] + ] +} + +exports['array/numrange'] = { + format: 'text', + id: 3907, + tests: [ + ['{"[1,2]","(4.5,8)","[10,40)","(-21.2,60.3]"}', function (t, value) { + t.deepEqual(value, ['[1,2]', '(4.5,8)', '[10,40)', '(-21.2,60.3]']); + }], + ['{"[,20]","[3,]","[,]","(,35)","(1,)","(,)"}', function (t, value) { + t.deepEqual(value, ['[,20]', '[3,]', '[,]', '(,35)', '(1,)', '(,)']); + }], + ['{"[,20)","[3,)","[,)","[,35)","[1,)","[,)"}', function (t, value) { + t.deepEqual(value, ['[,20)', '[3,)', '[,)', '[,35)', '[1,)', '[,)']); + }] + ] +} + +exports['binary-string/varchar'] = { + format: 'binary', + id: 1043, + tests: [ + ['bang', 'bang'] + ] +} + +exports['binary-integer/int4'] = { + format: 'binary', + id: 23, + tests: [ + [[0, 0, 0, 100], 100] + ] +} + +exports['binary-smallint/int2'] = { + format: 'binary', + id: 21, + tests: [ + [[0, 101], 101] + ] +} + +exports['binary-bigint/int8'] = { + format: 'binary', + id: 20, + tests: [ + [new Buffer([0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), '9223372036854775807'] + ] +} + +exports['binary-oid'] = { + format: 'binary', + id: 26, + tests: [ + [[0, 0, 0, 103], 103] + ] +} + +exports['binary-numeric'] = { + format: 'binary', + id: 1700, + tests: [ + [ + [0, 2, 0, 0, 0, 0, 0, hex('0x64'), 0, 12, hex('0xd'), hex('0x48'), 0, 0, 0, 0], + 12.34 + ] + ] +} + +exports['binary-real/float4'] = { + format: 'binary', + id: 700, + tests: [ + [['0x41', '0x48', '0x00', '0x00'].map(hex), 12.5] + ] +} + +exports['binary-boolean'] = { + format: 'binary', + id: 16, + tests: [ + [[1], true], + [[0], false], + [null, null] + ] +} + +exports['binary-string'] = { + format: 'binary', + id: 25, + tests: [ + [ + new Buffer(['0x73', '0x6c', '0x61', '0x64', '0x64', '0x61'].map(hex)), + 'sladda' + ] + ] +} + +exports.point = { + format: 'text', + id: 600, + tests: [ + ['(25.1,50.5)', function (t, value) { + t.deepEqual(value, {x: 25.1, y: 50.5}) + }] + ] +} + +exports.circle = { + format: 'text', + id: 718, + tests: [ + ['<(25,10),5>', function (t, value) { + t.deepEqual(value, {x: 25, y: 10, radius: 5}) + }] + ] +} + +function hex (string) { + return parseInt(string, 16) +} + +function dateEquals () { + var timestamp = Date.UTC.apply(Date, arguments) + return function (t, value) { + t.equal(value.toUTCString(), new Date(timestamp).toUTCString()) + } +} diff --git a/node_modules/pg/LICENSE b/node_modules/pg/LICENSE new file mode 100644 index 0000000..5c14056 --- /dev/null +++ b/node_modules/pg/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2010 - 2021 Brian Carlson + +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/node_modules/pg/README.md b/node_modules/pg/README.md new file mode 100644 index 0000000..2fca0eb --- /dev/null +++ b/node_modules/pg/README.md @@ -0,0 +1,96 @@ +# node-postgres + +[![Build Status](https://secure.travis-ci.org/brianc/node-postgres.svg?branch=master)](http://travis-ci.org/brianc/node-postgres) +NPM version +NPM downloads + +Non-blocking PostgreSQL client for Node.js. Pure JavaScript and optional native libpq bindings. + +## Install + +```sh +$ npm install pg +``` + +--- + +## :star: [Documentation](https://node-postgres.com) :star: + +### Features + +- [Fastest PostgreSQL client for Node.js](https://github.com/nigrosimone/postgres-benchmarks) +- Pure JavaScript client and native libpq bindings share _the same API_ +- Connection pooling +- Extensible JS ↔ PostgreSQL data-type coercion +- Supported PostgreSQL features + - Parameterized queries + - Named statements with query plan caching + - Async notifications with `LISTEN/NOTIFY` + - Bulk import & export with `COPY TO/COPY FROM` + +### Extras + +node-postgres is by design pretty light on abstractions. These are some handy modules we've been using over the years to complete the picture. +The entire list can be found on our [wiki](https://github.com/brianc/node-postgres/wiki/Extras). + +## Support + +node-postgres is free software. If you encounter a bug with the library please open an issue on the [GitHub repo](https://github.com/brianc/node-postgres). If you have questions unanswered by the documentation please open an issue pointing out how the documentation was unclear & I will do my best to make it better! + +When you open an issue please provide: + +- version of Node +- version of Postgres +- smallest possible snippet of code to reproduce the problem + +You can also follow me [@brianc](https://bsky.app/profile/brianc.bsky.social) on bluesky if that's your thing for updates on node-postgres with nearly zero non node-postgres content. My old twitter/x account is no longer used. + +## Sponsorship :two_hearts: + +node-postgres's continued development has been made possible in part by generous financial support from [the community](https://github.com/brianc/node-postgres/blob/master/SPONSORS.md). + +If you or your company are benefiting from node-postgres and would like to help keep the project financially sustainable [please consider supporting](https://github.com/sponsors/brianc) its development. + +### Featured sponsor + +Special thanks to [medplum](https://medplum.com) for their generous and thoughtful support of node-postgres! + +![medplum](https://raw.githubusercontent.com/medplum/medplum-logo/refs/heads/main/medplum-logo.png) + +## Contributing + +**:heart: contributions!** + +I will **happily** accept your pull request if it: + +- **has tests** +- looks reasonable +- does not break backwards compatibility + +If your change involves breaking backwards compatibility please please point that out in the pull request & we can discuss & plan when and how to release it and what type of documentation or communicate it will require. + +## Troubleshooting and FAQ + +The causes and solutions to common errors can be found among the [Frequently Asked Questions (FAQ)](https://github.com/brianc/node-postgres/wiki/FAQ) + +## License + +Copyright (c) 2010-2020 Brian Carlson (brian.m.carlson@gmail.com) + +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/node_modules/pg/esm/index.mjs b/node_modules/pg/esm/index.mjs new file mode 100644 index 0000000..587d80c --- /dev/null +++ b/node_modules/pg/esm/index.mjs @@ -0,0 +1,20 @@ +// ESM wrapper for pg +import pg from '../lib/index.js' + +// Re-export all the properties +export const Client = pg.Client +export const Pool = pg.Pool +export const Connection = pg.Connection +export const types = pg.types +export const Query = pg.Query +export const DatabaseError = pg.DatabaseError +export const escapeIdentifier = pg.escapeIdentifier +export const escapeLiteral = pg.escapeLiteral +export const Result = pg.Result +export const TypeOverrides = pg.TypeOverrides + +// Also export the defaults +export const defaults = pg.defaults + +// Re-export the default +export default pg diff --git a/node_modules/pg/lib/client.js b/node_modules/pg/lib/client.js new file mode 100644 index 0000000..2b13c1d --- /dev/null +++ b/node_modules/pg/lib/client.js @@ -0,0 +1,846 @@ +const EventEmitter = require('events').EventEmitter +const utils = require('./utils') +const nodeUtils = require('util') +const sasl = require('./crypto/sasl') +const TypeOverrides = require('./type-overrides') + +const ConnectionParameters = require('./connection-parameters') +const Query = require('./query') +const defaults = require('./defaults') +const Connection = require('./connection') +const crypto = require('./crypto/utils') + +const activeQueryDeprecationNotice = nodeUtils.deprecate( + () => {}, + 'Client.activeQuery is deprecated and will be removed in pg@9.0' +) + +const queryQueueDeprecationNotice = nodeUtils.deprecate( + () => {}, + 'Client.queryQueue is deprecated and will be removed in pg@9.0.' +) + +const pgPassDeprecationNotice = nodeUtils.deprecate( + () => {}, + 'pgpass support is deprecated and will be removed in pg@9.0. ' + + 'You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code.' +) + +const byoPromiseDeprecationNotice = nodeUtils.deprecate( + () => {}, + 'Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0.' +) + +const queryQueueLengthDeprecationNotice = nodeUtils.deprecate( + () => {}, + 'Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.' +) + +function coerceNumberOrDefault(value, defaultValue) { + if (typeof value === 'number') { + return Number.isFinite(value) ? value : defaultValue + } + if (typeof value === 'string' && value.trim() !== '') { + const n = Number(value) + return Number.isFinite(n) ? n : defaultValue + } + return defaultValue +} + +class Client extends EventEmitter { + constructor(config) { + super() + + this.connectionParameters = new ConnectionParameters(config) + this.user = this.connectionParameters.user + this.database = this.connectionParameters.database + this.port = this.connectionParameters.port + this.host = this.connectionParameters.host + + // "hiding" the password so it doesn't show up in stack traces + // or if the client is console.logged + Object.defineProperty(this, 'password', { + configurable: true, + enumerable: false, + writable: true, + value: this.connectionParameters.password, + }) + + this.replication = this.connectionParameters.replication + + const c = config || {} + + if (c.Promise) { + byoPromiseDeprecationNotice() + } + this._Promise = c.Promise || global.Promise + this._types = new TypeOverrides(c.types) + this._ending = false + this._ended = false + this._connecting = false + this._connected = false + this._connectionError = false + this._queryable = true + this._activeQuery = null + this._txStatus = null + + this.enableChannelBinding = Boolean(c.enableChannelBinding) // set true to use SCRAM-SHA-256-PLUS when offered + this.scramMaxIterations = coerceNumberOrDefault(c.scramMaxIterations, sasl.DEFAULT_MAX_SCRAM_ITERATIONS) + this.connection = + c.connection || + new Connection({ + stream: c.stream, + ssl: this.connectionParameters.ssl, + sslNegotiation: this.connectionParameters.sslnegotiation, + keepAlive: c.keepAlive || false, + keepAliveInitialDelayMillis: c.keepAliveInitialDelayMillis || 0, + encoding: this.connectionParameters.client_encoding || 'utf8', + }) + this._queryQueue = [] + this._sentQueryQueue = [] + this.pipeline = Boolean(c.pipeline) + this.binary = c.binary || defaults.binary + this.processID = null + this.secretKey = null + this.ssl = this.connectionParameters.ssl || false + this.sslNegotiation = this.connectionParameters.sslnegotiation || 'postgres' + // As with Password, make SSL->Key (the private key) non-enumerable. + // It won't show up in stack traces + // or if the client is console.logged + if (this.ssl && this.ssl.key) { + Object.defineProperty(this.ssl, 'key', { + enumerable: false, + }) + } + + this._connectionTimeoutMillis = c.connectionTimeoutMillis || 0 + } + + get activeQuery() { + activeQueryDeprecationNotice() + return this._activeQuery + } + + set activeQuery(val) { + activeQueryDeprecationNotice() + this._activeQuery = val + } + + _getActiveQuery() { + return this._activeQuery + } + + _errorAllQueries(err) { + const enqueueError = (query) => { + process.nextTick(() => { + query.handleError(err, this.connection) + }) + } + + const activeQuery = this._getActiveQuery() + if (activeQuery) { + enqueueError(activeQuery) + this._activeQuery = null + } + + this._sentQueryQueue.forEach(enqueueError) + this._sentQueryQueue.length = 0 + + this._queryQueue.forEach(enqueueError) + this._queryQueue.length = 0 + } + + _connect(callback) { + const self = this + const con = this.connection + this._connectionCallback = callback + + if (this._connecting || this._connected) { + const err = new Error('Client has already been connected. You cannot reuse a client.') + process.nextTick(() => { + callback(err) + }) + return + } + this._connecting = true + + if (this._connectionTimeoutMillis > 0) { + this.connectionTimeoutHandle = setTimeout(() => { + con._ending = true + con.stream.destroy(new Error('timeout expired')) + }, this._connectionTimeoutMillis) + + if (this.connectionTimeoutHandle.unref) { + this.connectionTimeoutHandle.unref() + } + } + + if (this.host && this.host.indexOf('/') === 0) { + con.connect(this.host + '/.s.PGSQL.' + this.port) + } else { + con.connect(this.port, this.host) + } + + // once connection is established send startup message + con.on('connect', function () { + if (self.ssl) { + // With direct SSL negotiation the connection upgrades to TLS without an + // SSLRequest packet, so the startup message is sent after 'sslconnect'. + if (self.sslNegotiation !== 'direct') { + con.requestSsl() + } + } else { + con.startup(self.getStartupConf()) + } + }) + + con.on('sslconnect', function () { + con.startup(self.getStartupConf()) + }) + + this._attachListeners(con) + + con.once('end', () => { + const error = this._ending ? new Error('Connection terminated') : new Error('Connection terminated unexpectedly') + + clearTimeout(this.connectionTimeoutHandle) + this._errorAllQueries(error) + this._ended = true + + if (!this._ending) { + // if the connection is ended without us calling .end() + // on this client then we have an unexpected disconnection + // treat this as an error unless we've already emitted an error + // during connection. + if (this._connecting && !this._connectionError) { + if (this._connectionCallback) { + this._connectionCallback(error) + } else { + this._handleErrorEvent(error) + } + } else if (!this._connectionError) { + this._handleErrorEvent(error) + } + } + + process.nextTick(() => { + this.emit('end') + }) + }) + } + + connect(callback) { + if (callback) { + this._connect(callback) + return + } + + return new this._Promise((resolve, reject) => { + this._connect((error) => { + if (error) { + reject(error) + } else { + resolve(this) + } + }) + }) + } + + _attachListeners(con) { + // password request handling + con.on('authenticationCleartextPassword', this._handleAuthCleartextPassword.bind(this)) + // password request handling + con.on('authenticationMD5Password', this._handleAuthMD5Password.bind(this)) + // password request handling (SASL) + con.on('authenticationSASL', this._handleAuthSASL.bind(this)) + con.on('authenticationSASLContinue', this._handleAuthSASLContinue.bind(this)) + con.on('authenticationSASLFinal', this._handleAuthSASLFinal.bind(this)) + con.on('backendKeyData', this._handleBackendKeyData.bind(this)) + con.on('error', this._handleErrorEvent.bind(this)) + con.on('errorMessage', this._handleErrorMessage.bind(this)) + con.on('readyForQuery', this._handleReadyForQuery.bind(this)) + con.on('notice', this._handleNotice.bind(this)) + con.on('rowDescription', this._handleRowDescription.bind(this)) + con.on('dataRow', this._handleDataRow.bind(this)) + con.on('portalSuspended', this._handlePortalSuspended.bind(this)) + con.on('emptyQuery', this._handleEmptyQuery.bind(this)) + con.on('commandComplete', this._handleCommandComplete.bind(this)) + con.on('parseComplete', this._handleParseComplete.bind(this)) + con.on('copyInResponse', this._handleCopyInResponse.bind(this)) + con.on('copyData', this._handleCopyData.bind(this)) + con.on('notification', this._handleNotification.bind(this)) + } + + _getPassword(cb) { + const con = this.connection + if (typeof this.password === 'function') { + this._Promise + .resolve() + .then(() => this.password(this.connectionParameters)) + .then((pass) => { + if (pass !== undefined) { + if (typeof pass !== 'string') { + con.emit('error', new TypeError('Password must be a string')) + return + } + this.connectionParameters.password = this.password = pass + } else { + this.connectionParameters.password = this.password = null + } + cb() + }) + .catch((err) => { + con.emit('error', err) + }) + } else if (this.password !== null) { + cb() + } else { + try { + const pgPass = require('pgpass') + pgPass(this.connectionParameters, (pass) => { + if (undefined !== pass) { + pgPassDeprecationNotice() + this.connectionParameters.password = this.password = pass + } + cb() + }) + } catch (e) { + this.emit('error', e) + } + } + } + + _handleAuthCleartextPassword(msg) { + this._getPassword(() => { + this.connection.password(this.password) + }) + } + + _handleAuthMD5Password(msg) { + this._getPassword(async () => { + try { + const hashedPassword = await crypto.postgresMd5PasswordHash(this.user, this.password, msg.salt) + this.connection.password(hashedPassword) + } catch (e) { + this.emit('error', e) + } + }) + } + + _handleAuthSASL(msg) { + this._getPassword(() => { + try { + this.saslSession = sasl.startSession( + msg.mechanisms, + this.enableChannelBinding && this.connection.stream, + this.scramMaxIterations + ) + this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism, this.saslSession.response) + } catch (err) { + this.connection.emit('error', err) + } + }) + } + + async _handleAuthSASLContinue(msg) { + try { + await sasl.continueSession( + this.saslSession, + this.password, + msg.data, + this.enableChannelBinding && this.connection.stream + ) + this.connection.sendSCRAMClientFinalMessage(this.saslSession.response) + } catch (err) { + this.connection.emit('error', err) + } + } + + _handleAuthSASLFinal(msg) { + try { + sasl.finalizeSession(this.saslSession, msg.data) + this.saslSession = null + } catch (err) { + this.connection.emit('error', err) + } + } + + _handleBackendKeyData(msg) { + this.processID = msg.processID + this.secretKey = msg.secretKey + } + + _handleReadyForQuery(msg) { + if (this._connecting) { + this._connecting = false + this._connected = true + clearTimeout(this.connectionTimeoutHandle) + + // process possible callback argument to Client#connect + if (this._connectionCallback) { + this._connectionCallback(null, this) + // remove callback for proper error handling + // after the connect event + this._connectionCallback = null + } + this.emit('connect') + } + const activeQuery = this._getActiveQuery() + this._activeQuery = null + this._txStatus = msg?.status ?? null + this.readyForQuery = true + if (activeQuery) { + activeQuery.handleReadyForQuery(this.connection) + } + this._pulseQueryQueue() + } + + // if we receive an error event or error message + // during the connection process we handle it here + _handleErrorWhileConnecting(err) { + if (this._connectionError) { + // TODO(bmc): this is swallowing errors - we shouldn't do this + return + } + this._connectionError = true + clearTimeout(this.connectionTimeoutHandle) + if (this._connectionCallback) { + return this._connectionCallback(err) + } + this.emit('error', err) + } + + // if we're connected and we receive an error event from the connection + // this means the socket is dead - do a hard abort of all queries and emit + // the socket error on the client as well + _handleErrorEvent(err) { + if (this._connecting) { + return this._handleErrorWhileConnecting(err) + } + this._queryable = false + this._errorAllQueries(err) + this.emit('error', err) + } + + // handle error messages from the postgres backend + _handleErrorMessage(msg) { + if (this._connecting) { + return this._handleErrorWhileConnecting(msg) + } + const activeQuery = this._getActiveQuery() + + if (!activeQuery) { + this._handleErrorEvent(msg) + return + } + + this._activeQuery = null + if (activeQuery.name) { + delete this.connection.submittedNamedStatements[activeQuery.name] + } + activeQuery.handleError(msg, this.connection) + } + + _handleRowDescription(msg) { + const activeQuery = this._getActiveQuery() + if (activeQuery == null) { + const error = new Error('Received unexpected rowDescription message from backend.') + this._handleErrorEvent(error) + return + } + // delegate rowDescription to active query + activeQuery.handleRowDescription(msg) + } + + _handleDataRow(msg) { + const activeQuery = this._getActiveQuery() + if (activeQuery == null) { + const error = new Error('Received unexpected dataRow message from backend.') + this._handleErrorEvent(error) + return + } + // delegate dataRow to active query + activeQuery.handleDataRow(msg) + } + + _handlePortalSuspended(msg) { + const activeQuery = this._getActiveQuery() + if (activeQuery == null) { + const error = new Error('Received unexpected portalSuspended message from backend.') + this._handleErrorEvent(error) + return + } + // delegate portalSuspended to active query + activeQuery.handlePortalSuspended(this.connection) + } + + _handleEmptyQuery(msg) { + const activeQuery = this._getActiveQuery() + if (activeQuery == null) { + const error = new Error('Received unexpected emptyQuery message from backend.') + this._handleErrorEvent(error) + return + } + // delegate emptyQuery to active query + activeQuery.handleEmptyQuery(this.connection) + } + + _handleCommandComplete(msg) { + const activeQuery = this._getActiveQuery() + if (activeQuery == null) { + const error = new Error('Received unexpected commandComplete message from backend.') + this._handleErrorEvent(error) + return + } + // delegate commandComplete to active query + activeQuery.handleCommandComplete(msg, this.connection) + } + + _handleParseComplete() { + const activeQuery = this._getActiveQuery() + if (activeQuery == null) { + const error = new Error('Received unexpected parseComplete message from backend.') + this._handleErrorEvent(error) + return + } + // if a prepared statement has a name and properly parses + // we track that its already been executed so we don't parse + // it again on the same client + if (activeQuery.name) { + this.connection.parsedStatements[activeQuery.name] = activeQuery.text + delete this.connection.submittedNamedStatements[activeQuery.name] + } + } + + _handleCopyInResponse(msg) { + const activeQuery = this._getActiveQuery() + if (activeQuery == null) { + const error = new Error('Received unexpected copyInResponse message from backend.') + this._handleErrorEvent(error) + return + } + activeQuery.handleCopyInResponse(this.connection) + } + + _handleCopyData(msg) { + const activeQuery = this._getActiveQuery() + if (activeQuery == null) { + const error = new Error('Received unexpected copyData message from backend.') + this._handleErrorEvent(error) + return + } + activeQuery.handleCopyData(msg, this.connection) + } + + _handleNotification(msg) { + this.emit('notification', msg) + } + + _handleNotice(msg) { + this.emit('notice', msg) + } + + getStartupConf() { + const params = this.connectionParameters + + const data = { + user: params.user, + database: params.database, + } + + const appName = params.application_name || params.fallback_application_name + if (appName) { + data.application_name = appName + } + if (params.replication) { + data.replication = '' + params.replication + } + if (params.statement_timeout) { + data.statement_timeout = String(parseInt(params.statement_timeout, 10)) + } + if (params.lock_timeout) { + data.lock_timeout = String(parseInt(params.lock_timeout, 10)) + } + if (params.idle_in_transaction_session_timeout) { + data.idle_in_transaction_session_timeout = String(parseInt(params.idle_in_transaction_session_timeout, 10)) + } + if (params.options) { + data.options = params.options + } + + return data + } + + cancel(client, query) { + if (client.activeQuery === query) { + const con = this.connection + + if (this.host && this.host.indexOf('/') === 0) { + con.connect(this.host + '/.s.PGSQL.' + this.port) + } else { + con.connect(this.port, this.host) + } + + // once connection is established send cancel message + con.on('connect', function () { + con.cancel(client.processID, client.secretKey) + }) + } else if (client._queryQueue.indexOf(query) !== -1) { + client._queryQueue.splice(client._queryQueue.indexOf(query), 1) + } else if (client._sentQueryQueue.indexOf(query) !== -1) { + // Query already sent on wire — can't remove it without corrupting the + // pipeline. No-op the callback so the result is silently discarded. + query.callback = () => {} + } + } + + setTypeParser(oid, format, parseFn) { + return this._types.setTypeParser(oid, format, parseFn) + } + + getTypeParser(oid, format) { + return this._types.getTypeParser(oid, format) + } + + // escapeIdentifier and escapeLiteral moved to utility functions & exported + // on PG + // re-exported here for backwards compatibility + escapeIdentifier(str) { + return utils.escapeIdentifier(str) + } + + escapeLiteral(str) { + return utils.escapeLiteral(str) + } + + _pulseQueryQueue() { + if (this.pipeline) { + this._pulsePipelinedQueryQueue() + return + } + if (this.readyForQuery === true) { + this._activeQuery = this._queryQueue.shift() + const activeQuery = this._getActiveQuery() + if (activeQuery) { + this.readyForQuery = false + this.hasExecuted = true + + const queryError = activeQuery.submit(this.connection) + if (queryError) { + process.nextTick(() => { + activeQuery.handleError(queryError, this.connection) + this.readyForQuery = true + this._pulseQueryQueue() + }) + } + } else if (this.hasExecuted) { + this._activeQuery = null + this.emit('drain') + } + } + } + + _pulsePipelinedQueryQueue() { + if (!this._connected || !this._queryable) { + return + } + while (this._queryQueue.length > 0) { + const query = this._queryQueue.shift() + this.hasExecuted = true + const queryError = query.submit(this.connection) + if (queryError) { + process.nextTick(() => { + query.handleError(queryError, this.connection) + }) + continue + } + this._sentQueryQueue.push(query) + } + if (this.readyForQuery && !this._activeQuery && this._sentQueryQueue.length > 0) { + this._activeQuery = this._sentQueryQueue.shift() + this.readyForQuery = false + } + if (!this._activeQuery && this._sentQueryQueue.length === 0 && this._queryQueue.length === 0 && this.hasExecuted) { + this.emit('drain') + } + } + + query(config, values, callback) { + // can take in strings, config object or query object + let query + let result + + if (config == null) { + throw new TypeError('Client was passed a null or undefined query') + } + + if (typeof config.submit === 'function') { + result = query = config + if (!query.callback) { + if (typeof values === 'function') { + query.callback = values + } else if (callback) { + query.callback = callback + } + } + } else { + query = new Query(config, values, callback) + if (!query.callback) { + result = new this._Promise((resolve, reject) => { + query.callback = (err, res) => (err ? reject(err) : resolve(res)) + }).catch((err) => { + // replace the stack trace that leads to `TCP.onStreamRead` with one that leads back to the + // application that created the query + Error.captureStackTrace(err) + throw err + }) + } else if (typeof query.callback !== 'function') { + throw new TypeError('callback is not a function') + } + } + + const readTimeout = config.query_timeout || this.connectionParameters.query_timeout + if (readTimeout) { + const queryCallback = query.callback || (() => {}) + + const readTimeoutTimer = setTimeout(() => { + const error = new Error('Query read timeout') + + process.nextTick(() => { + query.handleError(error, this.connection) + }) + + queryCallback(error) + + // we already returned an error, + // just do nothing if query completes + query.callback = () => {} + + // Remove from queue (only safe if not yet sent) + const index = this._queryQueue.indexOf(query) + if (index > -1) { + this._queryQueue.splice(index, 1) + } else if (this.pipeline) { + // Query already sent — the pipeline is blocked until it completes. + // Destroy the connection to unblock all remaining pipelined queries. + this.connection.stream.destroy() + return + } + + this._pulseQueryQueue() + }, readTimeout) + + query.callback = (err, res) => { + clearTimeout(readTimeoutTimer) + queryCallback(err, res) + } + } + + if (this.binary && !query.binary) { + query.binary = true + } + + if (query._result && !query._result._types) { + query._result._types = this._types + } + + // A query that keeps a portal open across round trips cannot share a pipelined connection: the + // queries written behind it are answered out of its portal, so rows land on the wrong query and + // the reads that follow fail with 'portal does not exist'. Refuse it instead of corrupting. + if (this.pipeline) { + const portalQuery = + typeof config.submit === 'function' && !(query instanceof Query) + ? 'Custom query classes such as pg-cursor and pg-query-stream are' + : query.rows + ? 'The `rows` option is' + : null + if (portalQuery) { + process.nextTick(() => { + query.handleError(new Error(`${portalQuery} not supported in pipeline mode`), this.connection) + }) + return result + } + } + + if (!this._queryable) { + process.nextTick(() => { + query.handleError(new Error('Client has encountered a connection error and is not queryable'), this.connection) + }) + return result + } + + if (this._ending) { + process.nextTick(() => { + query.handleError(new Error('Client was closed and is not queryable'), this.connection) + }) + return result + } + + if (this._queryQueue.length > 0 && !this.pipeline) { + queryQueueLengthDeprecationNotice() + } + this._queryQueue.push(query) + this._pulseQueryQueue() + return result + } + + ref() { + this.connection.ref() + } + + unref() { + this.connection.unref() + } + + getTransactionStatus() { + return this._txStatus + } + + end(cb) { + this._ending = true + + // if we have never connected, then end is a noop, callback immediately + if (!this.connection._connecting || this._ended) { + if (cb) { + cb() + return + } else { + return this._Promise.resolve() + } + } + + if (!this._queryable) { + // socket is dead — force close + this.connection.stream.destroy() + } else if ( + this.pipeline && + (this._getActiveQuery() || this._sentQueryQueue.length > 0 || this._queryQueue.length > 0) + ) { + // pipelined queries are already on the wire (or queued to send) and will + // complete normally; wait for drain then do a graceful goodbye + this.once('drain', () => this.connection.end()) + } else if (this._getActiveQuery()) { + // non-pipeline: a hung query could block end forever — force disconnect + this.connection.stream.destroy() + } else { + this.connection.end() + } + + if (cb) { + this.connection.once('end', cb) + } else { + return new this._Promise((resolve) => { + this.connection.once('end', resolve) + }) + } + } + get queryQueue() { + queryQueueDeprecationNotice() + return this._queryQueue + } +} + +// expose a Query constructor +Client.Query = Query + +module.exports = Client diff --git a/node_modules/pg/lib/connection-parameters.js b/node_modules/pg/lib/connection-parameters.js new file mode 100644 index 0000000..37987fd --- /dev/null +++ b/node_modules/pg/lib/connection-parameters.js @@ -0,0 +1,184 @@ +'use strict' + +const dns = require('dns') + +const defaults = require('./defaults') + +const parse = require('pg-connection-string').parse // parses a connection string + +const val = function (key, config, envVar) { + if (config[key]) { + return config[key] + } + + if (envVar === undefined) { + envVar = process.env['PG' + key.toUpperCase()] + } else if (envVar === false) { + // do nothing ... use false + } else { + envVar = process.env[envVar] + } + + return envVar || defaults[key] +} + +const readSSLConfigFromEnvironment = function () { + switch (process.env.PGSSLMODE) { + case 'disable': + return false + case 'prefer': + case 'require': + case 'verify-ca': + case 'verify-full': + return true + case 'no-verify': + return { rejectUnauthorized: false } + } + return defaults.ssl +} + +// Convert arg to a string, surround in single quotes, and escape single quotes and backslashes +const quoteParamValue = function (value) { + return "'" + ('' + value).replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'" +} + +const add = function (params, config, paramName) { + const value = config[paramName] + if (value !== undefined && value !== null) { + params.push(paramName + '=' + quoteParamValue(value)) + } +} + +class ConnectionParameters { + constructor(config) { + // if a string is passed, it is a raw connection string so we parse it into a config + config = typeof config === 'string' ? parse(config) : config || {} + + // if the config has a connectionString defined, parse IT into the config we use + // this will override other default values with what is stored in connectionString + if (config.connectionString) { + config = Object.assign({}, config, parse(config.connectionString)) + } + + this.user = val('user', config) + this.database = val('database', config) + + if (this.database === undefined) { + this.database = this.user + } + + this.port = parseInt(val('port', config), 10) + this.host = val('host', config) + + // "hiding" the password so it doesn't show up in stack traces + // or if the client is console.logged + Object.defineProperty(this, 'password', { + configurable: true, + enumerable: false, + writable: true, + value: val('password', config), + }) + + this.binary = val('binary', config) + this.options = val('options', config) + + this.ssl = typeof config.ssl === 'undefined' ? readSSLConfigFromEnvironment() : config.ssl + + if (typeof this.ssl === 'string') { + if (this.ssl === 'true') { + this.ssl = true + } + } + // support passing in ssl=no-verify via connection string + if (this.ssl === 'no-verify') { + this.ssl = { rejectUnauthorized: false } + } + if (this.ssl && this.ssl.key) { + Object.defineProperty(this.ssl, 'key', { + enumerable: false, + }) + } + + // How to negotiate SSL: 'postgres' (default, the traditional SSLRequest + // handshake) or 'direct' (start the TLS handshake immediately on connect). + this.sslnegotiation = val('sslnegotiation', config, 'PGSSLNEGOTIATION') + if (this.sslnegotiation !== undefined && this.sslnegotiation !== 'postgres' && this.sslnegotiation !== 'direct') { + throw new Error( + `Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".` + ) + } + if (this.sslnegotiation === 'direct' && !this.ssl) { + throw new Error('sslnegotiation=direct requires SSL to be enabled') + } + + this.client_encoding = val('client_encoding', config) + this.replication = val('replication', config) + // a domain socket begins with '/' + this.isDomainSocket = !(this.host || '').indexOf('/') + + this.application_name = val('application_name', config, 'PGAPPNAME') + this.fallback_application_name = val('fallback_application_name', config, false) + this.statement_timeout = val('statement_timeout', config, false) + this.lock_timeout = val('lock_timeout', config, false) + this.idle_in_transaction_session_timeout = val('idle_in_transaction_session_timeout', config, false) + this.query_timeout = val('query_timeout', config, false) + + if (config.connectionTimeoutMillis === undefined) { + this.connect_timeout = process.env.PGCONNECT_TIMEOUT || 0 + } else { + this.connect_timeout = Math.floor(config.connectionTimeoutMillis / 1000) + } + + if (config.keepAlive === false) { + this.keepalives = 0 + } else if (config.keepAlive === true) { + this.keepalives = 1 + } + + if (typeof config.keepAliveInitialDelayMillis === 'number') { + this.keepalives_idle = Math.floor(config.keepAliveInitialDelayMillis / 1000) + } + } + + getLibpqConnectionString(cb) { + const params = [] + add(params, this, 'user') + add(params, this, 'password') + add(params, this, 'port') + add(params, this, 'application_name') + add(params, this, 'fallback_application_name') + add(params, this, 'connect_timeout') + add(params, this, 'options') + + const ssl = typeof this.ssl === 'object' ? this.ssl : this.ssl ? { sslmode: this.ssl } : {} + add(params, ssl, 'sslmode') + add(params, ssl, 'sslca') + add(params, ssl, 'sslkey') + add(params, ssl, 'sslcert') + add(params, ssl, 'sslrootcert') + add(params, this, 'sslnegotiation') + + if (this.database) { + params.push('dbname=' + quoteParamValue(this.database)) + } + if (this.replication) { + params.push('replication=' + quoteParamValue(this.replication)) + } + if (this.host) { + params.push('host=' + quoteParamValue(this.host)) + } + if (this.isDomainSocket) { + return cb(null, params.join(' ')) + } + if (this.client_encoding) { + params.push('client_encoding=' + quoteParamValue(this.client_encoding)) + } + dns.lookup(this.host, function (err, address) { + if (err) return cb(err, null) + params.push('hostaddr=' + quoteParamValue(address)) + return cb(null, params.join(' ')) + }) + } +} + +module.exports = ConnectionParameters diff --git a/node_modules/pg/lib/connection.js b/node_modules/pg/lib/connection.js new file mode 100644 index 0000000..85f3113 --- /dev/null +++ b/node_modules/pg/lib/connection.js @@ -0,0 +1,250 @@ +'use strict' + +const EventEmitter = require('events').EventEmitter + +const { parse, serialize } = require('pg-protocol') +const stream = require('./stream') +const { getStream } = stream + +const flushBuffer = serialize.flush() +const syncBuffer = serialize.sync() +const endBuffer = serialize.end() + +// TODO(bmc) support binary mode at some point +class Connection extends EventEmitter { + constructor(config) { + super() + config = config || {} + + this.stream = config.stream || getStream(config.ssl) + if (typeof this.stream === 'function') { + this.stream = this.stream(config) + } + + this._keepAlive = config.keepAlive + this._keepAliveInitialDelayMillis = config.keepAliveInitialDelayMillis + this.parsedStatements = {} + this.submittedNamedStatements = {} + this.ssl = config.ssl || false + this.sslNegotiation = config.sslNegotiation || 'postgres' + this._ending = false + this._emitMessage = false + const self = this + this.on('newListener', function (eventName) { + if (eventName === 'message') { + self._emitMessage = true + } + }) + } + + connect(port, host) { + const self = this + + this._connecting = true + this.stream.setNoDelay(true) + this.stream.connect(port, host) + + this.stream.once('connect', function () { + if (self._keepAlive) { + self.stream.setKeepAlive(true, self._keepAliveInitialDelayMillis) + } + self.emit('connect') + }) + + const reportStreamError = function (error) { + // errors about disconnections should be ignored during disconnect + if (self._ending && (error.code === 'ECONNRESET' || error.code === 'EPIPE')) { + return + } + self.emit('error', error) + } + this.stream.on('error', reportStreamError) + + this.stream.on('close', function () { + self.emit('end') + }) + + if (!this.ssl) { + return this.attachListeners(this.stream) + } + + // With direct SSL negotiation the TLS handshake starts immediately on the + // raw socket, skipping the SSLRequest packet and the server's 'S'/'N' reply. + if (this.sslNegotiation === 'direct') { + return this.stream.once('connect', function () { + self.upgradeToSSL(host, reportStreamError) + }) + } + + this.stream.once('data', function (buffer) { + const responseCode = buffer.toString('utf8') + switch (responseCode) { + case 'S': // Server supports SSL connections, continue with a secure connection + break + case 'N': // Server does not support SSL connections + self.stream.end() + return self.emit('error', new Error('The server does not support SSL connections')) + default: + // Any other response byte, including 'E' (ErrorResponse) indicating a server error + self.stream.end() + return self.emit('error', new Error('There was an error establishing an SSL connection')) + } + self.upgradeToSSL(host, reportStreamError) + }) + } + + upgradeToSSL(host, reportStreamError) { + const self = this + const options = { + socket: self.stream, + // tls.connect checks the server identity against `servername`, falling + // back to `host` and then to 'localhost'. `servername` must stay unset + // for IP addresses (see below), so `host` is needed to keep certificate + // validation working when connecting to an IP address. + host, + } + + if (self.ssl !== true) { + Object.assign(options, self.ssl) + + if ('key' in self.ssl) { + options.key = self.ssl.key + } + } + + // Direct SSL negotiation requires ALPN so the server can confirm it is + // speaking the PostgreSQL protocol over the TLS connection. + if (self.sslNegotiation === 'direct') { + options.ALPNProtocols = ['postgresql'] + } + + // SNI must not be set to an IP address (RFC 6066 section 3) + const net = require('net') + if (net.isIP && net.isIP(host) === 0) { + options.servername = host + } + try { + self.stream = stream.getSecureStream(options) + } catch (err) { + return self.emit('error', err) + } + self.attachListeners(self.stream) + self.stream.on('error', reportStreamError) + + self.emit('sslconnect') + } + + attachListeners(stream) { + parse(stream, (msg) => { + const eventName = msg.name === 'error' ? 'errorMessage' : msg.name + if (this._emitMessage) { + this.emit('message', msg) + } + this.emit(eventName, msg) + }) + } + + requestSsl() { + this.stream.write(serialize.requestSsl()) + } + + startup(config) { + this.stream.write(serialize.startup(config)) + } + + cancel(processID, secretKey) { + this._send(serialize.cancel(processID, secretKey)) + } + + password(password) { + this._send(serialize.password(password)) + } + + sendSASLInitialResponseMessage(mechanism, initialResponse) { + this._send(serialize.sendSASLInitialResponseMessage(mechanism, initialResponse)) + } + + sendSCRAMClientFinalMessage(additionalData) { + this._send(serialize.sendSCRAMClientFinalMessage(additionalData)) + } + + _send(buffer) { + if (!this.stream.writable) { + return false + } + return this.stream.write(buffer) + } + + query(text) { + this._send(serialize.query(text)) + } + + // send parse message + parse(query) { + this._send(serialize.parse(query)) + } + + // send bind message + bind(config) { + this._send(serialize.bind(config)) + } + + // send execute message + execute(config) { + this._send(serialize.execute(config)) + } + + flush() { + if (this.stream.writable) { + this.stream.write(flushBuffer) + } + } + + sync() { + // Sync is the extended-query protocol barrier, not a disconnect. + // Only end()/Terminate (and connect-timeout teardown) should set _ending. + this._send(syncBuffer) + } + + ref() { + this.stream.ref() + } + + unref() { + this.stream.unref() + } + + end() { + // 0x58 = 'X' + this._ending = true + if (!this._connecting || !this.stream.writable) { + this.stream.end() + return + } + return this.stream.write(endBuffer, () => { + this.stream.end() + }) + } + + close(msg) { + this._send(serialize.close(msg)) + } + + describe(msg) { + this._send(serialize.describe(msg)) + } + + sendCopyFromChunk(chunk) { + this._send(serialize.copyData(chunk)) + } + + endCopyFrom() { + this._send(serialize.copyDone()) + } + + sendCopyFail(msg) { + this._send(serialize.copyFail(msg)) + } +} + +module.exports = Connection diff --git a/node_modules/pg/lib/crypto/cert-signatures.js b/node_modules/pg/lib/crypto/cert-signatures.js new file mode 100644 index 0000000..5f86506 --- /dev/null +++ b/node_modules/pg/lib/crypto/cert-signatures.js @@ -0,0 +1,122 @@ +function x509Error(msg, cert) { + return new Error('SASL channel binding: ' + msg + ' when parsing public certificate ' + cert.toString('base64')) +} + +function readASN1Length(data, index) { + let length = data[index++] + if (length < 0x80) return { length, index } + + const lengthBytes = length & 0x7f + if (lengthBytes > 4) throw x509Error('bad length', data) + + length = 0 + for (let i = 0; i < lengthBytes; i++) { + length = (length << 8) | data[index++] + } + + return { length, index } +} + +function readASN1OID(data, index) { + if (data[index++] !== 0x6) throw x509Error('non-OID data', data) // 6 = OID + + const { length: OIDLength, index: indexAfterOIDLength } = readASN1Length(data, index) + index = indexAfterOIDLength + const lastIndex = index + OIDLength + + const byte1 = data[index++] + let oid = ((byte1 / 40) >> 0) + '.' + (byte1 % 40) + + while (index < lastIndex) { + // loop over numbers in OID + let value = 0 + while (index < lastIndex) { + // loop over bytes in number + const nextByte = data[index++] + value = (value << 7) | (nextByte & 0x7f) + if (nextByte < 0x80) break + } + oid += '.' + value + } + + return { oid, index } +} + +function expectASN1Seq(data, index) { + if (data[index++] !== 0x30) throw x509Error('non-sequence data', data) // 30 = Sequence + return readASN1Length(data, index) +} + +function signatureAlgorithmHashFromCertificate(data, index) { + // read this thread: https://www.postgresql.org/message-id/17760-b6c61e752ec07060%40postgresql.org + if (index === undefined) index = 0 + index = expectASN1Seq(data, index).index + const { length: certInfoLength, index: indexAfterCertInfoLength } = expectASN1Seq(data, index) + index = indexAfterCertInfoLength + certInfoLength // skip over certificate info + index = expectASN1Seq(data, index).index // skip over signature length field + const { oid, index: indexAfterOID } = readASN1OID(data, index) + switch (oid) { + // RSA + case '1.2.840.113549.1.1.4': + return 'MD5' + case '1.2.840.113549.1.1.5': + return 'SHA-1' + case '1.2.840.113549.1.1.11': + return 'SHA-256' + case '1.2.840.113549.1.1.12': + return 'SHA-384' + case '1.2.840.113549.1.1.13': + return 'SHA-512' + case '1.2.840.113549.1.1.14': + return 'SHA-224' + case '1.2.840.113549.1.1.15': + return 'SHA512-224' + case '1.2.840.113549.1.1.16': + return 'SHA512-256' + // ECDSA + case '1.2.840.10045.4.1': + return 'SHA-1' + case '1.2.840.10045.4.3.1': + return 'SHA-224' + case '1.2.840.10045.4.3.2': + return 'SHA-256' + case '1.2.840.10045.4.3.3': + return 'SHA-384' + case '1.2.840.10045.4.3.4': + return 'SHA-512' + // RSASSA-PSS: hash is indicated separately + case '1.2.840.113549.1.1.10': { + index = indexAfterOID + index = expectASN1Seq(data, index).index + if (data[index++] !== 0xa0) throw x509Error('non-tag data', data) // a0 = constructed tag 0 + index = readASN1Length(data, index).index // skip over tag length field + index = expectASN1Seq(data, index).index // skip over sequence length field + const { oid: hashOID } = readASN1OID(data, index) + switch (hashOID) { + // standalone hash OIDs + case '1.2.840.113549.2.5': + return 'MD5' + case '1.3.14.3.2.26': + return 'SHA-1' + case '2.16.840.1.101.3.4.2.1': + return 'SHA-256' + case '2.16.840.1.101.3.4.2.2': + return 'SHA-384' + case '2.16.840.1.101.3.4.2.3': + return 'SHA-512' + } + throw x509Error('unknown hash OID ' + hashOID, data) + } + // Ed25519 -- see https://github.com/openssl/openssl/issues/15477 + case '1.3.101.110': + case '1.3.101.112': // ph + return 'SHA-512' + // Ed448 -- still not in pg 17.2 (if supported, digest would be SHAKE256 x 64 bytes) + case '1.3.101.111': + case '1.3.101.113': // ph + throw x509Error('Ed448 certificate channel binding is not currently supported by Postgres') + } + throw x509Error('unknown OID ' + oid, data) +} + +module.exports = { signatureAlgorithmHashFromCertificate } diff --git a/node_modules/pg/lib/crypto/sasl.js b/node_modules/pg/lib/crypto/sasl.js new file mode 100644 index 0000000..ea63b24 --- /dev/null +++ b/node_modules/pg/lib/crypto/sasl.js @@ -0,0 +1,262 @@ +'use strict' +const crypto = require('./utils') +const { signatureAlgorithmHashFromCertificate } = require('./cert-signatures') + +// SASLprep (RFC 4013) — minimal in-tree implementation. +// +// Per RFC 5802 §2.2, the SCRAM-SHA-256 client must normalize the password via +// SASLprep before feeding it into PBKDF2. PostgreSQL's server applies the same +// SASLprep when computing the stored verifier, and libpq does the same client +// side, so passwords whose NFKC form differs from the raw form +// would otherwise authenticate against psql/libpq but fail against pg with `28P01`. +// +// We deliberately implement only the three steps that change the byte content: +// 1. RFC 3454 Table C.1.2 (non-ASCII space) → U+0020 SPACE. +// 2. RFC 3454 Table B.1 (commonly mapped to nothing) → empty. +// 3. NFKC normalization. +// We skip the prohibition (RFC 4013 §2.3) and bidi (RFC 3454 §6) checks. +// libpq is forgiving on those paths and Postgres's own SASLprep matches that +// leniency for legacy roles, so omitting the rejection logic keeps existing +// roles working without adding complexity. +function saslprep(password) { + // RFC 3454 Table C.1.2 — non-ASCII space characters, mapped to U+0020. + const nonAsciiSpace = /[\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000]/g + // RFC 3454 Table B.1 — "commonly mapped to nothing". The set intentionally + // contains zero-width joiners and variation selectors — the very characters + // ESLint's no-misleading-character-class warns about — because they combine + // with their neighbors and the RFC strips them for that reason. + // eslint-disable-next-line no-misleading-character-class + const mappedToNothing = /[\u00AD\u034F\u1806\u180B\u180C\u180D\u200C\u200D\u2060\uFE00-\uFE0F\uFEFF]/g + return password.replace(nonAsciiSpace, ' ').replace(mappedToNothing, '').normalize('NFKC') +} + +const DEFAULT_MAX_SCRAM_ITERATIONS = 100000 + +function startSession(mechanisms, stream, scramMaxIterations = DEFAULT_MAX_SCRAM_ITERATIONS) { + const candidates = ['SCRAM-SHA-256'] + if (stream) candidates.unshift('SCRAM-SHA-256-PLUS') // higher-priority, so placed first + + const mechanism = candidates.find((candidate) => mechanisms.includes(candidate)) + + if (!mechanism) { + throw new Error('SASL: Only mechanism(s) ' + candidates.join(' and ') + ' are supported') + } + + if (mechanism === 'SCRAM-SHA-256-PLUS' && typeof stream.getPeerCertificate !== 'function') { + // this should never happen if we are really talking to a Postgres server + throw new Error('SASL: Mechanism SCRAM-SHA-256-PLUS requires a certificate') + } + + const clientNonce = crypto.randomBytes(18).toString('base64') + const gs2Header = mechanism === 'SCRAM-SHA-256-PLUS' ? 'p=tls-server-end-point' : stream ? 'y' : 'n' + + return { + mechanism, + clientNonce, + response: gs2Header + ',,n=*,r=' + clientNonce, + message: 'SASLInitialResponse', + scramMaxIterations, + } +} + +async function continueSession(session, password, serverData, stream) { + if (session.message !== 'SASLInitialResponse') { + throw new Error('SASL: Last message was not SASLInitialResponse') + } + if (typeof password !== 'string') { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string') + } + if (password === '') { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a non-empty string') + } + if (typeof serverData !== 'string') { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: serverData must be a string') + } + + const sv = parseServerFirstMessage(serverData) + + if (!sv.nonce.startsWith(session.clientNonce)) { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce does not start with client nonce') + } else if (sv.nonce.length === session.clientNonce.length) { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: server nonce is too short') + } + + const scramMaxIterations = + typeof session.scramMaxIterations === 'number' ? session.scramMaxIterations : DEFAULT_MAX_SCRAM_ITERATIONS + // a value of 0 disables the iteration count check + if (scramMaxIterations !== 0 && sv.iteration > scramMaxIterations) { + throw new Error( + 'SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration count ' + + sv.iteration + + ' exceeds scramMaxIterations of ' + + scramMaxIterations + ) + } + + const clientFirstMessageBare = 'n=*,r=' + session.clientNonce + const serverFirstMessage = 'r=' + sv.nonce + ',s=' + sv.salt + ',i=' + sv.iteration + + // without channel binding: + let channelBinding = stream ? 'eSws' : 'biws' // 'y,,' or 'n,,', base64-encoded + + // override if channel binding is in use: + if (session.mechanism === 'SCRAM-SHA-256-PLUS') { + const peerCert = stream.getPeerCertificate().raw + let hashName = signatureAlgorithmHashFromCertificate(peerCert) + if (hashName === 'MD5' || hashName === 'SHA-1') hashName = 'SHA-256' + const certHash = await crypto.hashByName(hashName, peerCert) + const bindingData = Buffer.concat([Buffer.from('p=tls-server-end-point,,'), Buffer.from(certHash)]) + channelBinding = bindingData.toString('base64') + } + + const clientFinalMessageWithoutProof = 'c=' + channelBinding + ',r=' + sv.nonce + const authMessage = clientFirstMessageBare + ',' + serverFirstMessage + ',' + clientFinalMessageWithoutProof + + const saltBytes = Buffer.from(sv.salt, 'base64') + const saltedPassword = await crypto.deriveKey(saslprep(password), saltBytes, sv.iteration) + const clientKey = await crypto.hmacSha256(saltedPassword, 'Client Key') + const storedKey = await crypto.sha256(clientKey) + const clientSignature = await crypto.hmacSha256(storedKey, authMessage) + const clientProof = xorBuffers(Buffer.from(clientKey), Buffer.from(clientSignature)).toString('base64') + const serverKey = await crypto.hmacSha256(saltedPassword, 'Server Key') + const serverSignatureBytes = await crypto.hmacSha256(serverKey, authMessage) + + session.message = 'SASLResponse' + session.serverSignature = Buffer.from(serverSignatureBytes).toString('base64') + session.response = clientFinalMessageWithoutProof + ',p=' + clientProof +} + +function finalizeSession(session, serverData) { + if (session.message !== 'SASLResponse') { + throw new Error('SASL: Last message was not SASLResponse') + } + if (typeof serverData !== 'string') { + throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: serverData must be a string') + } + + const { serverSignature } = parseServerFinalMessage(serverData) + + if (serverSignature !== session.serverSignature) { + throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature does not match') + } +} + +/** + * printable = %x21-2B / %x2D-7E + * ;; Printable ASCII except ",". + * ;; Note that any "printable" is also + * ;; a valid "value". + */ +function isPrintableChars(text) { + if (typeof text !== 'string') { + throw new TypeError('SASL: text must be a string') + } + return text + .split('') + .map((_, i) => text.charCodeAt(i)) + .every((c) => (c >= 0x21 && c <= 0x2b) || (c >= 0x2d && c <= 0x7e)) +} + +/** + * base64-char = ALPHA / DIGIT / "/" / "+" + * + * base64-4 = 4base64-char + * + * base64-3 = 3base64-char "=" + * + * base64-2 = 2base64-char "==" + * + * base64 = *base64-4 [base64-3 / base64-2] + */ +function isBase64(text) { + return /^(?:[a-zA-Z0-9+/]{4})*(?:[a-zA-Z0-9+/]{2}==|[a-zA-Z0-9+/]{3}=)?$/.test(text) +} + +function parseAttributePairs(text) { + if (typeof text !== 'string') { + throw new TypeError('SASL: attribute pairs text must be a string') + } + + return new Map( + text.split(',').map((attrValue) => { + if (!/^.=/.test(attrValue)) { + throw new Error('SASL: Invalid attribute pair entry') + } + const name = attrValue[0] + const value = attrValue.substring(2) + return [name, value] + }) + ) +} + +function parseServerFirstMessage(data) { + const attrPairs = parseAttributePairs(data) + + const nonce = attrPairs.get('r') + if (!nonce) { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce missing') + } else if (!isPrintableChars(nonce)) { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: nonce must only contain printable characters') + } + const salt = attrPairs.get('s') + if (!salt) { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt missing') + } else if (!isBase64(salt)) { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: salt must be base64') + } + const iterationText = attrPairs.get('i') + if (!iterationText) { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: iteration missing') + } else if (!/^[1-9][0-9]*$/.test(iterationText)) { + throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: invalid iteration count') + } + const iteration = parseInt(iterationText, 10) + + return { + nonce, + salt, + iteration, + } +} + +function parseServerFinalMessage(serverData) { + const attrPairs = parseAttributePairs(serverData) + const error = attrPairs.get('e') + const serverSignature = attrPairs.get('v') + + if (error) { + throw new Error(`SASL: SCRAM-SERVER-FINAL-MESSAGE: server returned error: "${error}"`) + } + + if (!serverSignature) { + throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature is missing') + } else if (!isBase64(serverSignature)) { + throw new Error('SASL: SCRAM-SERVER-FINAL-MESSAGE: server signature must be base64') + } + return { + serverSignature, + } +} + +function xorBuffers(a, b) { + if (!Buffer.isBuffer(a)) { + throw new TypeError('first argument must be a Buffer') + } + if (!Buffer.isBuffer(b)) { + throw new TypeError('second argument must be a Buffer') + } + if (a.length !== b.length) { + throw new Error('Buffer lengths must match') + } + if (a.length === 0) { + throw new Error('Buffers cannot be empty') + } + return Buffer.from(a.map((_, i) => a[i] ^ b[i])) +} + +module.exports = { + startSession, + continueSession, + finalizeSession, + DEFAULT_MAX_SCRAM_ITERATIONS, +} diff --git a/node_modules/pg/lib/crypto/utils.js b/node_modules/pg/lib/crypto/utils.js new file mode 100644 index 0000000..65aa4a1 --- /dev/null +++ b/node_modules/pg/lib/crypto/utils.js @@ -0,0 +1,89 @@ +const nodeCrypto = require('crypto') + +module.exports = { + postgresMd5PasswordHash, + randomBytes, + deriveKey, + sha256, + hashByName, + hmacSha256, + md5, +} + +/** + * The Web Crypto API - grabbed from the Node.js library or the global + * @type Crypto + */ +// eslint-disable-next-line no-undef +const webCrypto = nodeCrypto.webcrypto || globalThis.crypto +/** + * The SubtleCrypto API for low level crypto operations. + * @type SubtleCrypto + */ +const subtleCrypto = webCrypto.subtle +const textEncoder = new TextEncoder() + +/** + * + * @param {*} length + * @returns + */ +function randomBytes(length) { + return webCrypto.getRandomValues(Buffer.alloc(length)) +} + +async function md5(string) { + try { + return nodeCrypto.createHash('md5').update(string, 'utf-8').digest('hex') + } catch (e) { + // `createHash()` failed so we are probably not in Node.js, use the WebCrypto API instead. + // Note that the MD5 algorithm on WebCrypto is not available in Node.js. + // This is why we cannot just use WebCrypto in all environments. + const data = typeof string === 'string' ? textEncoder.encode(string) : string + const hash = await subtleCrypto.digest('MD5', data) + return Array.from(new Uint8Array(hash)) + .map((b) => b.toString(16).padStart(2, '0')) + .join('') + } +} + +// See AuthenticationMD5Password at https://www.postgresql.org/docs/current/static/protocol-flow.html +async function postgresMd5PasswordHash(user, password, salt) { + const inner = await md5(password + user) + const outer = await md5(Buffer.concat([Buffer.from(inner), salt])) + return 'md5' + outer +} + +/** + * Create a SHA-256 digest of the given data + * @param {Buffer} data + */ +async function sha256(text) { + return await subtleCrypto.digest('SHA-256', text) +} + +async function hashByName(hashName, text) { + return await subtleCrypto.digest(hashName, text) +} + +/** + * Sign the message with the given key + * @param {ArrayBuffer} keyBuffer + * @param {string} msg + */ +async function hmacSha256(keyBuffer, msg) { + const key = await subtleCrypto.importKey('raw', keyBuffer, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']) + return await subtleCrypto.sign('HMAC', key, textEncoder.encode(msg)) +} + +/** + * Derive a key from the password and salt + * @param {string} password + * @param {Uint8Array} salt + * @param {number} iterations + */ +async function deriveKey(password, salt, iterations) { + const key = await subtleCrypto.importKey('raw', textEncoder.encode(password), 'PBKDF2', false, ['deriveBits']) + const params = { name: 'PBKDF2', hash: 'SHA-256', salt: salt, iterations: iterations } + return await subtleCrypto.deriveBits(params, key, 32 * 8, ['deriveBits']) +} diff --git a/node_modules/pg/lib/defaults.js b/node_modules/pg/lib/defaults.js new file mode 100644 index 0000000..427243f --- /dev/null +++ b/node_modules/pg/lib/defaults.js @@ -0,0 +1,94 @@ +'use strict' + +let user +try { + user = process.platform === 'win32' ? process.env.USERNAME : process.env.USER +} catch { + // ignore, e.g., Deno without --allow-env +} + +module.exports = { + // database host. defaults to localhost + host: 'localhost', + + // database user's name + user, + + // name of database to connect + database: undefined, + + // database user's password + password: null, + + // a Postgres connection string to be used instead of setting individual connection items + // NOTE: Setting this value will cause it to override any other value (such as database or user) defined + // in the defaults object. + connectionString: undefined, + + // database port + port: 5432, + + // number of rows to return at a time from a prepared statement's + // portal. 0 will return all rows at once + rows: 0, + + // binary result mode + binary: false, + + // Connection pool options - see https://github.com/brianc/node-pg-pool + + // number of connections to use in connection pool + // 0 will disable connection pooling + max: 10, + + // max milliseconds a client can go unused before it is removed + // from the pool and destroyed + idleTimeoutMillis: 30000, + + client_encoding: '', + + ssl: false, + + // SSL negotiation style: 'postgres' (traditional SSLRequest) or 'direct' + sslnegotiation: undefined, + + application_name: undefined, + + fallback_application_name: undefined, + + options: undefined, + + parseInputDatesAsUTC: false, + + // max milliseconds any query using this connection will execute for before timing out in error. + // false=unlimited + statement_timeout: false, + + // Abort any statement that waits longer than the specified duration in milliseconds while attempting to acquire a lock. + // false=unlimited + lock_timeout: false, + + // Terminate any session with an open transaction that has been idle for longer than the specified duration in milliseconds + // false=unlimited + idle_in_transaction_session_timeout: false, + + // max milliseconds to wait for query to complete (client side) + query_timeout: false, + + connect_timeout: 0, + + keepalives: 1, + + keepalives_idle: 0, +} + +const pgTypes = require('pg-types') +// save default parsers +const parseBigInteger = pgTypes.getTypeParser(20, 'text') +const parseBigIntegerArray = pgTypes.getTypeParser(1016, 'text') + +// parse int8 so you can get your count values as actual numbers +module.exports.__defineSetter__('parseInt8', function (val) { + pgTypes.setTypeParser(20, 'text', val ? pgTypes.getTypeParser(23, 'text') : parseBigInteger) + pgTypes.setTypeParser(1016, 'text', val ? pgTypes.getTypeParser(1007, 'text') : parseBigIntegerArray) +}) diff --git a/node_modules/pg/lib/index.js b/node_modules/pg/lib/index.js new file mode 100644 index 0000000..e8b7461 --- /dev/null +++ b/node_modules/pg/lib/index.js @@ -0,0 +1,73 @@ +'use strict' + +const Client = require('./client') +const defaults = require('./defaults') +const Connection = require('./connection') +const Result = require('./result') +const utils = require('./utils') +const Pool = require('pg-pool') +const TypeOverrides = require('./type-overrides') +const { DatabaseError } = require('pg-protocol') +const { escapeIdentifier, escapeLiteral } = require('./utils') + +const poolFactory = (Client) => { + return class BoundPool extends Pool { + constructor(options) { + super(options, Client) + } + } +} + +const PG = function (clientConstructor) { + this.defaults = defaults + this.Client = clientConstructor + this.Query = this.Client.Query + this.Pool = poolFactory(this.Client) + this._pools = [] + this.Connection = Connection + this.types = require('pg-types') + this.DatabaseError = DatabaseError + this.TypeOverrides = TypeOverrides + this.escapeIdentifier = escapeIdentifier + this.escapeLiteral = escapeLiteral + this.Result = Result + this.utils = utils +} + +let clientConstructor = Client + +let forceNative = false +try { + forceNative = !!process.env.NODE_PG_FORCE_NATIVE +} catch { + // ignore, e.g., Deno without --allow-env +} + +if (forceNative) { + clientConstructor = require('./native') +} + +module.exports = new PG(clientConstructor) + +// lazy require native module...the native module may not have installed +Object.defineProperty(module.exports, 'native', { + configurable: true, + enumerable: false, + get() { + let native = null + try { + native = new PG(require('./native')) + } catch (err) { + if (err.code !== 'MODULE_NOT_FOUND') { + throw err + } + } + + // overwrite module.exports.native so that getter is never called again + Object.defineProperty(module.exports, 'native', { + value: native, + }) + + return native + }, +}) diff --git a/node_modules/pg/lib/native/client.js b/node_modules/pg/lib/native/client.js new file mode 100644 index 0000000..9ec3c8c --- /dev/null +++ b/node_modules/pg/lib/native/client.js @@ -0,0 +1,428 @@ +const nodeUtils = require('util') +// eslint-disable-next-line +var Native +// eslint-disable-next-line no-useless-catch +try { + // Wrap this `require()` in a try-catch to avoid upstream bundlers from complaining that this might not be available since it is an optional import + Native = require('pg-native') +} catch (e) { + throw e +} +const TypeOverrides = require('../type-overrides') +const EventEmitter = require('events').EventEmitter +const util = require('util') +const ConnectionParameters = require('../connection-parameters') + +const NativeQuery = require('./query') + +const queryQueueLengthDeprecationNotice = nodeUtils.deprecate( + () => {}, + 'Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.' +) + +const Client = (module.exports = function (config) { + EventEmitter.call(this) + config = config || {} + + this._Promise = config.Promise || global.Promise + this._types = new TypeOverrides(config.types) + + this.native = new Native({ + types: this._types, + }) + + this._queryQueue = [] + this._ending = false + this._connecting = false + this._connected = false + this._queryable = true + this.pipeline = Boolean(config.pipeline) + this._pipelineInFlight = false + + // keep these on the object for legacy reasons + // for the time being. TODO: deprecate all this jazz + const cp = (this.connectionParameters = new ConnectionParameters(config)) + if (config.nativeConnectionString) cp.nativeConnectionString = config.nativeConnectionString + this.user = cp.user + + // "hiding" the password so it doesn't show up in stack traces + // or if the client is console.logged + Object.defineProperty(this, 'password', { + configurable: true, + enumerable: false, + writable: true, + value: cp.password, + }) + this.database = cp.database + this.host = cp.host + this.port = cp.port + + // a hash to hold named queries + this.namedQueries = {} +}) + +Client.Query = NativeQuery + +util.inherits(Client, EventEmitter) + +Client.prototype._errorAllQueries = function (err) { + const enqueueError = (query) => { + process.nextTick(() => { + query.native = this.native + query.handleError(err) + }) + } + + if (this._hasActiveQuery()) { + enqueueError(this._activeQuery) + this._activeQuery = null + } + + this._queryQueue.forEach(enqueueError) + this._queryQueue.length = 0 +} + +// connect to the backend +// pass an optional callback to be called once connected +// or with an error if there was a connection error +Client.prototype._connect = function (cb) { + const self = this + + if (this._connecting) { + process.nextTick(() => cb(new Error('Client has already been connected. You cannot reuse a client.'))) + return + } + + this._connecting = true + + this.connectionParameters.getLibpqConnectionString(function (err, conString) { + if (self.connectionParameters.nativeConnectionString) conString = self.connectionParameters.nativeConnectionString + if (err) return cb(err) + self.native.connect(conString, function (err) { + if (err) { + self.native.end() + return cb(err) + } + + // set internal states to connected + self._connected = true + + // handle connection errors from the native layer + self.native.on('error', function (err) { + self._queryable = false + self._errorAllQueries(err) + self.emit('error', err) + }) + + self.native.on('notification', function (msg) { + self.emit('notification', { + channel: msg.relname, + payload: msg.extra, + }) + }) + + // signal we are connected now + self.emit('connect') + self._pulseQueryQueue(true) + + cb(null, this) + }) + }) +} + +Client.prototype.connect = function (callback) { + if (callback) { + this._connect(callback) + return + } + + return new this._Promise((resolve, reject) => { + this._connect((error) => { + if (error) { + reject(error) + } else { + resolve(this) + } + }) + }) +} + +// send a query to the server +// this method is highly overloaded to take +// 1) string query, optional array of parameters, optional function callback +// 2) object query with { +// string query +// optional array values, +// optional function callback instead of as a separate parameter +// optional string name to name & cache the query plan +// optional string rowMode = 'array' for an array of results +// } +Client.prototype.query = function (config, values, callback) { + let query + let result + let readTimeout + let readTimeoutTimer + let queryCallback + + if (config === null || config === undefined) { + throw new TypeError('Client was passed a null or undefined query') + } else if (typeof config.submit === 'function') { + readTimeout = config.query_timeout || this.connectionParameters.query_timeout + result = query = config + // accept query(new Query(...), (err, res) => { }) style + if (typeof values === 'function') { + config.callback = values + } + } else { + readTimeout = config.query_timeout || this.connectionParameters.query_timeout + query = new NativeQuery(config, values, callback) + if (!query.callback) { + let resolveOut, rejectOut + result = new this._Promise((resolve, reject) => { + resolveOut = resolve + rejectOut = reject + }).catch((err) => { + Error.captureStackTrace(err) + throw err + }) + query.callback = (err, res) => (err ? rejectOut(err) : resolveOut(res)) + } + } + + if (readTimeout) { + queryCallback = query.callback || (() => {}) + + readTimeoutTimer = setTimeout(() => { + const error = new Error('Query read timeout') + + process.nextTick(() => { + query.handleError(error, this.connection) + }) + + queryCallback(error) + + // we already returned an error, + // just do nothing if query completes + query.callback = () => {} + + // Remove from queue + const index = this._queryQueue.indexOf(query) + if (index > -1) { + this._queryQueue.splice(index, 1) + } + + this._pulseQueryQueue() + }, readTimeout) + + query.callback = (err, res) => { + clearTimeout(readTimeoutTimer) + queryCallback(err, res) + } + } + + if (!this._queryable) { + query.native = this.native + process.nextTick(() => { + query.handleError(new Error('Client has encountered a connection error and is not queryable')) + }) + return result + } + + if (this._ending) { + query.native = this.native + process.nextTick(() => { + query.handleError(new Error('Client was closed and is not queryable')) + }) + return result + } + + if (this._queryQueue.length > 0 && !this.pipeline) { + queryQueueLengthDeprecationNotice() + } + + this._queryQueue.push(query) + this._pulseQueryQueue() + return result +} + +// disconnect from the backend server +Client.prototype.end = function (cb) { + const self = this + + this._ending = true + + if (this._connecting && !this._connected) { + this.once('connect', () => { + this.end(() => {}) + }) + } + let result + if (!cb) { + result = new this._Promise(function (resolve, reject) { + cb = (err) => (err ? reject(err) : resolve()) + }) + } + + const doEnd = function () { + self.native.end(function () { + self._connected = false + + self._errorAllQueries(new Error('Connection terminated')) + + process.nextTick(() => { + self.emit('end') + if (cb) cb() + }) + }) + } + + // If pipeline has in-flight or queued queries, wait for them to drain before closing + if (this.pipeline && (this._pipelineInFlight || this._queryQueue.length > 0)) { + this.once('drain', doEnd) + } else { + doEnd() + } + return result +} + +Client.prototype._hasActiveQuery = function () { + return this._activeQuery && this._activeQuery.state !== 'error' && this._activeQuery.state !== 'end' +} + +Client.prototype._pulseQueryQueue = function (initialConnection) { + if (!this._connected) { + return + } + if (this.pipeline && !initialConnection) { + return this._pulsePipelinedQueryQueue() + } + if (this._hasActiveQuery()) { + return + } + const query = this._queryQueue.shift() + if (!query) { + if (!initialConnection) { + this.emit('drain') + } + return + } + this._activeQuery = query + query.submit(this) + const self = this + query.once('_done', function () { + self._pulseQueryQueue() + }) +} + +Client.prototype._pulsePipelinedQueryQueue = function () { + if (!this._connected || this._pipelineInFlight) { + return + } + if (this._queryQueue.length === 0) { + if (this.hasExecuted) { + this.emit('drain') + } + return + } + + this._pipelineInFlight = true + const self = this + const queries = [] + const nativeQueries = [] + const utils = require('../utils') + + while (this._queryQueue.length > 0) { + const query = this._queryQueue.shift() + this.hasExecuted = true + nativeQueries.push(query) + + const values = query.values ? query.values.map(utils.prepareValue) : null + const pipelineEntry = { text: query.text, name: query.name, arrayMode: query._arrayMode } + if (values) { + pipelineEntry.values = values + } + if (query.name && this.namedQueries[query.name]) { + pipelineEntry._alreadyPrepared = true + } + queries.push(pipelineEntry) + } + + this.native.pipeline(queries, function (err, results) { + self._pipelineInFlight = false + + if (err) { + // Total pipeline failure. Per-query errors arrive on results[i].err, so reaching here means + // the connection itself is gone: mark it unusable and say so, the way the JS client and the + // non-pipelined native path both do. Without this the client looks healthy after losing its + // backend, a Pool never discards it, and everything routed to it fails one query at a time + // for the life of the process. + self._connected = false + self._queryable = false + for (let i = 0; i < nativeQueries.length; i++) { + const q = nativeQueries[i] + q.native = self.native + q.handleError(err) + } + self._errorAllQueries(err) + self.emit('error', err) + self.emit('end') + return + } + + // Deliver results to each query + for (let i = 0; i < nativeQueries.length; i++) { + const q = nativeQueries[i] + const r = results[i] + q.native = self.native + + if (r.err) { + q.handleError(r.err) + } else { + // Track named queries on success + if (q.name) { + self.namedQueries[q.name] = q.text + } + q.state = 'end' + q.emit('end', r.result) + if (q.callback) { + q.callback(null, r.result) + } + } + + setImmediate(function () { + q.emit('_done') + }) + } + + // Process any queries that arrived while we were reading + self._pulsePipelinedQueryQueue() + }) +} + +// attempt to cancel an in-progress query +Client.prototype.cancel = function (query) { + if (this._activeQuery === query) { + this.native.cancel(function () {}) + } else if (this._queryQueue.indexOf(query) !== -1) { + this._queryQueue.splice(this._queryQueue.indexOf(query), 1) + } +} + +Client.prototype.ref = function () {} +Client.prototype.unref = function () {} + +Client.prototype.setTypeParser = function (oid, format, parseFn) { + return this._types.setTypeParser(oid, format, parseFn) +} + +Client.prototype.getTypeParser = function (oid, format) { + return this._types.getTypeParser(oid, format) +} + +Client.prototype.isConnected = function () { + return this._connected +} + +Client.prototype.getTransactionStatus = function () { + return this.native.getTransactionStatus() +} diff --git a/node_modules/pg/lib/native/index.js b/node_modules/pg/lib/native/index.js new file mode 100644 index 0000000..eead422 --- /dev/null +++ b/node_modules/pg/lib/native/index.js @@ -0,0 +1,2 @@ +'use strict' +module.exports = require('./client') diff --git a/node_modules/pg/lib/native/query.js b/node_modules/pg/lib/native/query.js new file mode 100644 index 0000000..39dfcc2 --- /dev/null +++ b/node_modules/pg/lib/native/query.js @@ -0,0 +1,167 @@ +'use strict' + +const EventEmitter = require('events').EventEmitter +const util = require('util') +const utils = require('../utils') + +const NativeQuery = (module.exports = function (config, values, callback) { + EventEmitter.call(this) + config = utils.normalizeQueryConfig(config, values, callback) + this.text = config.text + this.values = config.values + this.name = config.name + this.queryMode = config.queryMode + this.callback = config.callback + this.state = 'new' + this._arrayMode = config.rowMode === 'array' + + // if the 'row' event is listened for + // then emit them as they come in + // without setting singleRowMode to true + // this has almost no meaning because libpq + // reads all rows into memory before returning any + this._emitRowEvents = false + this.on( + 'newListener', + function (event) { + if (event === 'row') this._emitRowEvents = true + }.bind(this) + ) +}) + +util.inherits(NativeQuery, EventEmitter) + +const errorFieldMap = { + sqlState: 'code', + statementPosition: 'position', + messagePrimary: 'message', + messageDetail: 'detail', + messageHint: 'hint', + context: 'where', + schemaName: 'schema', + tableName: 'table', + columnName: 'column', + dataTypeName: 'dataType', + constraintName: 'constraint', + sourceFile: 'file', + sourceLine: 'line', + sourceFunction: 'routine', +} + +NativeQuery.prototype.handleError = function (err) { + // copy pq error fields into the error object + const fields = this.native && this.native.pq.resultErrorFields() + if (fields) { + for (const key in fields) { + const normalizedFieldName = errorFieldMap[key] || key + err[normalizedFieldName] = fields[key] + } + } + if (this.callback) { + this.callback(err) + } else { + this.emit('error', err) + } + this.state = 'error' +} + +NativeQuery.prototype.then = function (onSuccess, onFailure) { + return this._getPromise().then(onSuccess, onFailure) +} + +NativeQuery.prototype.catch = function (callback) { + return this._getPromise().catch(callback) +} + +NativeQuery.prototype._getPromise = function () { + if (this._promise) return this._promise + this._promise = new Promise( + function (resolve, reject) { + this._once('end', resolve) + this._once('error', reject) + }.bind(this) + ) + return this._promise +} + +NativeQuery.prototype.submit = function (client) { + this.state = 'running' + const self = this + this.native = client.native + client.native.arrayMode = this._arrayMode + + let after = function (err, rows, results) { + client.native.arrayMode = false + setImmediate(function () { + self.emit('_done') + }) + + // handle possible query error + if (err) { + return self.handleError(err) + } + + // emit row events for each row in the result + if (self._emitRowEvents) { + if (results.length > 1) { + rows.forEach((rowOfRows, i) => { + rowOfRows.forEach((row) => { + self.emit('row', row, results[i]) + }) + }) + } else { + rows.forEach(function (row) { + self.emit('row', row, results) + }) + } + } + + // handle successful result + self.state = 'end' + self.emit('end', results) + if (self.callback) { + self.callback(null, results) + } + } + + if (process.domain) { + after = process.domain.bind(after) + } + + // named query + if (this.name) { + if (this.name.length > 63) { + console.error('Warning! Postgres only supports 63 characters for query names.') + console.error('You supplied %s (%s)', this.name, this.name.length) + console.error('This can cause conflicts and silent errors executing queries') + } + const values = (this.values || []).map(utils.prepareValue) + + // check if the client has already executed this named query + // if so...just execute it again - skip the planning phase + if (client.namedQueries[this.name] !== undefined) { + if (this.text && client.namedQueries[this.name] !== this.text) { + const err = new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`) + return after(err) + } + return client.native.execute(this.name, values, after) + } + // plan the named query the first time, then execute it + return client.native.prepare(this.name, this.text, values.length, function (err) { + if (err) return after(err) + client.namedQueries[self.name] = self.text + return self.native.execute(self.name, values, after) + }) + } else if (this.values) { + if (!Array.isArray(this.values)) { + const err = new Error('Query values must be an array') + return after(err) + } + const vals = this.values.map(utils.prepareValue) + client.native.query(this.text, vals, after) + } else if (this.queryMode === 'extended') { + client.native.query(this.text, [], after) + } else { + client.native.query(this.text, after) + } +} diff --git a/node_modules/pg/lib/query.js b/node_modules/pg/lib/query.js new file mode 100644 index 0000000..3b93cb5 --- /dev/null +++ b/node_modules/pg/lib/query.js @@ -0,0 +1,263 @@ +'use strict' + +const { EventEmitter } = require('events') + +const Result = require('./result') +const utils = require('./utils') + +class Query extends EventEmitter { + constructor(config, values, callback) { + super() + + config = utils.normalizeQueryConfig(config, values, callback) + + this.text = config.text + this.values = config.values + this.rows = config.rows + this.types = config.types + this.name = config.name + this.queryMode = config.queryMode + this.binary = config.binary + // use unique portal name each time + this.portal = config.portal || '' + this.callback = config.callback + this._rowMode = config.rowMode + if (process.domain && config.callback) { + this.callback = process.domain.bind(config.callback) + } + this._result = new Result(this._rowMode, this.types) + + // potential for multiple results + this._results = this._result + this._canceledDueToError = false + } + + requiresPreparation() { + if (this.queryMode === 'extended') { + return true + } + + // named queries must always be prepared + if (this.name) { + return true + } + // always prepare if there are max number of rows expected per + // portal execution + if (this.rows) { + return true + } + // don't prepare empty text queries + if (!this.text) { + return false + } + // prepare if there are values + if (!this.values) { + return false + } + return this.values.length > 0 + } + + _checkForMultirow() { + // if we already have a result with a command property + // then we've already executed one query in a multi-statement simple query + // turn our results into an array of results + if (this._result.command) { + if (!Array.isArray(this._results)) { + this._results = [this._result] + } + this._result = new Result(this._rowMode, this._result._types) + this._results.push(this._result) + } + } + + // associates row metadata from the supplied + // message with this query object + // metadata used when parsing row results + handleRowDescription(msg) { + this._checkForMultirow() + this._result.addFields(msg.fields) + this._accumulateRows = this.callback || !this.listeners('row').length + } + + handleDataRow(msg) { + let row + + if (this._canceledDueToError) { + return + } + + try { + row = this._result.parseRow(msg.fields) + } catch (err) { + this._canceledDueToError = err + return + } + + this.emit('row', row, this._result) + if (this._accumulateRows) { + this._result.addRow(row) + } + } + + handleCommandComplete(msg, connection) { + this._checkForMultirow() + this._result.addCommandComplete(msg) + // need to sync after each command complete of a prepared statement + // if we were using a row count which results in multiple calls to _getRows + if (this.rows) { + connection.sync() + } + } + + // if a named prepared statement is created with empty query text + // the backend will send an emptyQuery message but *not* a command complete message + // since we pipeline sync immediately after execute we don't need to do anything here + // unless we have rows specified, in which case we did not pipeline the initial sync call + handleEmptyQuery(connection) { + if (this.rows) { + connection.sync() + } + } + + handleError(err, connection) { + // need to sync after error during a prepared statement + if (this._canceledDueToError) { + err = this._canceledDueToError + this._canceledDueToError = false + } + // if callback supplied do not emit error event as uncaught error + // events will bubble up to node process + if (this.callback) { + return this.callback(err) + } + this.emit('error', err) + } + + handleReadyForQuery(con) { + if (this._canceledDueToError) { + return this.handleError(this._canceledDueToError, con) + } + if (this.callback) { + try { + this.callback(null, this._results) + } catch (err) { + process.nextTick(() => { + throw err + }) + } + } + this.emit('end', this._results) + } + + submit(connection) { + if (typeof this.text !== 'string' && typeof this.name !== 'string') { + return new Error('A query must have either text or a name. Supplying neither is unsupported.') + } + const previous = connection.parsedStatements[this.name] || connection.submittedNamedStatements[this.name] + if (this.text && previous && this.text !== previous) { + return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`) + } + if (this.values && !Array.isArray(this.values)) { + return new Error('Query values must be an array') + } + if (this.requiresPreparation()) { + // If we're using the extended query protocol we fire off several separate commands + // to the backend. On some versions of node & some operating system versions + // the network stack writes each message separately instead of buffering them together + // causing the client & network to send more slowly. Corking & uncorking the stream + // allows node to buffer up the messages internally before sending them all off at once. + // note: we're checking for existence of cork/uncork because some versions of streams + // might not have this (cloudflare?) + connection.stream.cork && connection.stream.cork() + try { + this.prepare(connection) + } finally { + // while unlikely for this.prepare to throw, if it does & we don't uncork this stream + // this client becomes unresponsive, so put in finally block "just in case" + connection.stream.uncork && connection.stream.uncork() + } + } else { + connection.query(this.text) + } + return null + } + + hasBeenParsed(connection) { + return ( + this.name && + (connection.parsedStatements[this.name] !== undefined || + connection.submittedNamedStatements[this.name] !== undefined) + ) + } + + handlePortalSuspended(connection) { + this._getRows(connection, this.rows) + } + + _getRows(connection, rows) { + connection.execute({ + portal: this.portal, + rows: rows, + }) + // if we're not reading pages of rows send the sync command + // to indicate the pipeline is finished + if (!rows) { + connection.sync() + } else { + // otherwise flush the call out to read more rows + connection.flush() + } + } + + // http://developer.postgresql.org/pgdocs/postgres/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY + prepare(connection) { + // TODO refactor this poor encapsulation + if (!this.hasBeenParsed(connection)) { + connection.parse({ + text: this.text, + name: this.name, + types: this.types, + }) + if (this.name) { + connection.submittedNamedStatements[this.name] = this.text + } + } + + // because we're mapping user supplied values to + // postgres wire protocol compatible values it could + // throw an exception, so try/catch this section + try { + connection.bind({ + portal: this.portal, + statement: this.name, + values: this.values, + binary: this.binary, + valueMapper: utils.prepareValue, + }) + } catch (err) { + // we should close parse to avoid leaking connections + connection.close({ type: 'S', name: this.name }) + connection.sync() + + this.handleError(err, connection) + return + } + + connection.describe({ + type: 'P', + name: this.portal || '', + }) + + this._getRows(connection, this.rows) + } + + handleCopyInResponse(connection) { + connection.sendCopyFail('No source stream defined') + } + + handleCopyData(msg, connection) { + // noop + } +} + +module.exports = Query diff --git a/node_modules/pg/lib/result.js b/node_modules/pg/lib/result.js new file mode 100644 index 0000000..329fbf9 --- /dev/null +++ b/node_modules/pg/lib/result.js @@ -0,0 +1,109 @@ +'use strict' + +const types = require('pg-types') + +const matchRegexp = /^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/ + +// result object returned from query +// in the 'end' event and also +// passed as second argument to provided callback +class Result { + constructor(rowMode, types) { + this.command = null + this.rowCount = null + this.oid = null + this.rows = [] + this.fields = [] + this._parsers = undefined + this._types = types + this.RowCtor = null + this.rowAsArray = rowMode === 'array' + if (this.rowAsArray) { + this.parseRow = this._parseRowAsArray + } + this._prebuiltEmptyResultObject = null + } + + // adds a command complete message + addCommandComplete(msg) { + let match + if (msg.text) { + // pure javascript + match = matchRegexp.exec(msg.text) + } else { + // native bindings + match = matchRegexp.exec(msg.command) + } + if (match) { + this.command = match[1] + if (match[3]) { + // COMMAND OID ROWS + this.oid = parseInt(match[2], 10) + this.rowCount = parseInt(match[3], 10) + } else if (match[2]) { + // COMMAND ROWS + this.rowCount = parseInt(match[2], 10) + } + } + } + + _parseRowAsArray(rowData) { + const row = new Array(rowData.length) + for (let i = 0, len = rowData.length; i < len; i++) { + const rawValue = rowData[i] + if (rawValue !== null) { + row[i] = this._parsers[i](rawValue) + } else { + row[i] = null + } + } + return row + } + + parseRow(rowData) { + const row = { ...this._prebuiltEmptyResultObject } + for (let i = 0, len = rowData.length; i < len; i++) { + const rawValue = rowData[i] + const field = this.fields[i].name + if (rawValue !== null) { + const v = this.fields[i].format === 'binary' ? Buffer.from(rawValue) : rawValue + row[field] = this._parsers[i](v) + } else { + row[field] = null + } + } + return row + } + + addRow(row) { + this.rows.push(row) + } + + addFields(fieldDescriptions) { + // clears field definitions + // multiple query statements in 1 action can result in multiple sets + // of rowDescriptions...eg: 'select NOW(); select 1::int;' + // you need to reset the fields + this.fields = fieldDescriptions + if (this.fields.length) { + this._parsers = new Array(fieldDescriptions.length) + } + + const row = Object.create(null) + + for (let i = 0; i < fieldDescriptions.length; i++) { + const desc = fieldDescriptions[i] + row[desc.name] = null + + if (this._types) { + this._parsers[i] = this._types.getTypeParser(desc.dataTypeID, desc.format || 'text') + } else { + this._parsers[i] = types.getTypeParser(desc.dataTypeID, desc.format || 'text') + } + } + + this._prebuiltEmptyResultObject = { ...row } + } +} + +module.exports = Result diff --git a/node_modules/pg/lib/stream.js b/node_modules/pg/lib/stream.js new file mode 100644 index 0000000..edc3018 --- /dev/null +++ b/node_modules/pg/lib/stream.js @@ -0,0 +1,83 @@ +const { getStream, getSecureStream } = getStreamFuncs() + +module.exports = { + /** + * Get a socket stream compatible with the current runtime environment. + * @returns {Duplex} + */ + getStream, + /** + * Get a TLS secured socket, compatible with the current environment, + * using the socket and other settings given in `options`. + * @returns {Duplex} + */ + getSecureStream, +} + +/** + * The stream functions that work in Node.js + */ +function getNodejsStreamFuncs() { + function getStream(ssl) { + const net = require('net') + return new net.Socket() + } + + function getSecureStream(options) { + const tls = require('tls') + return tls.connect(options) + } + return { + getStream, + getSecureStream, + } +} + +/** + * The stream functions that work in Cloudflare Workers + */ +function getCloudflareStreamFuncs() { + function getStream(ssl) { + const { CloudflareSocket } = require('pg-cloudflare') + return new CloudflareSocket(ssl) + } + + function getSecureStream(options) { + options.socket.startTls(options) + return options.socket + } + return { + getStream, + getSecureStream, + } +} + +/** + * Are we running in a Cloudflare Worker? + * + * @returns true if the code is currently running inside a Cloudflare Worker. + */ +function isCloudflareRuntime() { + // Since 2022-03-21 the `global_navigator` compatibility flag is on for Cloudflare Workers + // which means that `navigator.userAgent` will be defined. + // eslint-disable-next-line no-undef + if (typeof navigator === 'object' && navigator !== null && typeof navigator.userAgent === 'string') { + // eslint-disable-next-line no-undef + return navigator.userAgent === 'Cloudflare-Workers' + } + // In case `navigator` or `navigator.userAgent` is not defined then try a more sneaky approach + if (typeof Response === 'function') { + const resp = new Response(null, { cf: { thing: true } }) + if (typeof resp.cf === 'object' && resp.cf !== null && resp.cf.thing) { + return true + } + } + return false +} + +function getStreamFuncs() { + if (isCloudflareRuntime()) { + return getCloudflareStreamFuncs() + } + return getNodejsStreamFuncs() +} diff --git a/node_modules/pg/lib/type-overrides.js b/node_modules/pg/lib/type-overrides.js new file mode 100644 index 0000000..9d219e5 --- /dev/null +++ b/node_modules/pg/lib/type-overrides.js @@ -0,0 +1,35 @@ +'use strict' + +const types = require('pg-types') + +function TypeOverrides(userTypes) { + this._types = userTypes || types + this.text = {} + this.binary = {} +} + +TypeOverrides.prototype.getOverrides = function (format) { + switch (format) { + case 'text': + return this.text + case 'binary': + return this.binary + default: + return {} + } +} + +TypeOverrides.prototype.setTypeParser = function (oid, format, parseFn) { + if (typeof format === 'function') { + parseFn = format + format = 'text' + } + this.getOverrides(format)[oid] = parseFn +} + +TypeOverrides.prototype.getTypeParser = function (oid, format) { + format = format || 'text' + return this.getOverrides(format)[oid] || this._types.getTypeParser(oid, format) +} + +module.exports = TypeOverrides diff --git a/node_modules/pg/lib/utils.js b/node_modules/pg/lib/utils.js new file mode 100644 index 0000000..ba51c82 --- /dev/null +++ b/node_modules/pg/lib/utils.js @@ -0,0 +1,225 @@ +'use strict' + +const defaults = require('./defaults') +const nodeUtils = require('util') + +const { isDate } = require('util/types') + +const invalidDateDeprecationNotice = nodeUtils.deprecate( + () => {}, + 'Sending an invalid date to Postgres is deprecated and will throw an error in the next major version of pg. Ensure any Date object passed as a query parameter is valid.', + 'PG_INVALID_DATE' +) + +function escapeElement(elementRepresentation) { + const escaped = elementRepresentation.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + + return '"' + escaped + '"' +} + +// convert a JS array to a postgres array literal +// uses comma separator so won't work for types like box that use +// a different array separator. +function arrayString(val) { + let result = '{' + for (let i = 0; i < val.length; i++) { + if (i > 0) { + result += ',' + } + let item = val[i] + if (item == null) { + result += 'NULL' + } else if (Array.isArray(item)) { + result += arrayString(item) + } else if (ArrayBuffer.isView(item)) { + if (!(item instanceof Buffer)) { + item = Buffer.from(item.buffer, item.byteOffset, item.byteLength) + } + result += '\\\\x' + item.toString('hex') + } else { + result += escapeElement(prepareValue(item)) + } + } + result += '}' + return result +} + +// converts values from javascript types +// to their 'raw' counterparts for use as a postgres parameter +// note: you can override this function to provide your own conversion mechanism +// for complex types, etc... +const prepareValue = function (val, seen) { + // null and undefined are both null for postgres + if (val == null) { + return null + } + if (typeof val === 'object') { + if (val instanceof Buffer) { + return val + } + if (ArrayBuffer.isView(val)) { + return Buffer.from(val.buffer, val.byteOffset, val.byteLength) + } + if (isDate(val)) { + if (isNaN(val.getTime())) { + invalidDateDeprecationNotice() + } + if (defaults.parseInputDatesAsUTC) { + return dateToStringUTC(val) + } else { + return dateToString(val) + } + } + if (Array.isArray(val)) { + return arrayString(val) + } + + return prepareObject(val, seen) + } + return val.toString() +} + +function prepareObject(val, seen) { + if (val && typeof val.toPostgres === 'function') { + seen = seen || [] + if (seen.indexOf(val) !== -1) { + throw new Error('circular reference detected while preparing "' + val + '" for query') + } + seen.push(val) + + return prepareValue(val.toPostgres(prepareValue), seen) + } + return JSON.stringify(val) +} + +function dateToString(date) { + let offset = -date.getTimezoneOffset() + + let year = date.getFullYear() + const isBCYear = year < 1 + if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation + + let ret = + String(year).padStart(4, '0') + + '-' + + String(date.getMonth() + 1).padStart(2, '0') + + '-' + + String(date.getDate()).padStart(2, '0') + + 'T' + + String(date.getHours()).padStart(2, '0') + + ':' + + String(date.getMinutes()).padStart(2, '0') + + ':' + + String(date.getSeconds()).padStart(2, '0') + + '.' + + String(date.getMilliseconds()).padStart(3, '0') + + if (offset < 0) { + ret += '-' + offset *= -1 + } else { + ret += '+' + } + + ret += String(Math.floor(offset / 60)).padStart(2, '0') + ':' + String(offset % 60).padStart(2, '0') + if (isBCYear) ret += ' BC' + return ret +} + +function dateToStringUTC(date) { + let year = date.getUTCFullYear() + const isBCYear = year < 1 + if (isBCYear) year = Math.abs(year) + 1 // negative years are 1 off their BC representation + + let ret = + String(year).padStart(4, '0') + + '-' + + String(date.getUTCMonth() + 1).padStart(2, '0') + + '-' + + String(date.getUTCDate()).padStart(2, '0') + + 'T' + + String(date.getUTCHours()).padStart(2, '0') + + ':' + + String(date.getUTCMinutes()).padStart(2, '0') + + ':' + + String(date.getUTCSeconds()).padStart(2, '0') + + '.' + + String(date.getUTCMilliseconds()).padStart(3, '0') + + ret += '+00:00' + if (isBCYear) ret += ' BC' + return ret +} + +function normalizeQueryConfig(config, values, callback) { + // can take in strings or config objects + // Copy config so normalization does not mutate the caller's object. + config = typeof config === 'string' ? { text: config } : cloneQueryConfig(config) + if (values) { + if (typeof values === 'function') { + config.callback = values + } else { + config.values = values + } + } + if (callback) { + config.callback = callback + } + return config +} + +function cloneQueryConfig(config) { + if (config == null) { + return config + } + return Object.defineProperties(Object.create(Object.getPrototypeOf(config)), Object.getOwnPropertyDescriptors(config)) +} + +// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c +const escapeIdentifier = function (str) { + return '"' + str.replace(/"/g, '""') + '"' +} + +const escapeLiteral = function (str) { + let hasBackslash = false + let escaped = "'" + + if (str == null) { + return "''" + } + + if (typeof str !== 'string') { + return "''" + } + + for (let i = 0; i < str.length; i++) { + const c = str[i] + if (c === "'") { + escaped += c + c + } else if (c === '\\') { + escaped += c + c + hasBackslash = true + } else { + escaped += c + } + } + + escaped += "'" + + if (hasBackslash === true) { + escaped = ' E' + escaped + } + + return escaped +} + +module.exports = { + prepareValue: function prepareValueWrapper(value) { + // this ensures that extra arguments do not get passed into prepareValue + // by accident, eg: from calling values.map(utils.prepareValue) + return prepareValue(value) + }, + normalizeQueryConfig, + escapeIdentifier, + escapeLiteral, +} diff --git a/node_modules/pg/package.json b/node_modules/pg/package.json new file mode 100644 index 0000000..27b8b9b --- /dev/null +++ b/node_modules/pg/package.json @@ -0,0 +1,76 @@ +{ + "name": "pg", + "version": "8.23.1", + "description": "PostgreSQL client - pure javascript & libpq with the same API", + "keywords": [ + "database", + "libpq", + "pg", + "postgre", + "postgres", + "postgresql", + "rdbms" + ], + "homepage": "https://github.com/brianc/node-postgres", + "repository": { + "type": "git", + "url": "git://github.com/brianc/node-postgres.git", + "directory": "packages/pg" + }, + "author": "Brian Carlson ", + "main": "./lib", + "exports": { + ".": { + "import": "./esm/index.mjs", + "require": "./lib/index.js", + "default": "./lib/index.js" + }, + "./package.json": { + "default": "./package.json" + }, + "./lib/*": "./lib/*.js", + "./lib/*.js": "./lib/*.js" + }, + "dependencies": { + "pg-connection-string": "^2.14.1", + "pg-pool": "^3.14.0", + "pg-protocol": "^1.16.1", + "pg-types": "2.2.0", + "pgpass": "1.0.5" + }, + "devDependencies": { + "@cloudflare/vitest-pool-workers": "0.8.23", + "@cloudflare/workers-types": "^4.20230404.0", + "async": "2.6.4", + "bluebird": "3.7.2", + "co": "4.6.0", + "pg-copy-streams": "0.3.0", + "typescript": "^6.0.3", + "vitest": "~3.0.9", + "wrangler": "^3.x" + }, + "optionalDependencies": { + "pg-cloudflare": "^1.4.1" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + }, + "scripts": { + "test": "make test-all" + }, + "files": [ + "lib", + "esm", + "SPONSORS.md" + ], + "license": "MIT", + "engines": { + "node": ">= 16.0.0" + }, + "gitHead": "0980cefebe0ae461da8883703be049fe13ca96cf" +} diff --git a/node_modules/pgpass/README.md b/node_modules/pgpass/README.md new file mode 100644 index 0000000..bbc5193 --- /dev/null +++ b/node_modules/pgpass/README.md @@ -0,0 +1,74 @@ +# pgpass + +[![Build Status](https://github.com/hoegaarden/pgpass/workflows/CI/badge.svg?branch=master)](https://github.com/hoegaarden/pgpass/actions?query=workflow%3ACI+branch%3Amaster) + +## Install + +```sh +npm install pgpass +``` + +## Usage +```js +var pgPass = require('pgpass'); + +var connInfo = { + 'host' : 'pgserver' , + 'user' : 'the_user_name' , +}; + +pgPass(connInfo, function(pass){ + conn_info.password = pass; + // connect to postgresql server +}); +``` + +## Description + +This module tries to read the `~/.pgpass` file (or the equivalent for windows systems). If the environment variable `PGPASSFILE` is set, this file is used instead. If everything goes right, the password from said file is passed to the callback; if the password cannot be read `undefined` is passed to the callback. + +Cases where `undefined` is returned: + +- the environment variable `PGPASSWORD` is set +- the file cannot be read (wrong permissions, no such file, ...) +- for non windows systems: the file is write-/readable by the group or by other users +- there is no matching line for the given connection info + +There should be no need to use this module directly; it is already included in `node-postgres`. + +## Configuration + +The module reads the environment variable `PGPASS_NO_DEESCAPE` to decide if the the read tokens from the password file should be de-escaped or not. Default is to do de-escaping. For further information on this see [this commit](https://github.com/postgres/postgres/commit/8d15e3ec4fcb735875a8a70a09ec0c62153c3329). + + +## Tests + +There are tests in `./test/`; including linting and coverage testing. Running `npm test` runs: + +- `jshint` +- `mocha` tests +- `jscoverage` and `mocha -R html-cov` + +You can see the coverage report in `coverage.html`. + + +## Development, Patches, Bugs, ... + +If you find Bugs or have improvements, please feel free to open a issue on GitHub. If you provide a pull request, I'm more than happy to merge them, just make sure to add tests for your changes. + +## Links + +- https://github.com/hoegaarden/node-pgpass +- http://www.postgresql.org/docs/current/static/libpq-pgpass.html +- https://wiki.postgresql.org/wiki/Pgpass +- https://github.com/postgres/postgres/blob/master/src/interfaces/libpq/fe-connect.c + +## License + +Copyright (c) 2013-2016 Hannes Hörl + +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/node_modules/pgpass/lib/helper.js b/node_modules/pgpass/lib/helper.js new file mode 100644 index 0000000..f988460 --- /dev/null +++ b/node_modules/pgpass/lib/helper.js @@ -0,0 +1,233 @@ +'use strict'; + +var path = require('path') + , Stream = require('stream').Stream + , split = require('split2') + , util = require('util') + , defaultPort = 5432 + , isWin = (process.platform === 'win32') + , warnStream = process.stderr +; + + +var S_IRWXG = 56 // 00070(8) + , S_IRWXO = 7 // 00007(8) + , S_IFMT = 61440 // 00170000(8) + , S_IFREG = 32768 // 0100000(8) +; +function isRegFile(mode) { + return ((mode & S_IFMT) == S_IFREG); +} + +var fieldNames = [ 'host', 'port', 'database', 'user', 'password' ]; +var nrOfFields = fieldNames.length; +var passKey = fieldNames[ nrOfFields -1 ]; + + +function warn() { + var isWritable = ( + warnStream instanceof Stream && + true === warnStream.writable + ); + + if (isWritable) { + var args = Array.prototype.slice.call(arguments).concat("\n"); + warnStream.write( util.format.apply(util, args) ); + } +} + + +Object.defineProperty(module.exports, 'isWin', { + get : function() { + return isWin; + } , + set : function(val) { + isWin = val; + } +}); + + +module.exports.warnTo = function(stream) { + var old = warnStream; + warnStream = stream; + return old; +}; + +module.exports.getFileName = function(rawEnv){ + var env = rawEnv || process.env; + var file = env.PGPASSFILE || ( + isWin ? + path.join( env.APPDATA || './' , 'postgresql', 'pgpass.conf' ) : + path.join( env.HOME || './', '.pgpass' ) + ); + return file; +}; + +module.exports.usePgPass = function(stats, fname) { + if (Object.prototype.hasOwnProperty.call(process.env, 'PGPASSWORD')) { + return false; + } + + if (isWin) { + return true; + } + + fname = fname || ''; + + if (! isRegFile(stats.mode)) { + warn('WARNING: password file "%s" is not a plain file', fname); + return false; + } + + if (stats.mode & (S_IRWXG | S_IRWXO)) { + /* If password file is insecure, alert the user and ignore it. */ + warn('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less', fname); + return false; + } + + return true; +}; + + +var matcher = module.exports.match = function(connInfo, entry) { + return fieldNames.slice(0, -1).reduce(function(prev, field, idx){ + if (idx == 1) { + // the port + if ( Number( connInfo[field] || defaultPort ) === Number( entry[field] ) ) { + return prev && true; + } + } + return prev && ( + entry[field] === '*' || + entry[field] === connInfo[field] + ); + }, true); +}; + + +module.exports.getPassword = function(connInfo, stream, cb) { + var pass; + var lineStream = stream.pipe(split()); + + function onLine(line) { + var entry = parseLine(line); + if (entry && isValidEntry(entry) && matcher(connInfo, entry)) { + pass = entry[passKey]; + lineStream.end(); // -> calls onEnd(), but pass is set now + } + } + + var onEnd = function() { + stream.destroy(); + cb(pass); + }; + + var onErr = function(err) { + stream.destroy(); + warn('WARNING: error on reading file: %s', err); + cb(undefined); + }; + + stream.on('error', onErr); + lineStream + .on('data', onLine) + .on('end', onEnd) + .on('error', onErr) + ; + +}; + + +var parseLine = module.exports.parseLine = function(line) { + if (line.length < 11 || line.match(/^\s+#/)) { + return null; + } + + var curChar = ''; + var prevChar = ''; + var fieldIdx = 0; + var startIdx = 0; + var endIdx = 0; + var obj = {}; + var isLastField = false; + var addToObj = function(idx, i0, i1) { + var field = line.substring(i0, i1); + + if (! Object.hasOwnProperty.call(process.env, 'PGPASS_NO_DEESCAPE')) { + field = field.replace(/\\([:\\])/g, '$1'); + } + + obj[ fieldNames[idx] ] = field; + }; + + for (var i = 0 ; i < line.length-1 ; i += 1) { + curChar = line.charAt(i+1); + prevChar = line.charAt(i); + + isLastField = (fieldIdx == nrOfFields-1); + + if (isLastField) { + addToObj(fieldIdx, startIdx); + break; + } + + if (i >= 0 && curChar == ':' && prevChar !== '\\') { + addToObj(fieldIdx, startIdx, i+1); + + startIdx = i+2; + fieldIdx += 1; + } + } + + obj = ( Object.keys(obj).length === nrOfFields ) ? obj : null; + + return obj; +}; + + +var isValidEntry = module.exports.isValidEntry = function(entry){ + var rules = { + // host + 0 : function(x){ + return x.length > 0; + } , + // port + 1 : function(x){ + if (x === '*') { + return true; + } + x = Number(x); + return ( + isFinite(x) && + x > 0 && + x < 9007199254740992 && + Math.floor(x) === x + ); + } , + // database + 2 : function(x){ + return x.length > 0; + } , + // username + 3 : function(x){ + return x.length > 0; + } , + // password + 4 : function(x){ + return x.length > 0; + } + }; + + for (var idx = 0 ; idx < fieldNames.length ; idx += 1) { + var rule = rules[idx]; + var value = entry[ fieldNames[idx] ] || ''; + + var res = rule(value); + if (!res) { + return false; + } + } + + return true; +}; + diff --git a/node_modules/pgpass/lib/index.js b/node_modules/pgpass/lib/index.js new file mode 100644 index 0000000..ecfcf30 --- /dev/null +++ b/node_modules/pgpass/lib/index.js @@ -0,0 +1,23 @@ +'use strict'; + +var path = require('path') + , fs = require('fs') + , helper = require('./helper.js') +; + + +module.exports = function(connInfo, cb) { + var file = helper.getFileName(); + + fs.stat(file, function(err, stat){ + if (err || !helper.usePgPass(stat, file)) { + return cb(undefined); + } + + var st = fs.createReadStream(file); + + helper.getPassword(connInfo, st, cb); + }); +}; + +module.exports.warnTo = helper.warnTo; diff --git a/node_modules/pgpass/package.json b/node_modules/pgpass/package.json new file mode 100644 index 0000000..22bfe84 --- /dev/null +++ b/node_modules/pgpass/package.json @@ -0,0 +1,41 @@ +{ + "name": "pgpass", + "version": "1.0.5", + "description": "Module for reading .pgpass", + "main": "lib/index", + "scripts": { + "pretest": "chmod 600 ./test/_pgpass", + "_hint": "jshint --exclude node_modules --verbose lib test", + "_test": "mocha --recursive -R list", + "_covered_test": "nyc --reporter html --reporter text \"$npm_execpath\" run _test", + "test": "\"$npm_execpath\" run _hint && \"$npm_execpath\" run _covered_test" + }, + "author": "Hannes Hörl ", + "license": "MIT", + "dependencies": { + "split2": "^4.1.0" + }, + "devDependencies": { + "jshint": "^2.12.0", + "mocha": "^8.2.0", + "nyc": "^15.1.0", + "pg": "^8.4.1", + "pg-escape": "^0.2.0", + "pg-native": "3.0.0", + "resumer": "0.0.0", + "tmp": "^0.2.1", + "which": "^2.0.2" + }, + "keywords": [ + "postgres", + "pg", + "pgpass", + "password", + "postgresql" + ], + "bugs": "https://github.com/hoegaarden/pgpass/issues", + "repository": { + "type": "git", + "url": "https://github.com/hoegaarden/pgpass.git" + } +} diff --git a/node_modules/pngjs/.eslintignore b/node_modules/pngjs/.eslintignore new file mode 100644 index 0000000..188bbcf --- /dev/null +++ b/node_modules/pngjs/.eslintignore @@ -0,0 +1,2 @@ +/browser.js +/test/imagediff.js diff --git a/node_modules/pngjs/.eslintrc.json b/node_modules/pngjs/.eslintrc.json new file mode 100644 index 0000000..a66e018 --- /dev/null +++ b/node_modules/pngjs/.eslintrc.json @@ -0,0 +1,19 @@ +{ + "parserOptions": { "ecmaVersion": 2018 }, + "extends": ["eslint:recommended", "prettier"], + "env": { + "node": true, + "es6": true + }, + "rules": { + "no-var": "error" + }, + "overrides": [ + { + "files": ["test/*.js", "examples/*.js"], + "rules": { + "no-console": "off" + } + } + ] +} diff --git a/node_modules/pngjs/.prettierignore b/node_modules/pngjs/.prettierignore new file mode 100644 index 0000000..8af2c5d --- /dev/null +++ b/node_modules/pngjs/.prettierignore @@ -0,0 +1,3 @@ +/browser.js +/test/imagediff.js +.nyc_output diff --git a/node_modules/pngjs/LICENSE b/node_modules/pngjs/LICENSE new file mode 100644 index 0000000..6942e25 --- /dev/null +++ b/node_modules/pngjs/LICENSE @@ -0,0 +1,20 @@ +pngjs2 original work Copyright (c) 2015 Luke Page & Original Contributors +pngjs derived work Copyright (c) 2012 Kuba Niegowski + +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/node_modules/pngjs/README.md b/node_modules/pngjs/README.md new file mode 100644 index 0000000..1b07d33 --- /dev/null +++ b/node_modules/pngjs/README.md @@ -0,0 +1,429 @@ +[![Build Status](https://travis-ci.com/lukeapage/pngjs.svg?branch=master)](https://travis-ci.com/lukeapage/pngjs) [![Build status](https://ci.appveyor.com/api/projects/status/qo5x8ayutr028108/branch/master?svg=true)](https://ci.appveyor.com/project/lukeapage/pngjs/branch/master) [![codecov](https://codecov.io/gh/lukeapage/pngjs/branch/master/graph/badge.svg)](https://codecov.io/gh/lukeapage/pngjs) [![npm version](https://badge.fury.io/js/pngjs.svg)](http://badge.fury.io/js/pngjs) + +# pngjs + +Simple PNG encoder/decoder for Node.js with no dependencies. + +Based on the original [pngjs](https://github.com/niegowski/node-pngjs) with the follow enhancements. + +- Support for reading 1,2,4 & 16 bit files +- Support for reading interlace files +- Support for reading `tTRNS` transparent colours +- Support for writing colortype 0 (grayscale), colortype 2 (RGB), colortype 4 (grayscale alpha) and colortype 6 (RGBA) +- Sync interface as well as async +- API compatible with pngjs and node-pngjs + +Known lack of support for: + +- Extended PNG e.g. Animation +- Writing in colortype 3 (indexed color) + +# Table of Contents + +- [Requirements](#requirements) +- [Comparison Table](#comparison-table) +- [Tests](#tests) +- [Installation](#installation) +- [Browser](#browser) +- [Example](#example) +- [Async API](#async-api) +- [Sync API](#sync-api) +- [Changelog](#changelog) + +# Requirements + +- Node.js v4 (use older v2.3.0 for 0.10/0.12/iojs support) + +# Comparison Table + +| Name | Forked From | Sync | Async | 16 Bit | 1/2/4 Bit | Interlace | Gamma | Encodes | Tested | +| ------------- | ----------- | ---- | ----- | ------ | --------- | --------- | ------ | ------- | ------ | +| pngjs | | Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | +| node-png | pngjs | No | Yes | No | No | No | Hidden | Yes | Manual | +| png-coder | pngjs | No | Yes | Yes | No | No | Hidden | Yes | Manual | +| pngparse | | No | Yes | No | Yes | No | No | No | Yes | +| pngparse-sync | pngparse | Yes | No | No | Yes | No | No | No | Yes | +| png-async | | No | Yes | No | No | No | No | Yes | Yes | +| png-js | | No | Yes | No | No | No | No | No | No | + +Native C++ node decoders: + +- png +- png-sync (sync version of above) +- pixel-png +- png-img + +# Tests + +Tested using [PNG Suite](http://www.schaik.com/pngsuite/). We read every file into pngjs, output it in standard 8bit colour, synchronously and asynchronously, then compare the original with the newly saved images. + +To run the tests, fetch the repo (tests are not distributed via npm) and install with `npm i`, run `npm test`. + +The only thing not converted is gamma correction - this is because multiple vendors will do gamma correction differently, so the tests will have different results on different browsers. + +In addition we use a tolerance of 3 for 16 bit images in PhantomJS because PhantomJS seems to have non-compliant rules for downscaling 16 bit images. + +# Installation + +``` +$ npm install pngjs --save +``` + +# Browser + +The package has been build with a [Browserify](browserify.org) version (`npm run browserify`) and you can use the browser version by including in your code: + +``` +import { PNG } from 'pngjs/browser'; +``` + +# Example + +```js +var fs = require("fs"), + PNG = require("pngjs").PNG; + +fs.createReadStream("in.png") + .pipe( + new PNG({ + filterType: 4, + }) + ) + .on("parsed", function () { + for (var y = 0; y < this.height; y++) { + for (var x = 0; x < this.width; x++) { + var idx = (this.width * y + x) << 2; + + // invert color + this.data[idx] = 255 - this.data[idx]; + this.data[idx + 1] = 255 - this.data[idx + 1]; + this.data[idx + 2] = 255 - this.data[idx + 2]; + + // and reduce opacity + this.data[idx + 3] = this.data[idx + 3] >> 1; + } + } + + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +For more examples see `examples` folder. + +# Async API + +As input any color type is accepted (grayscale, rgb, palette, grayscale with alpha, rgb with alpha) but 8 bit per sample (channel) is the only supported bit depth. Interlaced mode is not supported. + +## Class: PNG + +`PNG` is readable and writable `Stream`. + +### Options + +- `width` - use this with `height` if you want to create png from scratch +- `height` - as above +- `checkCRC` - whether parser should be strict about checksums in source stream (default: `true`) +- `deflateChunkSize` - chunk size used for deflating data chunks, this should be power of 2 and must not be less than 256 and more than 32\*1024 (default: 32 kB) +- `deflateLevel` - compression level for deflate (default: 9) +- `deflateStrategy` - compression strategy for deflate (default: 3) +- `deflateFactory` - deflate stream factory (default: `zlib.createDeflate`) +- `filterType` - png filtering method for scanlines (default: -1 => auto, accepts array of numbers 0-4) +- `colorType` - the output colorType - see constants. 0 = grayscale, no alpha, 2 = color, no alpha, 4 = grayscale & alpha, 6 = color & alpha. Default currently 6, but in the future may calculate best mode. +- `inputColorType` - the input colorType - see constants. Default is 6 (RGBA) +- `bitDepth` - the bitDepth of the output, 8 or 16 bits. Input data is expected to have this bit depth. + 16 bit data is expected in the system endianness (Default: 8) +- `inputHasAlpha` - whether the input bitmap has 4 bytes per pixel (rgb and alpha) or 3 (rgb - no alpha). +- `bgColor` - an object containing red, green, and blue values between 0 and 255 + that is used when packing a PNG if alpha is not to be included (default: 255,255,255) + +### Event "metadata" + +`function(metadata) { }` +Image's header has been parsed, metadata contains this information: + +- `width` image size in pixels +- `height` image size in pixels +- `palette` image is paletted +- `color` image is not grayscale +- `alpha` image contains alpha channel +- `interlace` image is interlaced + +### Event: "parsed" + +`function(data) { }` +Input image has been completely parsed, `data` is complete and ready for modification. + +### Event: "error" + +`function(error) { }` + +### png.parse(data, [callback]) + +Parses PNG file data. Can be `String` or `Buffer`. Alternatively you can stream data to instance of PNG. + +Optional `callback` is once called on `error` or `parsed`. The callback gets +two arguments `(err, data)`. + +Returns `this` for method chaining. + +#### Example + +```js +new PNG({ filterType: 4 }).parse(imageData, function (error, data) { + console.log(error, data); +}); +``` + +### png.pack() + +Starts converting data to PNG file Stream. + +Returns `this` for method chaining. + +### png.bitblt(dst, sx, sy, w, h, dx, dy) + +Helper for image manipulation, copies a rectangle of pixels from current (i.e. the source) image (`sx`, `sy`, `w`, `h`) to `dst` image (at `dx`, `dy`). + +Returns `this` for method chaining. + +For example, the following code copies the top-left 100x50 px of `in.png` into dst and writes it to `out.png`: + +```js +var dst = new PNG({ width: 100, height: 50 }); +fs.createReadStream("in.png") + .pipe(new PNG()) + .on("parsed", function () { + this.bitblt(dst, 0, 0, 100, 50, 0, 0); + dst.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +### Property: adjustGamma() + +Helper that takes data and adjusts it to be gamma corrected. Note that it is not 100% reliable with transparent colours because that requires knowing the background colour the bitmap is rendered on to. + +In tests against PNG suite it compared 100% with chrome on all 8 bit and below images. On IE there were some differences. + +The following example reads a file, adjusts the gamma (which sets the gamma to 0) and writes it out again, effectively removing any gamma correction from the image. + +```js +fs.createReadStream("in.png") + .pipe(new PNG()) + .on("parsed", function () { + this.adjustGamma(); + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +### Property: width + +Width of image in pixels + +### Property: height + +Height of image in pixels + +### Property: data + +Buffer of image pixel data. Every pixel consists 4 bytes: R, G, B, A (opacity). + +### Property: gamma + +Gamma of image (0 if not specified) + +## Packing a PNG and removing alpha (RGBA to RGB) + +When removing the alpha channel from an image, there needs to be a background color to correctly +convert each pixel's transparency to the appropriate RGB value. By default, pngjs will flatten +the image against a white background. You can override this in the options: + +```js +var fs = require("fs"), + PNG = require("pngjs").PNG; + +fs.createReadStream("in.png") + .pipe( + new PNG({ + colorType: 2, + bgColor: { + red: 0, + green: 255, + blue: 0, + }, + }) + ) + .on("parsed", function () { + this.pack().pipe(fs.createWriteStream("out.png")); + }); +``` + +# Sync API + +## PNG.sync + +### PNG.sync.read(buffer) + +Take a buffer and returns a PNG image. The properties on the image include the meta data and `data` as per the async API above. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +``` + +### PNG.sync.write(png) + +Take a PNG image and returns a buffer. The properties on the image include the meta data and `data` as per the async API above. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +var options = { colorType: 6 }; +var buffer = PNG.sync.write(png, options); +fs.writeFileSync('out.png', buffer); +``` + +### PNG.adjustGamma(src) + +Adjusts the gamma of a sync image. See the async adjustGamma. + +``` +var data = fs.readFileSync('in.png'); +var png = PNG.sync.read(data); +PNG.adjustGamma(png); +``` + +# Changelog + +### 5.0.0 - 15/04/2020 + +- Drop support for Node 8 +- Browserified bundle may now contain ES20(15-20) code if the supported node version supports it. Please run the browserified version through babel if you need to support older browsers. + +### 4.0.1 - 15/04/2020 + +- Fix to possible null reference in nextTick of async method + +### 4.0.0 - 09/04/2020 + +- Fix issue in newer nodes with using Buffer +- Fix async issue with some png files +- Drop support for Node 4 & 6 + +### 3.4.0 - 09/03/2019 + +- Include whether the png has alpha in the meta data +- emit an error if the image is truncated instead of hanging +- Add a browserified version +- speed up some mapping functions + +### 3.3.3 - 19/04/2018 + +- Real fix for node 9 + +### 3.3.2 - 16/02/2018 + +- Fix for node 9 + +### 3.3.1 - 15/11/2017 + +- Bugfixes and removal of es6 + +### 3.3.0 + +- Add writing 16 bit channels and support for grayscale input + +### 3.2.0 - 30/04/2017 + +- Support for encoding 8-bit grayscale images + +### 3.1.0 - 30/04/2017 + +- Support for pngs with zlib chunks that are malformed after valid data + +### 3.0.1 - 16/02/2017 + +- Fix single pixel pngs + +### 3.0.0 - 03/08/2016 + +- Drop support for node below v4 and iojs. Pin to 2.3.0 to use with old, unsupported or patched node versions. + +### 2.3.0 - 22/04/2016 + +- Support for sync in node 0.10 + +### 2.2.0 - 04/12/2015 + +- Add sync write api +- Fix newfile example +- Correct comparison table + +### 2.1.0 - 28/10/2015 + +- rename package to pngjs +- added 'bgColor' option + +### 2.0.0 - 08/10/2015 + +- fixes to readme +- _breaking change_ - bitblt on the png prototype now doesn't take a unused, unnecessary src first argument + +### 1.2.0 - 13/09/2015 + +- support passing colorType to write PNG's and writing bitmaps without alpha information + +### 1.1.0 - 07/09/2015 + +- support passing a deflate factory for controlled compression + +### 1.0.2 - 22/08/2015 + +- Expose all PNG creation info + +### 1.0.1 - 21/08/2015 + +- Fix non square interlaced files + +### 1.0.0 - 08/08/2015 + +- More tests +- source linted +- maintainability refactorings +- async API - exceptions in reading now emit warnings +- documentation improvement - sync api now documented, adjustGamma documented +- breaking change - gamma chunk is now written. previously a read then write would destroy gamma information, now it is persisted. + +### 0.0.3 - 03/08/2015 + +- Error handling fixes +- ignore files for smaller npm footprint + +### 0.0.2 - 02/08/2015 + +- Bugfixes to interlacing, support for transparent colours + +### 0.0.1 - 02/08/2015 + +- Initial release, see pngjs for older changelog. + +# License + +(The MIT License) + +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/node_modules/pngjs/browser.js b/node_modules/pngjs/browser.js new file mode 100644 index 0000000..9daae91 --- /dev/null +++ b/node_modules/pngjs/browser.js @@ -0,0 +1,16096 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.png = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o= data.length) { + throw new Error("Ran out of data"); + } + + let pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = data[rawPos + 1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, data, pxPos, rawPos) { + if (rawPos + 2 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = 0xff; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, data, pxPos, rawPos) { + if (rawPos + 3 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = data[rawPos + 3]; + }, +]; + +let pixelBppCustomMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = maxBit; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function (pxData, pixelData, pxPos) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = pixelData[1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = maxBit; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, pixelData, pxPos) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = pixelData[3]; + }, +]; + +function bitRetriever(data, depth) { + let leftOver = []; + let i = 0; + + function split() { + if (i === data.length) { + throw new Error("Ran out of data"); + } + let byte = data[i]; + i++; + let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1; + switch (depth) { + default: + throw new Error("unrecognised depth"); + case 16: + byte2 = data[i]; + i++; + leftOver.push((byte << 8) + byte2); + break; + case 4: + byte2 = byte & 0x0f; + byte1 = byte >> 4; + leftOver.push(byte1, byte2); + break; + case 2: + byte4 = byte & 3; + byte3 = (byte >> 2) & 3; + byte2 = (byte >> 4) & 3; + byte1 = (byte >> 6) & 3; + leftOver.push(byte1, byte2, byte3, byte4); + break; + case 1: + byte8 = byte & 1; + byte7 = (byte >> 1) & 1; + byte6 = (byte >> 2) & 1; + byte5 = (byte >> 3) & 1; + byte4 = (byte >> 4) & 1; + byte3 = (byte >> 5) & 1; + byte2 = (byte >> 6) & 1; + byte1 = (byte >> 7) & 1; + leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8); + break; + } + } + + return { + get: function (count) { + while (leftOver.length < count) { + split(); + } + let returner = leftOver.slice(0, count); + leftOver = leftOver.slice(count); + return returner; + }, + resetAfterLine: function () { + leftOver.length = 0; + }, + end: function () { + if (i !== data.length) { + throw new Error("extra data found"); + } + }, + }; +} + +function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pxPos = getPxPos(x, y, imagePass); + pixelBppMapper[bpp](pxData, data, pxPos, rawPos); + rawPos += bpp; //eslint-disable-line no-param-reassign + } + } + return rawPos; +} + +function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pixelData = bits.get(bpp); + let pxPos = getPxPos(x, y, imagePass); + pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); + } + bits.resetAfterLine(); + } +} + +exports.dataToBitMap = function (data, bitmapInfo) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let depth = bitmapInfo.depth; + let bpp = bitmapInfo.bpp; + let interlace = bitmapInfo.interlace; + let bits; + + if (depth !== 8) { + bits = bitRetriever(data, depth); + } + let pxData; + if (depth <= 8) { + pxData = Buffer.alloc(width * height * 4); + } else { + pxData = new Uint16Array(width * height * 4); + } + let maxBit = Math.pow(2, depth) - 1; + let rawPos = 0; + let images; + let getPxPos; + + if (interlace) { + images = interlaceUtils.getImagePasses(width, height); + getPxPos = interlaceUtils.getInterlaceIterator(width, height); + } else { + let nonInterlacedPxPos = 0; + getPxPos = function () { + let returner = nonInterlacedPxPos; + nonInterlacedPxPos += 4; + return returner; + }; + images = [{ width: width, height: height }]; + } + + for (let imageIndex = 0; imageIndex < images.length; imageIndex++) { + if (depth === 8) { + rawPos = mapImage8Bit( + images[imageIndex], + pxData, + getPxPos, + bpp, + data, + rawPos + ); + } else { + mapImageCustomBit( + images[imageIndex], + pxData, + getPxPos, + bpp, + bits, + maxBit + ); + } + } + if (depth === 8) { + if (rawPos !== data.length) { + throw new Error("extra data found"); + } + } else { + bits.end(); + } + + return pxData; +}; + +}).call(this,require("buffer").Buffer) +},{"./interlace":11,"buffer":28}],2:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let constants = require("./constants"); + +module.exports = function (dataIn, width, height, options) { + let outHasAlpha = + [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf( + options.colorType + ) !== -1; + if (options.colorType === options.inputColorType) { + let bigEndian = (function () { + let buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] !== 256; + })(); + // If no need to convert to grayscale and alpha is present/absent in both, take a fast route + if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) { + return dataIn; + } + } + + // map to a UInt16 array if data is 16bit, fix endianness below + let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); + + let maxValue = 255; + let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType]; + if (inBpp === 4 && !options.inputHasAlpha) { + inBpp = 3; + } + let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType]; + if (options.bitDepth === 16) { + maxValue = 65535; + outBpp *= 2; + } + let outData = Buffer.alloc(width * height * outBpp); + + let inIndex = 0; + let outIndex = 0; + + let bgColor = options.bgColor || {}; + if (bgColor.red === undefined) { + bgColor.red = maxValue; + } + if (bgColor.green === undefined) { + bgColor.green = maxValue; + } + if (bgColor.blue === undefined) { + bgColor.blue = maxValue; + } + + function getRGBA() { + let red; + let green; + let blue; + let alpha = maxValue; + switch (options.inputColorType) { + case constants.COLORTYPE_COLOR_ALPHA: + alpha = data[inIndex + 3]; + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_COLOR: + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_ALPHA: + alpha = data[inIndex + 1]; + red = data[inIndex]; + green = red; + blue = red; + break; + case constants.COLORTYPE_GRAYSCALE: + red = data[inIndex]; + green = red; + blue = red; + break; + default: + throw new Error( + "input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + + if (options.inputHasAlpha) { + if (!outHasAlpha) { + alpha /= maxValue; + red = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), + maxValue + ); + green = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), + maxValue + ); + blue = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), + maxValue + ); + } + } + return { red: red, green: green, blue: blue, alpha: alpha }; + } + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let rgba = getRGBA(data, inIndex); + + switch (options.colorType) { + case constants.COLORTYPE_COLOR_ALPHA: + case constants.COLORTYPE_COLOR: + if (options.bitDepth === 8) { + outData[outIndex] = rgba.red; + outData[outIndex + 1] = rgba.green; + outData[outIndex + 2] = rgba.blue; + if (outHasAlpha) { + outData[outIndex + 3] = rgba.alpha; + } + } else { + outData.writeUInt16BE(rgba.red, outIndex); + outData.writeUInt16BE(rgba.green, outIndex + 2); + outData.writeUInt16BE(rgba.blue, outIndex + 4); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 6); + } + } + break; + case constants.COLORTYPE_ALPHA: + case constants.COLORTYPE_GRAYSCALE: { + // Convert to grayscale and alpha + let grayscale = (rgba.red + rgba.green + rgba.blue) / 3; + if (options.bitDepth === 8) { + outData[outIndex] = grayscale; + if (outHasAlpha) { + outData[outIndex + 1] = rgba.alpha; + } + } else { + outData.writeUInt16BE(grayscale, outIndex); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 2); + } + } + break; + } + default: + throw new Error("unrecognised color Type " + options.colorType); + } + + inIndex += inBpp; + outIndex += outBpp; + } + } + + return outData; +}; + +}).call(this,require("buffer").Buffer) +},{"./constants":4,"buffer":28}],3:[function(require,module,exports){ +(function (process,Buffer){ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); + +let ChunkStream = (module.exports = function () { + Stream.call(this); + + this._buffers = []; + this._buffered = 0; + + this._reads = []; + this._paused = false; + + this._encoding = "utf8"; + this.writable = true; +}); +util.inherits(ChunkStream, Stream); + +ChunkStream.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); + + process.nextTick( + function () { + this._process(); + + // its paused and there is not enought data then ask for more + if (this._paused && this._reads && this._reads.length > 0) { + this._paused = false; + + this.emit("drain"); + } + }.bind(this) + ); +}; + +ChunkStream.prototype.write = function (data, encoding) { + if (!this.writable) { + this.emit("error", new Error("Stream not writable")); + return false; + } + + let dataBuffer; + if (Buffer.isBuffer(data)) { + dataBuffer = data; + } else { + dataBuffer = Buffer.from(data, encoding || this._encoding); + } + + this._buffers.push(dataBuffer); + this._buffered += dataBuffer.length; + + this._process(); + + // ok if there are no more read requests + if (this._reads && this._reads.length === 0) { + this._paused = true; + } + + return this.writable && !this._paused; +}; + +ChunkStream.prototype.end = function (data, encoding) { + if (data) { + this.write(data, encoding); + } + + this.writable = false; + + // already destroyed + if (!this._buffers) { + return; + } + + // enqueue or handle end + if (this._buffers.length === 0) { + this._end(); + } else { + this._buffers.push(null); + this._process(); + } +}; + +ChunkStream.prototype.destroySoon = ChunkStream.prototype.end; + +ChunkStream.prototype._end = function () { + if (this._reads.length > 0) { + this.emit("error", new Error("Unexpected end of input")); + } + + this.destroy(); +}; + +ChunkStream.prototype.destroy = function () { + if (!this._buffers) { + return; + } + + this.writable = false; + this._reads = null; + this._buffers = null; + + this.emit("close"); +}; + +ChunkStream.prototype._processReadAllowingLess = function (read) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + // first we need to peek into first buffer + let smallerBuf = this._buffers[0]; + + // ok there is more data than we need + if (smallerBuf.length > read.length) { + this._buffered -= read.length; + this._buffers[0] = smallerBuf.slice(read.length); + + read.func.call(this, smallerBuf.slice(0, read.length)); + } else { + // ok this is less than maximum length so use it all + this._buffered -= smallerBuf.length; + this._buffers.shift(); // == smallerBuf + + read.func.call(this, smallerBuf); + } +}; + +ChunkStream.prototype._processRead = function (read) { + this._reads.shift(); // == read + + let pos = 0; + let count = 0; + let data = Buffer.alloc(read.length); + + // create buffer for all data + while (pos < read.length) { + let buf = this._buffers[count++]; + let len = Math.min(buf.length, read.length - pos); + + buf.copy(data, pos, 0, len); + pos += len; + + // last buffer wasn't used all so just slice it and leave + if (len !== buf.length) { + this._buffers[--count] = buf.slice(len); + } + } + + // remove all used buffers + if (count > 0) { + this._buffers.splice(0, count); + } + + this._buffered -= read.length; + + read.func.call(this, data); +}; + +ChunkStream.prototype._process = function () { + try { + // as long as there is any data and read requests + while (this._buffered > 0 && this._reads && this._reads.length > 0) { + let read = this._reads[0]; + + // read any data (but no more than length) + if (read.allowLess) { + this._processReadAllowingLess(read); + } else if (this._buffered >= read.length) { + // ok we can meet some expectations + + this._processRead(read); + } else { + // not enought data to satisfy first request in queue + // so we need to wait for more + break; + } + } + + if (this._buffers && !this.writable) { + this._end(); + } + } catch (ex) { + this.emit("error", ex); + } +}; + +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":47,"buffer":28,"stream":63,"util":67}],4:[function(require,module,exports){ +"use strict"; + +module.exports = { + PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], + + TYPE_IHDR: 0x49484452, + TYPE_IEND: 0x49454e44, + TYPE_IDAT: 0x49444154, + TYPE_PLTE: 0x504c5445, + TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase + TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase + + // color-type bits + COLORTYPE_GRAYSCALE: 0, + COLORTYPE_PALETTE: 1, + COLORTYPE_COLOR: 2, + COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha + + // color-type combinations + COLORTYPE_PALETTE_COLOR: 3, + COLORTYPE_COLOR_ALPHA: 6, + + COLORTYPE_TO_BPP_MAP: { + 0: 1, + 2: 3, + 3: 1, + 4: 2, + 6: 4, + }, + + GAMMA_DIVISION: 100000, +}; + +},{}],5:[function(require,module,exports){ +"use strict"; + +let crcTable = []; + +(function () { + for (let i = 0; i < 256; i++) { + let currentCrc = i; + for (let j = 0; j < 8; j++) { + if (currentCrc & 1) { + currentCrc = 0xedb88320 ^ (currentCrc >>> 1); + } else { + currentCrc = currentCrc >>> 1; + } + } + crcTable[i] = currentCrc; + } +})(); + +let CrcCalculator = (module.exports = function () { + this._crc = -1; +}); + +CrcCalculator.prototype.write = function (data) { + for (let i = 0; i < data.length; i++) { + this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8); + } + return true; +}; + +CrcCalculator.prototype.crc32 = function () { + return this._crc ^ -1; +}; + +CrcCalculator.crc32 = function (buf) { + let crc = -1; + for (let i = 0; i < buf.length; i++) { + crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return crc ^ -1; +}; + +},{}],6:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let paethPredictor = require("./paeth-predictor"); + +function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + rawData[rawPos + x] = pxData[pxPos + x]; + } +} + +function filterSumNone(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + + for (let i = pxPos; i < length; i++) { + sum += Math.abs(pxData[i]); + } + return sum; +} + +function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + rawData[rawPos + x] = val; + } +} + +function filterSumSub(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + sum += Math.abs(val); + } + + return sum; +} + +function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - up; + + rawData[rawPos + x] = val; + } +} + +function filterSumUp(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + for (let x = pxPos; x < length; x++) { + let up = pxPos > 0 ? pxData[x - byteWidth] : 0; + let val = pxData[x] - up; + + sum += Math.abs(val); + } + + return sum; +} + +function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + rawData[rawPos + x] = val; + } +} + +function filterSumAvg(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + sum += Math.abs(val); + } + + return sum; +} + +function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + rawData[rawPos + x] = val; + } +} + +function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + sum += Math.abs(val); + } + + return sum; +} + +let filters = { + 0: filterNone, + 1: filterSub, + 2: filterUp, + 3: filterAvg, + 4: filterPaeth, +}; + +let filterSums = { + 0: filterSumNone, + 1: filterSumSub, + 2: filterSumUp, + 3: filterSumAvg, + 4: filterSumPaeth, +}; + +module.exports = function (pxData, width, height, options, bpp) { + let filterTypes; + if (!("filterType" in options) || options.filterType === -1) { + filterTypes = [0, 1, 2, 3, 4]; + } else if (typeof options.filterType === "number") { + filterTypes = [options.filterType]; + } else { + throw new Error("unrecognised filter types"); + } + + if (options.bitDepth === 16) { + bpp *= 2; + } + let byteWidth = width * bpp; + let rawPos = 0; + let pxPos = 0; + let rawData = Buffer.alloc((byteWidth + 1) * height); + + let sel = filterTypes[0]; + + for (let y = 0; y < height; y++) { + if (filterTypes.length > 1) { + // find best filter for this line (with lowest sum of values) + let min = Infinity; + + for (let i = 0; i < filterTypes.length; i++) { + let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp); + if (sum < min) { + sel = filterTypes[i]; + min = sum; + } + } + } + + rawData[rawPos] = sel; + rawPos++; + filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); + rawPos += byteWidth; + pxPos += byteWidth; + } + return rawData; +}; + +}).call(this,require("buffer").Buffer) +},{"./paeth-predictor":15,"buffer":28}],7:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let util = require("util"); +let ChunkStream = require("./chunkstream"); +let Filter = require("./filter-parse"); + +let FilterAsync = (module.exports = function (bitmapInfo) { + ChunkStream.call(this); + + let buffers = []; + let that = this; + this._filter = new Filter(bitmapInfo, { + read: this.read.bind(this), + write: function (buffer) { + buffers.push(buffer); + }, + complete: function () { + that.emit("complete", Buffer.concat(buffers)); + }, + }); + + this._filter.start(); +}); +util.inherits(FilterAsync, ChunkStream); + +}).call(this,require("buffer").Buffer) +},{"./chunkstream":3,"./filter-parse":9,"buffer":28,"util":67}],8:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let SyncReader = require("./sync-reader"); +let Filter = require("./filter-parse"); + +exports.process = function (inBuffer, bitmapInfo) { + let outBuffers = []; + let reader = new SyncReader(inBuffer); + let filter = new Filter(bitmapInfo, { + read: reader.read.bind(reader), + write: function (bufferPart) { + outBuffers.push(bufferPart); + }, + complete: function () {}, + }); + + filter.start(); + reader.process(); + + return Buffer.concat(outBuffers); +}; + +}).call(this,require("buffer").Buffer) +},{"./filter-parse":9,"./sync-reader":22,"buffer":28}],9:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let interlaceUtils = require("./interlace"); +let paethPredictor = require("./paeth-predictor"); + +function getByteWidth(width, bpp, depth) { + let byteWidth = width * bpp; + if (depth !== 8) { + byteWidth = Math.ceil(byteWidth / (8 / depth)); + } + return byteWidth; +} + +let Filter = (module.exports = function (bitmapInfo, dependencies) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let interlace = bitmapInfo.interlace; + let bpp = bitmapInfo.bpp; + let depth = bitmapInfo.depth; + + this.read = dependencies.read; + this.write = dependencies.write; + this.complete = dependencies.complete; + + this._imageIndex = 0; + this._images = []; + if (interlace) { + let passes = interlaceUtils.getImagePasses(width, height); + for (let i = 0; i < passes.length; i++) { + this._images.push({ + byteWidth: getByteWidth(passes[i].width, bpp, depth), + height: passes[i].height, + lineIndex: 0, + }); + } + } else { + this._images.push({ + byteWidth: getByteWidth(width, bpp, depth), + height: height, + lineIndex: 0, + }); + } + + // when filtering the line we look at the pixel to the left + // the spec also says it is done on a byte level regardless of the number of pixels + // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back + // a pixel rather than just a different byte part. However if we are sub byte, we ignore. + if (depth === 8) { + this._xComparison = bpp; + } else if (depth === 16) { + this._xComparison = bpp * 2; + } else { + this._xComparison = 1; + } +}); + +Filter.prototype.start = function () { + this.read( + this._images[this._imageIndex].byteWidth + 1, + this._reverseFilterLine.bind(this) + ); +}; + +Filter.prototype._unFilterType1 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + unfilteredLine[x] = rawByte + f1Left; + } +}; + +Filter.prototype._unFilterType2 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f2Up = lastLine ? lastLine[x] : 0; + unfilteredLine[x] = rawByte + f2Up; + } +}; + +Filter.prototype._unFilterType3 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f3Up = lastLine ? lastLine[x] : 0; + let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f3Add = Math.floor((f3Left + f3Up) / 2); + unfilteredLine[x] = rawByte + f3Add; + } +}; + +Filter.prototype._unFilterType4 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f4Up = lastLine ? lastLine[x] : 0; + let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; + let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); + unfilteredLine[x] = rawByte + f4Add; + } +}; + +Filter.prototype._reverseFilterLine = function (rawData) { + let filter = rawData[0]; + let unfilteredLine; + let currentImage = this._images[this._imageIndex]; + let byteWidth = currentImage.byteWidth; + + if (filter === 0) { + unfilteredLine = rawData.slice(1, byteWidth + 1); + } else { + unfilteredLine = Buffer.alloc(byteWidth); + + switch (filter) { + case 1: + this._unFilterType1(rawData, unfilteredLine, byteWidth); + break; + case 2: + this._unFilterType2(rawData, unfilteredLine, byteWidth); + break; + case 3: + this._unFilterType3(rawData, unfilteredLine, byteWidth); + break; + case 4: + this._unFilterType4(rawData, unfilteredLine, byteWidth); + break; + default: + throw new Error("Unrecognised filter type - " + filter); + } + } + + this.write(unfilteredLine); + + currentImage.lineIndex++; + if (currentImage.lineIndex >= currentImage.height) { + this._lastLine = null; + this._imageIndex++; + currentImage = this._images[this._imageIndex]; + } else { + this._lastLine = unfilteredLine; + } + + if (currentImage) { + // read, using the byte width that may be from the new current image + this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this)); + } else { + this._lastLine = null; + this.complete(); + } +}; + +}).call(this,require("buffer").Buffer) +},{"./interlace":11,"./paeth-predictor":15,"buffer":28}],10:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +function dePalette(indata, outdata, width, height, palette) { + let pxPos = 0; + // use values from palette + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let color = palette[indata[pxPos]]; + + if (!color) { + throw new Error("index " + indata[pxPos] + " not in palette"); + } + + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = color[i]; + } + pxPos += 4; + } + } +} + +function replaceTransparentColor(indata, outdata, width, height, transColor) { + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let makeTrans = false; + + if (transColor.length === 1) { + if (transColor[0] === indata[pxPos]) { + makeTrans = true; + } + } else if ( + transColor[0] === indata[pxPos] && + transColor[1] === indata[pxPos + 1] && + transColor[2] === indata[pxPos + 2] + ) { + makeTrans = true; + } + if (makeTrans) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = 0; + } + } + pxPos += 4; + } + } +} + +function scaleDepth(indata, outdata, width, height, depth) { + let maxOutSample = 255; + let maxInSample = Math.pow(2, depth) - 1; + let pxPos = 0; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = Math.floor( + (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5 + ); + } + pxPos += 4; + } + } +} + +module.exports = function (indata, imageData) { + let depth = imageData.depth; + let width = imageData.width; + let height = imageData.height; + let colorType = imageData.colorType; + let transColor = imageData.transColor; + let palette = imageData.palette; + + let outdata = indata; // only different for 16 bits + + if (colorType === 3) { + // paletted + dePalette(indata, outdata, width, height, palette); + } else { + if (transColor) { + replaceTransparentColor(indata, outdata, width, height, transColor); + } + // if it needs scaling + if (depth !== 8) { + // if we need to change the buffer size + if (depth === 16) { + outdata = Buffer.alloc(width * height * 4); + } + scaleDepth(indata, outdata, width, height, depth); + } + } + return outdata; +}; + +}).call(this,require("buffer").Buffer) +},{"buffer":28}],11:[function(require,module,exports){ +"use strict"; + +// Adam 7 +// 0 1 2 3 4 5 6 7 +// 0 x 6 4 6 x 6 4 6 +// 1 7 7 7 7 7 7 7 7 +// 2 5 6 5 6 5 6 5 6 +// 3 7 7 7 7 7 7 7 7 +// 4 3 6 4 6 3 6 4 6 +// 5 7 7 7 7 7 7 7 7 +// 6 5 6 5 6 5 6 5 6 +// 7 7 7 7 7 7 7 7 7 + +let imagePasses = [ + { + // pass 1 - 1px + x: [0], + y: [0], + }, + { + // pass 2 - 1px + x: [4], + y: [0], + }, + { + // pass 3 - 2px + x: [0, 4], + y: [4], + }, + { + // pass 4 - 4px + x: [2, 6], + y: [0, 4], + }, + { + // pass 5 - 8px + x: [0, 2, 4, 6], + y: [2, 6], + }, + { + // pass 6 - 16px + x: [1, 3, 5, 7], + y: [0, 2, 4, 6], + }, + { + // pass 7 - 32px + x: [0, 1, 2, 3, 4, 5, 6, 7], + y: [1, 3, 5, 7], + }, +]; + +exports.getImagePasses = function (width, height) { + let images = []; + let xLeftOver = width % 8; + let yLeftOver = height % 8; + let xRepeats = (width - xLeftOver) / 8; + let yRepeats = (height - yLeftOver) / 8; + for (let i = 0; i < imagePasses.length; i++) { + let pass = imagePasses[i]; + let passWidth = xRepeats * pass.x.length; + let passHeight = yRepeats * pass.y.length; + for (let j = 0; j < pass.x.length; j++) { + if (pass.x[j] < xLeftOver) { + passWidth++; + } else { + break; + } + } + for (let j = 0; j < pass.y.length; j++) { + if (pass.y[j] < yLeftOver) { + passHeight++; + } else { + break; + } + } + if (passWidth > 0 && passHeight > 0) { + images.push({ width: passWidth, height: passHeight, index: i }); + } + } + return images; +}; + +exports.getInterlaceIterator = function (width) { + return function (x, y, pass) { + let outerXLeftOver = x % imagePasses[pass].x.length; + let outerX = + ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 + + imagePasses[pass].x[outerXLeftOver]; + let outerYLeftOver = y % imagePasses[pass].y.length; + let outerY = + ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 + + imagePasses[pass].y[outerYLeftOver]; + return outerX * 4 + outerY * width * 4; + }; +}; + +},{}],12:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let constants = require("./constants"); +let Packer = require("./packer"); + +let PackerAsync = (module.exports = function (opt) { + Stream.call(this); + + let options = opt || {}; + + this._packer = new Packer(options); + this._deflate = this._packer.createDeflate(); + + this.readable = true; +}); +util.inherits(PackerAsync, Stream); + +PackerAsync.prototype.pack = function (data, width, height, gamma) { + // Signature + this.emit("data", Buffer.from(constants.PNG_SIGNATURE)); + this.emit("data", this._packer.packIHDR(width, height)); + + if (gamma) { + this.emit("data", this._packer.packGAMA(gamma)); + } + + let filteredData = this._packer.filterData(data, width, height); + + // compress it + this._deflate.on("error", this.emit.bind(this, "error")); + + this._deflate.on( + "data", + function (compressedData) { + this.emit("data", this._packer.packIDAT(compressedData)); + }.bind(this) + ); + + this._deflate.on( + "end", + function () { + this.emit("data", this._packer.packIEND()); + this.emit("end"); + }.bind(this) + ); + + this._deflate.end(filteredData); +}; + +}).call(this,require("buffer").Buffer) +},{"./constants":4,"./packer":14,"buffer":28,"stream":63,"util":67}],13:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let constants = require("./constants"); +let Packer = require("./packer"); + +module.exports = function (metaData, opt) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let options = opt || {}; + + let packer = new Packer(options); + + let chunks = []; + + // Signature + chunks.push(Buffer.from(constants.PNG_SIGNATURE)); + + // Header + chunks.push(packer.packIHDR(metaData.width, metaData.height)); + + if (metaData.gamma) { + chunks.push(packer.packGAMA(metaData.gamma)); + } + + let filteredData = packer.filterData( + metaData.data, + metaData.width, + metaData.height + ); + + // compress it + let compressedData = zlib.deflateSync( + filteredData, + packer.getDeflateOptions() + ); + filteredData = null; + + if (!compressedData || !compressedData.length) { + throw new Error("bad png - invalid compressed data response"); + } + chunks.push(packer.packIDAT(compressedData)); + + // End + chunks.push(packer.packIEND()); + + return Buffer.concat(chunks); +}; + +}).call(this,require("buffer").Buffer) +},{"./constants":4,"./packer":14,"buffer":28,"zlib":27}],14:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let constants = require("./constants"); +let CrcStream = require("./crc"); +let bitPacker = require("./bitpacker"); +let filter = require("./filter-pack"); +let zlib = require("zlib"); + +let Packer = (module.exports = function (options) { + this._options = options; + + options.deflateChunkSize = options.deflateChunkSize || 32 * 1024; + options.deflateLevel = + options.deflateLevel != null ? options.deflateLevel : 9; + options.deflateStrategy = + options.deflateStrategy != null ? options.deflateStrategy : 3; + options.inputHasAlpha = + options.inputHasAlpha != null ? options.inputHasAlpha : true; + options.deflateFactory = options.deflateFactory || zlib.createDeflate; + options.bitDepth = options.bitDepth || 8; + // This is outputColorType + options.colorType = + typeof options.colorType === "number" + ? options.colorType + : constants.COLORTYPE_COLOR_ALPHA; + options.inputColorType = + typeof options.inputColorType === "number" + ? options.inputColorType + : constants.COLORTYPE_COLOR_ALPHA; + + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.colorType) === -1 + ) { + throw new Error( + "option color type:" + options.colorType + " is not supported at present" + ); + } + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.inputColorType) === -1 + ) { + throw new Error( + "option input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + if (options.bitDepth !== 8 && options.bitDepth !== 16) { + throw new Error( + "option bit depth:" + options.bitDepth + " is not supported at present" + ); + } +}); + +Packer.prototype.getDeflateOptions = function () { + return { + chunkSize: this._options.deflateChunkSize, + level: this._options.deflateLevel, + strategy: this._options.deflateStrategy, + }; +}; + +Packer.prototype.createDeflate = function () { + return this._options.deflateFactory(this.getDeflateOptions()); +}; + +Packer.prototype.filterData = function (data, width, height) { + // convert to correct format for filtering (e.g. right bpp and bit depth) + let packedData = bitPacker(data, width, height, this._options); + + // filter pixel data + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType]; + let filteredData = filter(packedData, width, height, this._options, bpp); + return filteredData; +}; + +Packer.prototype._packChunk = function (type, data) { + let len = data ? data.length : 0; + let buf = Buffer.alloc(len + 12); + + buf.writeUInt32BE(len, 0); + buf.writeUInt32BE(type, 4); + + if (data) { + data.copy(buf, 8); + } + + buf.writeInt32BE( + CrcStream.crc32(buf.slice(4, buf.length - 4)), + buf.length - 4 + ); + return buf; +}; + +Packer.prototype.packGAMA = function (gamma) { + let buf = Buffer.alloc(4); + buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0); + return this._packChunk(constants.TYPE_gAMA, buf); +}; + +Packer.prototype.packIHDR = function (width, height) { + let buf = Buffer.alloc(13); + buf.writeUInt32BE(width, 0); + buf.writeUInt32BE(height, 4); + buf[8] = this._options.bitDepth; // Bit depth + buf[9] = this._options.colorType; // colorType + buf[10] = 0; // compression + buf[11] = 0; // filter + buf[12] = 0; // interlace + + return this._packChunk(constants.TYPE_IHDR, buf); +}; + +Packer.prototype.packIDAT = function (data) { + return this._packChunk(constants.TYPE_IDAT, data); +}; + +Packer.prototype.packIEND = function () { + return this._packChunk(constants.TYPE_IEND, null); +}; + +}).call(this,require("buffer").Buffer) +},{"./bitpacker":2,"./constants":4,"./crc":5,"./filter-pack":6,"buffer":28,"zlib":27}],15:[function(require,module,exports){ +"use strict"; + +module.exports = function paethPredictor(left, above, upLeft) { + let paeth = left + above - upLeft; + let pLeft = Math.abs(paeth - left); + let pAbove = Math.abs(paeth - above); + let pUpLeft = Math.abs(paeth - upLeft); + + if (pLeft <= pAbove && pLeft <= pUpLeft) { + return left; + } + if (pAbove <= pUpLeft) { + return above; + } + return upLeft; +}; + +},{}],16:[function(require,module,exports){ +"use strict"; + +let util = require("util"); +let zlib = require("zlib"); +let ChunkStream = require("./chunkstream"); +let FilterAsync = require("./filter-parse-async"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +let ParserAsync = (module.exports = function (options) { + ChunkStream.call(this); + + this._parser = new Parser(options, { + read: this.read.bind(this), + error: this._handleError.bind(this), + metadata: this._handleMetaData.bind(this), + gamma: this.emit.bind(this, "gamma"), + palette: this._handlePalette.bind(this), + transColor: this._handleTransColor.bind(this), + finished: this._finished.bind(this), + inflateData: this._inflateData.bind(this), + simpleTransparency: this._simpleTransparency.bind(this), + headersFinished: this._headersFinished.bind(this), + }); + this._options = options; + this.writable = true; + + this._parser.start(); +}); +util.inherits(ParserAsync, ChunkStream); + +ParserAsync.prototype._handleError = function (err) { + this.emit("error", err); + + this.writable = false; + + this.destroy(); + + if (this._inflate && this._inflate.destroy) { + this._inflate.destroy(); + } + + if (this._filter) { + this._filter.destroy(); + // For backward compatibility with Node 7 and below. + // Suppress errors due to _inflate calling write() even after + // it's destroy()'ed. + this._filter.on("error", function () {}); + } + + this.errord = true; +}; + +ParserAsync.prototype._inflateData = function (data) { + if (!this._inflate) { + if (this._bitmapInfo.interlace) { + this._inflate = zlib.createInflate(); + + this._inflate.on("error", this.emit.bind(this, "error")); + this._filter.on("complete", this._complete.bind(this)); + + this._inflate.pipe(this._filter); + } else { + let rowSize = + ((this._bitmapInfo.width * + this._bitmapInfo.bpp * + this._bitmapInfo.depth + + 7) >> + 3) + + 1; + let imageSize = rowSize * this._bitmapInfo.height; + let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); + + this._inflate = zlib.createInflate({ chunkSize: chunkSize }); + let leftToInflate = imageSize; + + let emitError = this.emit.bind(this, "error"); + this._inflate.on("error", function (err) { + if (!leftToInflate) { + return; + } + + emitError(err); + }); + this._filter.on("complete", this._complete.bind(this)); + + let filterWrite = this._filter.write.bind(this._filter); + this._inflate.on("data", function (chunk) { + if (!leftToInflate) { + return; + } + + if (chunk.length > leftToInflate) { + chunk = chunk.slice(0, leftToInflate); + } + + leftToInflate -= chunk.length; + + filterWrite(chunk); + }); + + this._inflate.on("end", this._filter.end.bind(this._filter)); + } + } + this._inflate.write(data); +}; + +ParserAsync.prototype._handleMetaData = function (metaData) { + this._metaData = metaData; + this._bitmapInfo = Object.create(metaData); + + this._filter = new FilterAsync(this._bitmapInfo); +}; + +ParserAsync.prototype._handleTransColor = function (transColor) { + this._bitmapInfo.transColor = transColor; +}; + +ParserAsync.prototype._handlePalette = function (palette) { + this._bitmapInfo.palette = palette; +}; + +ParserAsync.prototype._simpleTransparency = function () { + this._metaData.alpha = true; +}; + +ParserAsync.prototype._headersFinished = function () { + // Up until this point, we don't know if we have a tRNS chunk (alpha) + // so we can't emit metadata any earlier + this.emit("metadata", this._metaData); +}; + +ParserAsync.prototype._finished = function () { + if (this.errord) { + return; + } + + if (!this._inflate) { + this.emit("error", "No Inflate block"); + } else { + // no more data to inflate + this._inflate.end(); + } +}; + +ParserAsync.prototype._complete = function (filteredData) { + if (this.errord) { + return; + } + + let normalisedBitmapData; + + try { + let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); + + normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo); + bitmapData = null; + } catch (ex) { + this._handleError(ex); + return; + } + + this.emit("parsed", normalisedBitmapData); +}; + +},{"./bitmapper":1,"./chunkstream":3,"./filter-parse-async":7,"./format-normaliser":10,"./parser":18,"util":67,"zlib":27}],17:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +let inflateSync = require("./sync-inflate"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let SyncReader = require("./sync-reader"); +let FilterSync = require("./filter-parse-sync"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +module.exports = function (buffer, options) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let err; + function handleError(_err_) { + err = _err_; + } + + let metaData; + function handleMetaData(_metaData_) { + metaData = _metaData_; + } + + function handleTransColor(transColor) { + metaData.transColor = transColor; + } + + function handlePalette(palette) { + metaData.palette = palette; + } + + function handleSimpleTransparency() { + metaData.alpha = true; + } + + let gamma; + function handleGamma(_gamma_) { + gamma = _gamma_; + } + + let inflateDataList = []; + function handleInflateData(inflatedData) { + inflateDataList.push(inflatedData); + } + + let reader = new SyncReader(buffer); + + let parser = new Parser(options, { + read: reader.read.bind(reader), + error: handleError, + metadata: handleMetaData, + gamma: handleGamma, + palette: handlePalette, + transColor: handleTransColor, + inflateData: handleInflateData, + simpleTransparency: handleSimpleTransparency, + }); + + parser.start(); + reader.process(); + + if (err) { + throw err; + } + + //join together the inflate datas + let inflateData = Buffer.concat(inflateDataList); + inflateDataList.length = 0; + + let inflatedData; + if (metaData.interlace) { + inflatedData = zlib.inflateSync(inflateData); + } else { + let rowSize = + ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1; + let imageSize = rowSize * metaData.height; + inflatedData = inflateSync(inflateData, { + chunkSize: imageSize, + maxLength: imageSize, + }); + } + inflateData = null; + + if (!inflatedData || !inflatedData.length) { + throw new Error("bad png - invalid inflate data response"); + } + + let unfilteredData = FilterSync.process(inflatedData, metaData); + inflateData = null; + + let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); + unfilteredData = null; + + let normalisedBitmapData = formatNormaliser(bitmapData, metaData); + + metaData.data = normalisedBitmapData; + metaData.gamma = gamma || 0; + + return metaData; +}; + +}).call(this,require("buffer").Buffer) +},{"./bitmapper":1,"./filter-parse-sync":8,"./format-normaliser":10,"./parser":18,"./sync-inflate":21,"./sync-reader":22,"buffer":28,"zlib":27}],18:[function(require,module,exports){ +(function (Buffer){ +"use strict"; + +let constants = require("./constants"); +let CrcCalculator = require("./crc"); + +let Parser = (module.exports = function (options, dependencies) { + this._options = options; + options.checkCRC = options.checkCRC !== false; + + this._hasIHDR = false; + this._hasIEND = false; + this._emittedHeadersFinished = false; + + // input flags/metadata + this._palette = []; + this._colorType = 0; + + this._chunks = {}; + this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this); + this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this); + this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this); + this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this); + this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this); + this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this); + + this.read = dependencies.read; + this.error = dependencies.error; + this.metadata = dependencies.metadata; + this.gamma = dependencies.gamma; + this.transColor = dependencies.transColor; + this.palette = dependencies.palette; + this.parsed = dependencies.parsed; + this.inflateData = dependencies.inflateData; + this.finished = dependencies.finished; + this.simpleTransparency = dependencies.simpleTransparency; + this.headersFinished = dependencies.headersFinished || function () {}; +}); + +Parser.prototype.start = function () { + this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this)); +}; + +Parser.prototype._parseSignature = function (data) { + let signature = constants.PNG_SIGNATURE; + + for (let i = 0; i < signature.length; i++) { + if (data[i] !== signature[i]) { + this.error(new Error("Invalid file signature")); + return; + } + } + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._parseChunkBegin = function (data) { + // chunk content length + let length = data.readUInt32BE(0); + + // chunk type + let type = data.readUInt32BE(4); + let name = ""; + for (let i = 4; i < 8; i++) { + name += String.fromCharCode(data[i]); + } + + //console.log('chunk ', name, length); + + // chunk flags + let ancillary = Boolean(data[4] & 0x20); // or critical + // priv = Boolean(data[5] & 0x20), // or public + // safeToCopy = Boolean(data[7] & 0x20); // or unsafe + + if (!this._hasIHDR && type !== constants.TYPE_IHDR) { + this.error(new Error("Expected IHDR on beggining")); + return; + } + + this._crc = new CrcCalculator(); + this._crc.write(Buffer.from(name)); + + if (this._chunks[type]) { + return this._chunks[type](length); + } + + if (!ancillary) { + this.error(new Error("Unsupported critical chunk type " + name)); + return; + } + + this.read(length + 4, this._skipChunk.bind(this)); +}; + +Parser.prototype._skipChunk = function (/*data*/) { + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._handleChunkEnd = function () { + this.read(4, this._parseChunkEnd.bind(this)); +}; + +Parser.prototype._parseChunkEnd = function (data) { + let fileCrc = data.readInt32BE(0); + let calcCrc = this._crc.crc32(); + + // check CRC + if (this._options.checkCRC && calcCrc !== fileCrc) { + this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc)); + return; + } + + if (!this._hasIEND) { + this.read(8, this._parseChunkBegin.bind(this)); + } +}; + +Parser.prototype._handleIHDR = function (length) { + this.read(length, this._parseIHDR.bind(this)); +}; +Parser.prototype._parseIHDR = function (data) { + this._crc.write(data); + + let width = data.readUInt32BE(0); + let height = data.readUInt32BE(4); + let depth = data[8]; + let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha + let compr = data[10]; + let filter = data[11]; + let interlace = data[12]; + + // console.log(' width', width, 'height', height, + // 'depth', depth, 'colorType', colorType, + // 'compr', compr, 'filter', filter, 'interlace', interlace + // ); + + if ( + depth !== 8 && + depth !== 4 && + depth !== 2 && + depth !== 1 && + depth !== 16 + ) { + this.error(new Error("Unsupported bit depth " + depth)); + return; + } + if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) { + this.error(new Error("Unsupported color type")); + return; + } + if (compr !== 0) { + this.error(new Error("Unsupported compression method")); + return; + } + if (filter !== 0) { + this.error(new Error("Unsupported filter method")); + return; + } + if (interlace !== 0 && interlace !== 1) { + this.error(new Error("Unsupported interlace method")); + return; + } + + this._colorType = colorType; + + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; + + this._hasIHDR = true; + + this.metadata({ + width: width, + height: height, + depth: depth, + interlace: Boolean(interlace), + palette: Boolean(colorType & constants.COLORTYPE_PALETTE), + color: Boolean(colorType & constants.COLORTYPE_COLOR), + alpha: Boolean(colorType & constants.COLORTYPE_ALPHA), + bpp: bpp, + colorType: colorType, + }); + + this._handleChunkEnd(); +}; + +Parser.prototype._handlePLTE = function (length) { + this.read(length, this._parsePLTE.bind(this)); +}; +Parser.prototype._parsePLTE = function (data) { + this._crc.write(data); + + let entries = Math.floor(data.length / 3); + // console.log('Palette:', entries); + + for (let i = 0; i < entries; i++) { + this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]); + } + + this.palette(this._palette); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleTRNS = function (length) { + this.simpleTransparency(); + this.read(length, this._parseTRNS.bind(this)); +}; +Parser.prototype._parseTRNS = function (data) { + this._crc.write(data); + + // palette + if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) { + if (this._palette.length === 0) { + this.error(new Error("Transparency chunk must be after palette")); + return; + } + if (data.length > this._palette.length) { + this.error(new Error("More transparent colors than palette size")); + return; + } + for (let i = 0; i < data.length; i++) { + this._palette[i][3] = data[i]; + } + this.palette(this._palette); + } + + // for colorType 0 (grayscale) and 2 (rgb) + // there might be one gray/color defined as transparent + if (this._colorType === constants.COLORTYPE_GRAYSCALE) { + // grey, 2 bytes + this.transColor([data.readUInt16BE(0)]); + } + if (this._colorType === constants.COLORTYPE_COLOR) { + this.transColor([ + data.readUInt16BE(0), + data.readUInt16BE(2), + data.readUInt16BE(4), + ]); + } + + this._handleChunkEnd(); +}; + +Parser.prototype._handleGAMA = function (length) { + this.read(length, this._parseGAMA.bind(this)); +}; +Parser.prototype._parseGAMA = function (data) { + this._crc.write(data); + this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleIDAT = function (length) { + if (!this._emittedHeadersFinished) { + this._emittedHeadersFinished = true; + this.headersFinished(); + } + this.read(-length, this._parseIDAT.bind(this, length)); +}; +Parser.prototype._parseIDAT = function (length, data) { + this._crc.write(data); + + if ( + this._colorType === constants.COLORTYPE_PALETTE_COLOR && + this._palette.length === 0 + ) { + throw new Error("Expected palette not found"); + } + + this.inflateData(data); + let leftOverLength = length - data.length; + + if (leftOverLength > 0) { + this._handleIDAT(leftOverLength); + } else { + this._handleChunkEnd(); + } +}; + +Parser.prototype._handleIEND = function (length) { + this.read(length, this._parseIEND.bind(this)); +}; +Parser.prototype._parseIEND = function (data) { + this._crc.write(data); + + this._hasIEND = true; + this._handleChunkEnd(); + + if (this.finished) { + this.finished(); + } +}; + +}).call(this,require("buffer").Buffer) +},{"./constants":4,"./crc":5,"buffer":28}],19:[function(require,module,exports){ +"use strict"; + +let parse = require("./parser-sync"); +let pack = require("./packer-sync"); + +exports.read = function (buffer, options) { + return parse(buffer, options || {}); +}; + +exports.write = function (png, options) { + return pack(png, options); +}; + +},{"./packer-sync":13,"./parser-sync":17}],20:[function(require,module,exports){ +(function (process,Buffer){ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let Parser = require("./parser-async"); +let Packer = require("./packer-async"); +let PNGSync = require("./png-sync"); + +let PNG = (exports.PNG = function (options) { + Stream.call(this); + + options = options || {}; // eslint-disable-line no-param-reassign + + // coerce pixel dimensions to integers (also coerces undefined -> 0): + this.width = options.width | 0; + this.height = options.height | 0; + + this.data = + this.width > 0 && this.height > 0 + ? Buffer.alloc(4 * this.width * this.height) + : null; + + if (options.fill && this.data) { + this.data.fill(0); + } + + this.gamma = 0; + this.readable = this.writable = true; + + this._parser = new Parser(options); + + this._parser.on("error", this.emit.bind(this, "error")); + this._parser.on("close", this._handleClose.bind(this)); + this._parser.on("metadata", this._metadata.bind(this)); + this._parser.on("gamma", this._gamma.bind(this)); + this._parser.on( + "parsed", + function (data) { + this.data = data; + this.emit("parsed", data); + }.bind(this) + ); + + this._packer = new Packer(options); + this._packer.on("data", this.emit.bind(this, "data")); + this._packer.on("end", this.emit.bind(this, "end")); + this._parser.on("close", this._handleClose.bind(this)); + this._packer.on("error", this.emit.bind(this, "error")); +}); +util.inherits(PNG, Stream); + +PNG.sync = PNGSync; + +PNG.prototype.pack = function () { + if (!this.data || !this.data.length) { + this.emit("error", "No data provided"); + return this; + } + + process.nextTick( + function () { + this._packer.pack(this.data, this.width, this.height, this.gamma); + }.bind(this) + ); + + return this; +}; + +PNG.prototype.parse = function (data, callback) { + if (callback) { + let onParsed, onError; + + onParsed = function (parsedData) { + this.removeListener("error", onError); + + this.data = parsedData; + callback(null, this); + }.bind(this); + + onError = function (err) { + this.removeListener("parsed", onParsed); + + callback(err, null); + }.bind(this); + + this.once("parsed", onParsed); + this.once("error", onError); + } + + this.end(data); + return this; +}; + +PNG.prototype.write = function (data) { + this._parser.write(data); + return true; +}; + +PNG.prototype.end = function (data) { + this._parser.end(data); +}; + +PNG.prototype._metadata = function (metadata) { + this.width = metadata.width; + this.height = metadata.height; + + this.emit("metadata", metadata); +}; + +PNG.prototype._gamma = function (gamma) { + this.gamma = gamma; +}; + +PNG.prototype._handleClose = function () { + if (!this._parser.writable && !this._packer.readable) { + this.emit("close"); + } +}; + +PNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) { + // eslint-disable-line max-params + // coerce pixel dimensions to integers (also coerces undefined -> 0): + /* eslint-disable no-param-reassign */ + srcX |= 0; + srcY |= 0; + width |= 0; + height |= 0; + deltaX |= 0; + deltaY |= 0; + /* eslint-enable no-param-reassign */ + + if ( + srcX > src.width || + srcY > src.height || + srcX + width > src.width || + srcY + height > src.height + ) { + throw new Error("bitblt reading outside image"); + } + + if ( + deltaX > dst.width || + deltaY > dst.height || + deltaX + width > dst.width || + deltaY + height > dst.height + ) { + throw new Error("bitblt writing outside image"); + } + + for (let y = 0; y < height; y++) { + src.data.copy( + dst.data, + ((deltaY + y) * dst.width + deltaX) << 2, + ((srcY + y) * src.width + srcX) << 2, + ((srcY + y) * src.width + srcX + width) << 2 + ); + } +}; + +PNG.prototype.bitblt = function ( + dst, + srcX, + srcY, + width, + height, + deltaX, + deltaY +) { + // eslint-disable-line max-params + + PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); + return this; +}; + +PNG.adjustGamma = function (src) { + if (src.gamma) { + for (let y = 0; y < src.height; y++) { + for (let x = 0; x < src.width; x++) { + let idx = (src.width * y + x) << 2; + + for (let i = 0; i < 3; i++) { + let sample = src.data[idx + i] / 255; + sample = Math.pow(sample, 1 / 2.2 / src.gamma); + src.data[idx + i] = Math.round(sample * 255); + } + } + } + src.gamma = 0; + } +}; + +PNG.prototype.adjustGamma = function () { + PNG.adjustGamma(this); +}; + +}).call(this,require('_process'),require("buffer").Buffer) +},{"./packer-async":12,"./parser-async":16,"./png-sync":19,"_process":47,"buffer":28,"stream":63,"util":67}],21:[function(require,module,exports){ +(function (process,Buffer){ +"use strict"; + +let assert = require("assert").ok; +let zlib = require("zlib"); +let util = require("util"); + +let kMaxLength = require("buffer").kMaxLength; + +function Inflate(opts) { + if (!(this instanceof Inflate)) { + return new Inflate(opts); + } + + if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { + opts.chunkSize = zlib.Z_MIN_CHUNK; + } + + zlib.Inflate.call(this, opts); + + // Node 8 --> 9 compatibility check + this._offset = this._offset === undefined ? this._outOffset : this._offset; + this._buffer = this._buffer || this._outBuffer; + + if (opts && opts.maxLength != null) { + this._maxLength = opts.maxLength; + } +} + +function createInflate(opts) { + return new Inflate(opts); +} + +function _close(engine, callback) { + if (callback) { + process.nextTick(callback); + } + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) { + return; + } + + engine._handle.close(); + engine._handle = null; +} + +Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) { + if (typeof asyncCb === "function") { + return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); + } + + let self = this; + + let availInBefore = chunk && chunk.length; + let availOutBefore = this._chunkSize - this._offset; + let leftToInflate = this._maxLength; + let inOff = 0; + + let buffers = []; + let nread = 0; + + let error; + this.on("error", function (err) { + error = err; + }); + + function handleChunk(availInAfter, availOutAfter) { + if (self._hadError) { + return; + } + + let have = availOutBefore - availOutAfter; + assert(have >= 0, "have should not go down"); + + if (have > 0) { + let out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + + if (out.length > leftToInflate) { + out = out.slice(0, leftToInflate); + } + + buffers.push(out); + nread += out.length; + leftToInflate -= out.length; + + if (leftToInflate === 0) { + return false; + } + } + + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + return true; + } + + return false; + } + + assert(this._handle, "zlib binding closed"); + let res; + do { + res = this._handle.writeSync( + flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore + ); // out_len + // Node 8 --> 9 compatibility check + res = res || this._writeState; + } while (!this._hadError && handleChunk(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError( + "Cannot create final Buffer. It would be larger than 0x" + + kMaxLength.toString(16) + + " bytes" + ); + } + + let buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; +}; + +util.inherits(Inflate, zlib.Inflate); + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === "string") { + buffer = Buffer.from(buffer); + } + if (!(buffer instanceof Buffer)) { + throw new TypeError("Not a string or buffer"); + } + + let flushFlag = engine._finishFlushFlag; + if (flushFlag == null) { + flushFlag = zlib.Z_FINISH; + } + + return engine._processChunk(buffer, flushFlag); +} + +function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +} + +module.exports = exports = inflateSync; +exports.Inflate = Inflate; +exports.createInflate = createInflate; +exports.inflateSync = inflateSync; + +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":47,"assert":23,"buffer":28,"util":67,"zlib":27}],22:[function(require,module,exports){ +"use strict"; + +let SyncReader = (module.exports = function (buffer) { + this._buffer = buffer; + this._reads = []; +}); + +SyncReader.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); +}; + +SyncReader.prototype.process = function () { + // as long as there is any data and read requests + while (this._reads.length > 0 && this._buffer.length) { + let read = this._reads[0]; + + if ( + this._buffer.length && + (this._buffer.length >= read.length || read.allowLess) + ) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + let buf = this._buffer; + + this._buffer = buf.slice(read.length); + + read.func.call(this, buf.slice(0, read.length)); + } else { + break; + } + } + + if (this._reads.length > 0) { + return new Error("There are some read requests waitng on finished stream"); + } + + if (this._buffer.length > 0) { + return new Error("unrecognised content at end of stream"); + } +}; + +},{}],23:[function(require,module,exports){ +(function (global){ +'use strict'; + +// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js +// original notice: + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; +} +function isBuffer(b) { + if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { + return global.Buffer.isBuffer(b); + } + return !!(b != null && b._isBuffer); +} + +// based on node assert, original notice: + +// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 +// +// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! +// +// Originally from narwhal.js (http://narwhaljs.org) +// Copyright (c) 2009 Thomas Robinson <280north.com> +// +// 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +var util = require('util/'); +var hasOwn = Object.prototype.hasOwnProperty; +var pSlice = Array.prototype.slice; +var functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; +}()); +function pToString (obj) { + return Object.prototype.toString.call(obj); +} +function isView(arrbuf) { + if (isBuffer(arrbuf)) { + return false; + } + if (typeof global.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; +} +// 1. The assert module provides functions that throw +// AssertionError's when particular conditions are not met. The +// assert module must conform to the following interface. + +var assert = module.exports = ok; + +// 2. The AssertionError is defined in assert. +// new assert.AssertionError({ message: message, +// actual: actual, +// expected: expected }) + +var regex = /\s*function\s+([^\(\s]*)\s*/; +// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js +function getName(func) { + if (!util.isFunction(func)) { + return; + } + if (functionsHaveNames) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; +} +assert.AssertionError = function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} +function inspect(something) { + if (functionsHaveNames || !util.isFunction(something)) { + return util.inspect(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; +} +function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); +} + +// At present only the three keys mentioned above are used and +// understood by the spec. Implementations or sub modules can pass +// other keys to the AssertionError's constructor - they will be +// ignored. + +// 3. All of the following functions must throw an AssertionError +// when a corresponding condition is not met, with a message that +// may be undefined if not provided. All assertion methods provide +// both the actual and expected values to the assertion error for +// display purposes. + +function fail(actual, expected, message, operator, stackStartFunction) { + throw new assert.AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); +} + +// EXTENSION! allows for well behaved errors defined elsewhere. +assert.fail = fail; + +// 4. Pure assertion tests whether a value is truthy, as determined +// by !!guard. +// assert.ok(guard, message_opt); +// This statement is equivalent to assert.equal(true, !!guard, +// message_opt);. To test strictly for the value true, use +// assert.strictEqual(true, guard, message_opt);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = ok; + +// 5. The equality assertion tests shallow, coercive equality with +// ==. +// assert.equal(actual, expected, message_opt); + +assert.equal = function equal(actual, expected, message) { + if (actual != expected) fail(actual, expected, message, '==', assert.equal); +}; + +// 6. The non-equality assertion tests for whether two objects are not equal +// with != assert.notEqual(actual, expected, message_opt); + +assert.notEqual = function notEqual(actual, expected, message) { + if (actual == expected) { + fail(actual, expected, message, '!=', assert.notEqual); + } +}; + +// 7. The equivalence assertion tests a deep equality relation. +// assert.deepEqual(actual, expected, message_opt); + +assert.deepEqual = function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'deepEqual', assert.deepEqual); + } +}; + +assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); + } +}; + +function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer(actual) && isBuffer(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer(actual) !== isBuffer(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } +} + +function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (util.isPrimitive(a) || util.isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys(a); + var kb = objectKeys(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; +} + +// 8. The non-equivalence assertion tests for any deep inequality. +// assert.notDeepEqual(actual, expected, message_opt); + +assert.notDeepEqual = function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); + } +}; + +assert.notDeepStrictEqual = notDeepStrictEqual; +function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } +} + + +// 9. The strict equality assertion tests strict equality, as determined by ===. +// assert.strictEqual(actual, expected, message_opt); + +assert.strictEqual = function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail(actual, expected, message, '===', assert.strictEqual); + } +}; + +// 10. The strict non-equality assertion tests for strict inequality, as +// determined by !==. assert.notStrictEqual(actual, expected, message_opt); + +assert.notStrictEqual = function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail(actual, expected, message, '!==', assert.notStrictEqual); + } +}; + +function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; +} + +function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && util.isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 11. Expected to throw an error: +// assert.throws(block, Error_opt, message_opt); + +assert.throws = function(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); +}; + +// EXTENSION! This is annoying to write outside this module. +assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); +}; + +assert.ifError = function(err) { if (err) throw err; }; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"util/":67}],24:[function(require,module,exports){ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function placeHoldersCount (b64) { + var len = b64.length + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 +} + +function byteLength (b64) { + // base64 is 4/3 + up to two characters of the original data + return (b64.length * 3 / 4) - placeHoldersCount(b64) +} + +function toByteArray (b64) { + var i, l, tmp, placeHolders, arr + var len = b64.length + placeHolders = placeHoldersCount(b64) + + arr = new Arr((len * 3 / 4) - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0; i < l; i += 4) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],25:[function(require,module,exports){ + +},{}],26:[function(require,module,exports){ +(function (process,Buffer){ +'use strict'; +/* eslint camelcase: "off" */ + +var assert = require('assert'); + +var Zstream = require('pako/lib/zlib/zstream'); +var zlib_deflate = require('pako/lib/zlib/deflate.js'); +var zlib_inflate = require('pako/lib/zlib/inflate.js'); +var constants = require('pako/lib/zlib/constants'); + +for (var key in constants) { + exports[key] = constants[key]; +} + +// zlib modes +exports.NONE = 0; +exports.DEFLATE = 1; +exports.INFLATE = 2; +exports.GZIP = 3; +exports.GUNZIP = 4; +exports.DEFLATERAW = 5; +exports.INFLATERAW = 6; +exports.UNZIP = 7; + +var GZIP_HEADER_ID1 = 0x1f; +var GZIP_HEADER_ID2 = 0x8b; + +/** + * Emulate Node's zlib C++ layer for use by the JS layer in index.js + */ +function Zlib(mode) { + if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) { + throw new TypeError('Bad argument'); + } + + this.dictionary = null; + this.err = 0; + this.flush = 0; + this.init_done = false; + this.level = 0; + this.memLevel = 0; + this.mode = mode; + this.strategy = 0; + this.windowBits = 0; + this.write_in_progress = false; + this.pending_close = false; + this.gzip_id_bytes_read = 0; +} + +Zlib.prototype.close = function () { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + + this.pending_close = false; + + assert(this.init_done, 'close before init'); + assert(this.mode <= exports.UNZIP); + + if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) { + zlib_deflate.deflateEnd(this.strm); + } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) { + zlib_inflate.inflateEnd(this.strm); + } + + this.mode = exports.NONE; + + this.dictionary = null; +}; + +Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(true, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) { + return this._write(false, flush, input, in_off, in_len, out, out_off, out_len); +}; + +Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) { + assert.equal(arguments.length, 8); + + assert(this.init_done, 'write before init'); + assert(this.mode !== exports.NONE, 'already finalized'); + assert.equal(false, this.write_in_progress, 'write already in progress'); + assert.equal(false, this.pending_close, 'close is pending'); + + this.write_in_progress = true; + + assert.equal(false, flush === undefined, 'must provide flush value'); + + this.write_in_progress = true; + + if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) { + throw new Error('Invalid flush value'); + } + + if (input == null) { + input = Buffer.alloc(0); + in_len = 0; + in_off = 0; + } + + this.strm.avail_in = in_len; + this.strm.input = input; + this.strm.next_in = in_off; + this.strm.avail_out = out_len; + this.strm.output = out; + this.strm.next_out = out_off; + this.flush = flush; + + if (!async) { + // sync version + this._process(); + + if (this._checkError()) { + return this._afterSync(); + } + return; + } + + // async version + var self = this; + process.nextTick(function () { + self._process(); + self._after(); + }); + + return this; +}; + +Zlib.prototype._afterSync = function () { + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + return [avail_in, avail_out]; +}; + +Zlib.prototype._process = function () { + var next_expected_header_byte = null; + + // If the avail_out is left at 0, then it means that it ran out + // of room. If there was avail_out left over, then it means + // that all of the input was consumed. + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflate(this.strm, this.flush); + break; + case exports.UNZIP: + if (this.strm.avail_in > 0) { + next_expected_header_byte = this.strm.next_in; + } + + switch (this.gzip_id_bytes_read) { + case 0: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) { + this.gzip_id_bytes_read = 1; + next_expected_header_byte++; + + if (this.strm.avail_in === 1) { + // The only available byte was already read. + break; + } + } else { + this.mode = exports.INFLATE; + break; + } + + // fallthrough + case 1: + if (next_expected_header_byte === null) { + break; + } + + if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) { + this.gzip_id_bytes_read = 2; + this.mode = exports.GUNZIP; + } else { + // There is no actual difference between INFLATE and INFLATERAW + // (after initialization). + this.mode = exports.INFLATE; + } + + break; + default: + throw new Error('invalid number of gzip magic number bytes read'); + } + + // fallthrough + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + this.err = zlib_inflate.inflate(this.strm, this.flush + + // If data was encoded with dictionary + );if (this.err === exports.Z_NEED_DICT && this.dictionary) { + // Load it + this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary); + if (this.err === exports.Z_OK) { + // And try to decode again + this.err = zlib_inflate.inflate(this.strm, this.flush); + } else if (this.err === exports.Z_DATA_ERROR) { + // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR. + // Make it possible for After() to tell a bad dictionary from bad + // input. + this.err = exports.Z_NEED_DICT; + } + } + while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) { + // Bytes remain in input buffer. Perhaps this is another compressed + // member in the same archive, or just trailing garbage. + // Trailing zero bytes are okay, though, since they are frequently + // used for padding. + + this.reset(); + this.err = zlib_inflate.inflate(this.strm, this.flush); + } + break; + default: + throw new Error('Unknown mode ' + this.mode); + } +}; + +Zlib.prototype._checkError = function () { + // Acceptable error states depend on the type of zlib stream. + switch (this.err) { + case exports.Z_OK: + case exports.Z_BUF_ERROR: + if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) { + this._error('unexpected end of file'); + return false; + } + break; + case exports.Z_STREAM_END: + // normal statuses, not fatal + break; + case exports.Z_NEED_DICT: + if (this.dictionary == null) { + this._error('Missing dictionary'); + } else { + this._error('Bad dictionary'); + } + return false; + default: + // something else. + this._error('Zlib error'); + return false; + } + + return true; +}; + +Zlib.prototype._after = function () { + if (!this._checkError()) { + return; + } + + var avail_out = this.strm.avail_out; + var avail_in = this.strm.avail_in; + + this.write_in_progress = false; + + // call the write() cb + this.callback(avail_in, avail_out); + + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype._error = function (message) { + if (this.strm.msg) { + message = this.strm.msg; + } + this.onerror(message, this.err + + // no hope of rescue. + );this.write_in_progress = false; + if (this.pending_close) { + this.close(); + } +}; + +Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) { + assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])'); + + assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits'); + assert(level >= -1 && level <= 9, 'invalid compression level'); + + assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel'); + + assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy'); + + this._init(level, windowBits, memLevel, strategy, dictionary); + this._setDictionary(); +}; + +Zlib.prototype.params = function () { + throw new Error('deflateParams Not supported'); +}; + +Zlib.prototype.reset = function () { + this._reset(); + this._setDictionary(); +}; + +Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) { + this.level = level; + this.windowBits = windowBits; + this.memLevel = memLevel; + this.strategy = strategy; + + this.flush = exports.Z_NO_FLUSH; + + this.err = exports.Z_OK; + + if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) { + this.windowBits += 16; + } + + if (this.mode === exports.UNZIP) { + this.windowBits += 32; + } + + if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) { + this.windowBits = -1 * this.windowBits; + } + + this.strm = new Zstream(); + + switch (this.mode) { + case exports.DEFLATE: + case exports.GZIP: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy); + break; + case exports.INFLATE: + case exports.GUNZIP: + case exports.INFLATERAW: + case exports.UNZIP: + this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (this.err !== exports.Z_OK) { + this._error('Init error'); + } + + this.dictionary = dictionary; + + this.write_in_progress = false; + this.init_done = true; +}; + +Zlib.prototype._setDictionary = function () { + if (this.dictionary == null) { + return; + } + + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to set dictionary'); + } +}; + +Zlib.prototype._reset = function () { + this.err = exports.Z_OK; + + switch (this.mode) { + case exports.DEFLATE: + case exports.DEFLATERAW: + case exports.GZIP: + this.err = zlib_deflate.deflateReset(this.strm); + break; + case exports.INFLATE: + case exports.INFLATERAW: + case exports.GUNZIP: + this.err = zlib_inflate.inflateReset(this.strm); + break; + default: + break; + } + + if (this.err !== exports.Z_OK) { + this._error('Failed to reset stream'); + } +}; + +exports.Zlib = Zlib; +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":47,"assert":23,"buffer":28,"pako/lib/zlib/constants":37,"pako/lib/zlib/deflate.js":39,"pako/lib/zlib/inflate.js":41,"pako/lib/zlib/zstream":45}],27:[function(require,module,exports){ +(function (process){ +'use strict'; + +var Buffer = require('buffer').Buffer; +var Transform = require('stream').Transform; +var binding = require('./binding'); +var util = require('util'); +var assert = require('assert').ok; +var kMaxLength = require('buffer').kMaxLength; +var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes'; + +// zlib doesn't provide these, so kludge them in following the same +// const naming scheme zlib uses. +binding.Z_MIN_WINDOWBITS = 8; +binding.Z_MAX_WINDOWBITS = 15; +binding.Z_DEFAULT_WINDOWBITS = 15; + +// fewer than 64 bytes per chunk is stupid. +// technically it could work with as few as 8, but even 64 bytes +// is absurdly low. Usually a MB or more is best. +binding.Z_MIN_CHUNK = 64; +binding.Z_MAX_CHUNK = Infinity; +binding.Z_DEFAULT_CHUNK = 16 * 1024; + +binding.Z_MIN_MEMLEVEL = 1; +binding.Z_MAX_MEMLEVEL = 9; +binding.Z_DEFAULT_MEMLEVEL = 8; + +binding.Z_MIN_LEVEL = -1; +binding.Z_MAX_LEVEL = 9; +binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; + +// expose all the zlib constants +var bkeys = Object.keys(binding); +for (var bk = 0; bk < bkeys.length; bk++) { + var bkey = bkeys[bk]; + if (bkey.match(/^Z/)) { + Object.defineProperty(exports, bkey, { + enumerable: true, value: binding[bkey], writable: false + }); + } +} + +// translation table for return codes. +var codes = { + Z_OK: binding.Z_OK, + Z_STREAM_END: binding.Z_STREAM_END, + Z_NEED_DICT: binding.Z_NEED_DICT, + Z_ERRNO: binding.Z_ERRNO, + Z_STREAM_ERROR: binding.Z_STREAM_ERROR, + Z_DATA_ERROR: binding.Z_DATA_ERROR, + Z_MEM_ERROR: binding.Z_MEM_ERROR, + Z_BUF_ERROR: binding.Z_BUF_ERROR, + Z_VERSION_ERROR: binding.Z_VERSION_ERROR +}; + +var ckeys = Object.keys(codes); +for (var ck = 0; ck < ckeys.length; ck++) { + var ckey = ckeys[ck]; + codes[codes[ckey]] = ckey; +} + +Object.defineProperty(exports, 'codes', { + enumerable: true, value: Object.freeze(codes), writable: false +}); + +exports.Deflate = Deflate; +exports.Inflate = Inflate; +exports.Gzip = Gzip; +exports.Gunzip = Gunzip; +exports.DeflateRaw = DeflateRaw; +exports.InflateRaw = InflateRaw; +exports.Unzip = Unzip; + +exports.createDeflate = function (o) { + return new Deflate(o); +}; + +exports.createInflate = function (o) { + return new Inflate(o); +}; + +exports.createDeflateRaw = function (o) { + return new DeflateRaw(o); +}; + +exports.createInflateRaw = function (o) { + return new InflateRaw(o); +}; + +exports.createGzip = function (o) { + return new Gzip(o); +}; + +exports.createGunzip = function (o) { + return new Gunzip(o); +}; + +exports.createUnzip = function (o) { + return new Unzip(o); +}; + +// Convenience methods. +// compress/decompress a string or buffer in one step. +exports.deflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer, callback); +}; + +exports.deflateSync = function (buffer, opts) { + return zlibBufferSync(new Deflate(opts), buffer); +}; + +exports.gzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer, callback); +}; + +exports.gzipSync = function (buffer, opts) { + return zlibBufferSync(new Gzip(opts), buffer); +}; + +exports.deflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer, callback); +}; + +exports.deflateRawSync = function (buffer, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer); +}; + +exports.unzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer, callback); +}; + +exports.unzipSync = function (buffer, opts) { + return zlibBufferSync(new Unzip(opts), buffer); +}; + +exports.inflate = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer, callback); +}; + +exports.inflateSync = function (buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +}; + +exports.gunzip = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer, callback); +}; + +exports.gunzipSync = function (buffer, opts) { + return zlibBufferSync(new Gunzip(opts), buffer); +}; + +exports.inflateRaw = function (buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer, callback); +}; + +exports.inflateRawSync = function (buffer, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer); +}; + +function zlibBuffer(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once('readable', flow); + } + + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); + } + + function onEnd() { + var buf; + var err = null; + + if (nread >= kMaxLength) { + err = new RangeError(kRangeErrorMessage); + } else { + buf = Buffer.concat(buffers, nread); + } + + buffers = []; + engine.close(); + callback(err, buf); + } +} + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') buffer = Buffer.from(buffer); + + if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer'); + + var flushFlag = engine._finishFlushFlag; + + return engine._processChunk(buffer, flushFlag); +} + +// generic zlib +// minimal 2-byte header +function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib.call(this, opts, binding.DEFLATE); +} + +function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib.call(this, opts, binding.INFLATE); +} + +// gzip - bigger header, same deflate compression +function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib.call(this, opts, binding.GZIP); +} + +function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib.call(this, opts, binding.GUNZIP); +} + +// raw - no header +function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib.call(this, opts, binding.DEFLATERAW); +} + +function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib.call(this, opts, binding.INFLATERAW); +} + +// auto-detect header. +function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib.call(this, opts, binding.UNZIP); +} + +function isValidFlushFlag(flag) { + return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK; +} + +// the Zlib class they all inherit from +// This thing manages the queue of requests, and returns +// true or false if there is anything in the queue when +// you call the .write() method. + +function Zlib(opts, mode) { + var _this = this; + + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK; + + Transform.call(this, opts); + + if (opts.flush && !isValidFlushFlag(opts.flush)) { + throw new Error('Invalid flush flag: ' + opts.flush); + } + if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) { + throw new Error('Invalid flush flag: ' + opts.finishFlush); + } + + this._flushFlag = opts.flush || binding.Z_NO_FLUSH; + this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH; + + if (opts.chunkSize) { + if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); + } + } + + if (opts.windowBits) { + if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!Buffer.isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._handle = new binding.Zlib(mode); + + var self = this; + this._hadError = false; + this._handle.onerror = function (message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + _close(self); + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = exports.codes[errno]; + self.emit('error', error); + }; + + var level = exports.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = exports.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary); + + this._buffer = Buffer.allocUnsafe(this._chunkSize); + this._offset = 0; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); + + Object.defineProperty(this, '_closed', { + get: function () { + return !_this._handle; + }, + configurable: true, + enumerable: true + }); +} + +util.inherits(Zlib, Transform); + +Zlib.prototype.params = function (level, strategy, callback) { + if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding.Z_SYNC_FLUSH, function () { + assert(self._handle, 'zlib binding closed'); + self._handle.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); + } + }); + } else { + process.nextTick(callback); + } +}; + +Zlib.prototype.reset = function () { + assert(this._handle, 'zlib binding closed'); + return this._handle.reset(); +}; + +// This is the _flush function called by the transform class, +// internally, when the last chunk has been written. +Zlib.prototype._flush = function (callback) { + this._transform(Buffer.alloc(0), '', callback); +}; + +Zlib.prototype.flush = function (kind, callback) { + var _this2 = this; + + var ws = this._writableState; + + if (typeof kind === 'function' || kind === undefined && !callback) { + callback = kind; + kind = binding.Z_FULL_FLUSH; + } + + if (ws.ended) { + if (callback) process.nextTick(callback); + } else if (ws.ending) { + if (callback) this.once('end', callback); + } else if (ws.needDrain) { + if (callback) { + this.once('drain', function () { + return _this2.flush(kind, callback); + }); + } + } else { + this._flushFlag = kind; + this.write(Buffer.alloc(0), '', callback); + } +}; + +Zlib.prototype.close = function (callback) { + _close(this, callback); + process.nextTick(emitCloseNT, this); +}; + +function _close(engine, callback) { + if (callback) process.nextTick(callback); + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) return; + + engine._handle.close(); + engine._handle = null; +} + +function emitCloseNT(self) { + self.emit('close'); +} + +Zlib.prototype._transform = function (chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input')); + + if (!this._handle) return cb(new Error('zlib binding closed')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag + // (or whatever flag was provided using opts.finishFlush). + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) flushFlag = this._finishFlushFlag;else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; + } + } + + this._processChunk(chunk, flushFlag, cb); +}; + +Zlib.prototype._processChunk = function (chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function (er) { + error = er; + }); + + assert(this._handle, 'zlib binding closed'); + do { + var res = this._handle.writeSync(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError(kRangeErrorMessage); + } + + var buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; + } + + assert(this._handle, 'zlib binding closed'); + var req = this._handle.write(flushFlag, chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + // When the callback is used in an async write, the callback's + // context is the `req` object that was created. The req object + // is === this._handle, and that's why it's important to null + // out the values after they are done being used. `this._handle` + // can stay in memory longer than the callback and buffer are needed. + if (this) { + this.buffer = null; + this.callback = null; + } + + if (self._hadError) return; + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + if (!async) return true; + + var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) return false; + + // finished with the chunk. + cb(); + } +}; + +util.inherits(Deflate, Zlib); +util.inherits(Inflate, Zlib); +util.inherits(Gzip, Zlib); +util.inherits(Gunzip, Zlib); +util.inherits(DeflateRaw, Zlib); +util.inherits(InflateRaw, Zlib); +util.inherits(Unzip, Zlib); +}).call(this,require('_process')) +},{"./binding":26,"_process":47,"assert":23,"buffer":28,"stream":63,"util":67}],28:[function(require,module,exports){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +var K_MAX_LENGTH = 0x7fffffff +exports.kMaxLength = K_MAX_LENGTH + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ) +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + var arr = new Uint8Array(1) + arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}) + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}) + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + var buf = new Uint8Array(length) + buf.__proto__ = Buffer.prototype + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 +if (typeof Symbol !== 'undefined' && Symbol.species != null && + Buffer[Symbol.species] === Buffer) { + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true, + enumerable: false, + writable: false + }) +} + +Buffer.poolSize = 8192 // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayLike(value) + } + + if (value == null) { + throw TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + var valueOf = value.valueOf && value.valueOf() + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + var b = fromObject(value) + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from( + value[Symbol.toPrimitive]('string'), encodingOrOffset, length + ) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +} + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Buffer.prototype.__proto__ = Uint8Array.prototype +Buffer.__proto__ = Uint8Array + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +} + +function allocUnsafe (size) { + assertSize(size) + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +} + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + var length = byteLength(string, encoding) | 0 + var buf = createBuffer(length) + + var actual = buf.write(string, encoding) + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual) + } + + return buf +} + +function fromArrayLike (array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0 + var buf = createBuffer(length) + for (var i = 0; i < length; i += 1) { + buf[i] = array[i] & 255 + } + return buf +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + var buf + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array) + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset) + } else { + buf = new Uint8Array(array, byteOffset, length) + } + + // Return an augmented `Uint8Array` instance + buf.__proto__ = Buffer.prototype + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + var buf = createBuffer(len) + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len) + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +} + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; ++i) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; ++i) { + var buf = list[i] + if (isInstance(buf, Uint8Array)) { + buf = Buffer.from(buf) + } + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + var len = string.length + var mustMatch = (arguments.length > 2 && arguments[2] === true) + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7) + swap(this, i + 1, i + 6) + swap(this, i + 2, i + 5) + swap(this, i + 3, i + 4) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.toLocaleString = Buffer.prototype.toString + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() + if (this.length > max) str += ' ... ' + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength) + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset = +byteOffset // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1) + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1 + } else if (byteOffset < 0) { + if (dir) byteOffset = 0 + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i + if (dir) { + var foundIndex = -1 + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength + for (i = byteOffset; i >= 0; i--) { + var found = true + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +} + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + var strLen = string.length + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0 + if (isFinite(length)) { + length = length >>> 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; ++i) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf = this.subarray(start, end) + // Return an augmented `Uint8Array` instance + newBuf.__proto__ = Buffer.prototype + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0 + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + byteLength = byteLength >>> 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + var limit = Math.pow(2, (8 * byteLength) - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value + offset = offset >>> 0 + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end) + } else if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (var i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code + } + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding) + var len = bytes.length + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0] + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +},{"base64-js":24,"ieee754":31}],29:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":33}],30:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var objectCreate = Object.create || objectCreatePolyfill +var objectKeys = Object.keys || objectKeysPolyfill +var bind = Function.prototype.bind || functionBindPolyfill + +function EventEmitter() { + if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { + this._events = objectCreate(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +var defaultMaxListeners = 10; + +var hasDefineProperty; +try { + var o = {}; + if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); + hasDefineProperty = o.x === 0; +} catch (err) { hasDefineProperty = false } +if (hasDefineProperty) { + Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + // check whether the input is a positive number (whose value is zero or + // greater and not a NaN). + if (typeof arg !== 'number' || arg < 0 || arg !== arg) + throw new TypeError('"defaultMaxListeners" must be a positive number'); + defaultMaxListeners = arg; + } + }); +} else { + EventEmitter.defaultMaxListeners = defaultMaxListeners; +} + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + if (arguments.length > 1) + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Unhandled "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = objectCreate(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' "' + String(type) + '" listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit.'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + if (typeof console === 'object' && console.warn) { + console.warn('%s: %s', w.name, w.message); + } + } + } + } + + return target; +} + +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + switch (arguments.length) { + case 0: + return this.listener.call(this.target); + case 1: + return this.listener.call(this.target, arguments[0]); + case 2: + return this.listener.call(this.target, arguments[0], arguments[1]); + case 3: + return this.listener.call(this.target, arguments[0], arguments[1], + arguments[2]); + default: + var args = new Array(arguments.length); + for (var i = 0; i < args.length; ++i) + args[i] = arguments[i]; + this.listener.apply(this.target, args); + } + } +} + +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = bind.call(onceWrapper, state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// Emits a 'removeListener' event if and only if the listener was removed. +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = objectCreate(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else + spliceOne(list, position); + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = objectCreate(null); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = objectCreate(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = objectKeys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = objectCreate(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + +function _listeners(target, type, unwrap) { + var events = target._events; + + if (!events) + return []; + + var evlistener = events[type]; + if (!evlistener) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} + +EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; + +EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +function objectCreatePolyfill(proto) { + var F = function() {}; + F.prototype = proto; + return new F; +} +function objectKeysPolyfill(obj) { + var keys = []; + for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { + keys.push(k); + } + return k; +} +function functionBindPolyfill(context) { + var fn = this; + return function () { + return fn.apply(context, arguments); + }; +} + +},{}],31:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],32:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],33:[function(require,module,exports){ +/*! + * Determine if an object is a Buffer + * + * @author Feross Aboukhadijeh + * @license MIT + */ + +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +module.exports = function (obj) { + return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) +} + +function isBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) +} + +},{}],34:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],35:[function(require,module,exports){ +'use strict'; + + +var TYPED_OK = (typeof Uint8Array !== 'undefined') && + (typeof Uint16Array !== 'undefined') && + (typeof Int32Array !== 'undefined'); + +function _has(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} + +exports.assign = function (obj /*from1, from2, from3, ...*/) { + var sources = Array.prototype.slice.call(arguments, 1); + while (sources.length) { + var source = sources.shift(); + if (!source) { continue; } + + if (typeof source !== 'object') { + throw new TypeError(source + 'must be non-object'); + } + + for (var p in source) { + if (_has(source, p)) { + obj[p] = source[p]; + } + } + } + + return obj; +}; + + +// reduce buffer size, avoiding mem copy +exports.shrinkBuf = function (buf, size) { + if (buf.length === size) { return buf; } + if (buf.subarray) { return buf.subarray(0, size); } + buf.length = size; + return buf; +}; + + +var fnTyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + var i, l, len, pos, chunk, result; + + // calculate data length + len = 0; + for (i = 0, l = chunks.length; i < l; i++) { + len += chunks[i].length; + } + + // join chunks + result = new Uint8Array(len); + pos = 0; + for (i = 0, l = chunks.length; i < l; i++) { + chunk = chunks[i]; + result.set(chunk, pos); + pos += chunk.length; + } + + return result; + } +}; + +var fnUntyped = { + arraySet: function (dest, src, src_offs, len, dest_offs) { + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + }, + // Join array of chunks to single array. + flattenChunks: function (chunks) { + return [].concat.apply([], chunks); + } +}; + + +// Enable/Disable typed arrays use, for testing +// +exports.setTyped = function (on) { + if (on) { + exports.Buf8 = Uint8Array; + exports.Buf16 = Uint16Array; + exports.Buf32 = Int32Array; + exports.assign(exports, fnTyped); + } else { + exports.Buf8 = Array; + exports.Buf16 = Array; + exports.Buf32 = Array; + exports.assign(exports, fnUntyped); + } +}; + +exports.setTyped(TYPED_OK); + +},{}],36:[function(require,module,exports){ +'use strict'; + +// Note: adler32 takes 12% for level 0 and 2% for level 6. +// It isn't worth it to make additional optimizations as in original. +// Small size is preferable. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; +} + + +module.exports = adler32; + +},{}],37:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + + /* Allowed flush values; see deflate() and inflate() below for details */ + Z_NO_FLUSH: 0, + Z_PARTIAL_FLUSH: 1, + Z_SYNC_FLUSH: 2, + Z_FULL_FLUSH: 3, + Z_FINISH: 4, + Z_BLOCK: 5, + Z_TREES: 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK: 0, + Z_STREAM_END: 1, + Z_NEED_DICT: 2, + Z_ERRNO: -1, + Z_STREAM_ERROR: -2, + Z_DATA_ERROR: -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR: -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION: 0, + Z_BEST_SPEED: 1, + Z_BEST_COMPRESSION: 9, + Z_DEFAULT_COMPRESSION: -1, + + + Z_FILTERED: 1, + Z_HUFFMAN_ONLY: 2, + Z_RLE: 3, + Z_FIXED: 4, + Z_DEFAULT_STRATEGY: 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY: 0, + Z_TEXT: 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN: 2, + + /* The deflate compression method */ + Z_DEFLATED: 8 + //Z_NULL: null // Use -1 or null inline, depending on var type +}; + +},{}],38:[function(require,module,exports){ +'use strict'; + +// Note: we can't get significant speed boost here. +// So write code to minimize size - no pregenerated tables +// and array tools dependencies. + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// Use ordinary array, since untyped makes no boost here +function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; +} + +// Create table on load. Just 255 signed longs. Not a problem. +var crcTable = makeTable(); + + +function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; +} + + +module.exports = crc32; + +},{}],39:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var trees = require('./trees'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var msg = require('./messages'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +var Z_NO_FLUSH = 0; +var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +//var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +//var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +//var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + + +/* compression levels */ +//var Z_NO_COMPRESSION = 0; +//var Z_BEST_SPEED = 1; +//var Z_BEST_COMPRESSION = 9; +var Z_DEFAULT_COMPRESSION = -1; + + +var Z_FILTERED = 1; +var Z_HUFFMAN_ONLY = 2; +var Z_RLE = 3; +var Z_FIXED = 4; +var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +//var Z_BINARY = 0; +//var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + + +/* The deflate compression method */ +var Z_DEFLATED = 8; + +/*============================================================================*/ + + +var MAX_MEM_LEVEL = 9; +/* Maximum value for memLevel in deflateInit2 */ +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_MEM_LEVEL = 8; + + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ +var LITERALS = 256; +/* number of literal bytes 0..255 */ +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ +var D_CODES = 30; +/* number of distance codes */ +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + +var PRESET_DICT = 0x20; + +var INIT_STATE = 42; +var EXTRA_STATE = 69; +var NAME_STATE = 73; +var COMMENT_STATE = 91; +var HCRC_STATE = 103; +var BUSY_STATE = 113; +var FINISH_STATE = 666; + +var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ +var BS_BLOCK_DONE = 2; /* block flush performed */ +var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ +var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + +var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + +function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; +} + +function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); +} + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ +function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { return; } + + utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } +} + + +function flush_block_only(s, last) { + trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); +} + + +function put_byte(s, b) { + s.pending_buf[s.pending++] = b; +} + + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +function putShortMSB(s, b) { +// put_byte(s, (Byte)(b >> 8)); +// put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; +} + + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ +function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { len = size; } + if (len === 0) { return 0; } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + utils.arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } + + else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; +} + + +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { nice_match = s.lookahead; } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; +} + + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + utils.arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; +//#if MIN_MATCH != 3 +// Call update_hash() MIN_MATCH-3 more times +//#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ +// if (s.high_water < s.window_size) { +// var curr = s.strstart + s.lookahead; +// var init = 0; +// +// if (s.high_water < curr) { +// /* Previous high water mark below current data -- zero WIN_INIT +// * bytes or up to end of window, whichever is less. +// */ +// init = s.window_size - curr; +// if (init > WIN_INIT) +// init = WIN_INIT; +// zmemzero(s->window + curr, (unsigned)init); +// s->high_water = curr + init; +// } +// else if (s->high_water < (ulg)curr + WIN_INIT) { +// /* High water mark at or above current data, but below current data +// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up +// * to end of window, whichever is less. +// */ +// init = (ulg)curr + WIN_INIT - s->high_water; +// if (init > s->window_size - s->high_water) +// init = s->window_size - s->high_water; +// zmemzero(s->window + s->high_water, (unsigned)init); +// s->high_water += init; +// } +// } +// +// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, +// "not enough room for search"); +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); +// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || +// s.block_start >= s.w_size)) { +// throw new Error("slide too late"); +// } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); +// if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else + { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + +//#if MIN_MATCH != 3 +// Call UPDATE_HASH() MIN_MATCH-3 more times +//#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0/*NIL*/; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; +} + + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { break; } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = trees._tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; +} + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; +} + +var configuration_table; + +configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ +]; + + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; +} + + +function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new utils.Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ +} + + +function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH; + trees._tr_init(s); + return Z_OK; +} + + +function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK) { + lm_init(strm.state); + } + return ret; +} + + +function deflateSetHeader(strm, head) { + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } + strm.state.gzhead = head; + return Z_OK; +} + + +function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } + + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return err(strm, Z_STREAM_ERROR); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new utils.Buf8(s.w_size * 2); + s.head = new utils.Buf16(s.hash_size); + s.prev = new utils.Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new utils.Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); +} + +function deflateInit(strm, level) { + return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); +} + + +function deflate(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + + if (s.wrap === 2) { // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } + else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } + else // DEFLATE header + { + var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { header |= PRESET_DICT; } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + +//#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } + else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } + else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment/* != Z_NULL*/) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } + else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } + else { + s.status = BUSY_STATE; + } + } +//#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH) { + return err(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH) { + trees._tr_align(s); + } + else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + + trees._tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH) { + /*** CLEAR_HASH(s); ***/ /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH) { return Z_OK; } + if (s.wrap <= 0) { return Z_STREAM_END; } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } + else + { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { s.wrap = -s.wrap; } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK : Z_STREAM_END; +} + +function deflateEnd(strm) { + var status; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; +} + + +/* ========================================================================= + * Initializes the compression dictionary from the given byte + * sequence without producing any compressed output. + */ +function deflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var s; + var str, n; + var wrap; + var avail; + var next; + var input; + var tmpDict; + + if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { + return Z_STREAM_ERROR; + } + + s = strm.state; + wrap = s.wrap; + + if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) { + return Z_STREAM_ERROR; + } + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap === 1) { + /* adler32(strm->adler, dictionary, dictLength); */ + strm.adler = adler32(strm.adler, dictionary, dictLength, 0); + } + + s.wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s.w_size) { + if (wrap === 0) { /* already empty otherwise */ + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + /* use the tail */ + // dictionary = dictionary.slice(dictLength - s.w_size); + tmpDict = new utils.Buf8(s.w_size); + utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0); + dictionary = tmpDict; + dictLength = s.w_size; + } + /* insert dictionary into window and hash */ + avail = strm.avail_in; + next = strm.next_in; + input = strm.input; + strm.avail_in = dictLength; + strm.next_in = 0; + strm.input = dictionary; + fill_window(s); + while (s.lookahead >= MIN_MATCH) { + str = s.strstart; + n = s.lookahead - (MIN_MATCH - 1); + do { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + + s.head[s.ins_h] = str; + str++; + } while (--n); + s.strstart = str; + s.lookahead = MIN_MATCH - 1; + fill_window(s); + } + s.strstart += s.lookahead; + s.block_start = s.strstart; + s.insert = s.lookahead; + s.lookahead = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + strm.next_in = next; + strm.input = input; + strm.avail_in = avail; + s.wrap = wrap; + return Z_OK; +} + + +exports.deflateInit = deflateInit; +exports.deflateInit2 = deflateInit2; +exports.deflateReset = deflateReset; +exports.deflateResetKeep = deflateResetKeep; +exports.deflateSetHeader = deflateSetHeader; +exports.deflate = deflate; +exports.deflateEnd = deflateEnd; +exports.deflateSetDictionary = deflateSetDictionary; +exports.deflateInfo = 'pako deflate (from Nodeca project)'; + +/* Not implemented +exports.deflateBound = deflateBound; +exports.deflateCopy = deflateCopy; +exports.deflateParams = deflateParams; +exports.deflatePending = deflatePending; +exports.deflatePrime = deflatePrime; +exports.deflateTune = deflateTune; +*/ + +},{"../utils/common":35,"./adler32":36,"./crc32":38,"./messages":43,"./trees":44}],40:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +// See state defs from inflate.js +var BAD = 30; /* got a data error -- remain here until reset */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ +module.exports = function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ +//#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ +//#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); +//#ifdef INFLATE_STRICT + dmax = state.dmax; +//#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); +//#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } +//#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break top; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// if (len <= op - whave) { +// do { +// output[_out++] = 0; +// } while (--len); +// continue top; +// } +// len -= op - whave; +// do { +// output[_out++] = 0; +// } while (--op > whave); +// if (op === 0) { +// from = _out - dist; +// do { +// output[_out++] = output[from++]; +// } while (--len); +// continue top; +// } +//#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; +}; + +},{}],41:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); +var adler32 = require('./adler32'); +var crc32 = require('./crc32'); +var inflate_fast = require('./inffast'); +var inflate_table = require('./inftrees'); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +/* Allowed flush values; see deflate() and inflate() below for details */ +//var Z_NO_FLUSH = 0; +//var Z_PARTIAL_FLUSH = 1; +//var Z_SYNC_FLUSH = 2; +//var Z_FULL_FLUSH = 3; +var Z_FINISH = 4; +var Z_BLOCK = 5; +var Z_TREES = 6; + + +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ +var Z_OK = 0; +var Z_STREAM_END = 1; +var Z_NEED_DICT = 2; +//var Z_ERRNO = -1; +var Z_STREAM_ERROR = -2; +var Z_DATA_ERROR = -3; +var Z_MEM_ERROR = -4; +var Z_BUF_ERROR = -5; +//var Z_VERSION_ERROR = -6; + +/* The deflate compression method */ +var Z_DEFLATED = 8; + + +/* STATES ====================================================================*/ +/* ===========================================================================*/ + + +var HEAD = 1; /* i: waiting for magic header */ +var FLAGS = 2; /* i: waiting for method and flags (gzip) */ +var TIME = 3; /* i: waiting for modification time (gzip) */ +var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ +var EXLEN = 5; /* i: waiting for extra length (gzip) */ +var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ +var NAME = 7; /* i: waiting for end of file name (gzip) */ +var COMMENT = 8; /* i: waiting for end of comment (gzip) */ +var HCRC = 9; /* i: waiting for header crc (gzip) */ +var DICTID = 10; /* i: waiting for dictionary check value */ +var DICT = 11; /* waiting for inflateSetDictionary() call */ +var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ +var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ +var STORED = 14; /* i: waiting for stored size (length and complement) */ +var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ +var COPY = 16; /* i/o: waiting for input or output to copy stored block */ +var TABLE = 17; /* i: waiting for dynamic block table lengths */ +var LENLENS = 18; /* i: waiting for code length code lengths */ +var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ +var LEN_ = 20; /* i: same as LEN below, but only first time in */ +var LEN = 21; /* i: waiting for length/lit/eob code */ +var LENEXT = 22; /* i: waiting for length extra bits */ +var DIST = 23; /* i: waiting for distance code */ +var DISTEXT = 24; /* i: waiting for distance extra bits */ +var MATCH = 25; /* o: waiting for output space to copy string */ +var LIT = 26; /* o: waiting for output space to write literal */ +var CHECK = 27; /* i: waiting for 32-bit check value */ +var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ +var DONE = 29; /* finished check, done -- remain here until reset */ +var BAD = 30; /* got a data error -- remain here until reset */ +var MEM = 31; /* got an inflate() memory error -- remain here until reset */ +var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + +/* ===========================================================================*/ + + + +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var MAX_WBITS = 15; +/* 32K LZ77 window */ +var DEF_WBITS = MAX_WBITS; + + +function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); +} + + +function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ + this.work = new utils.Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ +} + +function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null/*Z_NULL*/; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + +} + +function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); +} + +function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { return Z_STREAM_ERROR; } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null/*Z_NULL*/; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK) { + strm.state = null/*Z_NULL*/; + } + return ret; +} + +function inflateInit(strm) { + return inflateInit2(strm, DEF_WBITS); +} + + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +var virgin = true; + +var lenfix, distfix; // We have no pointers in JS, so keep tables separate + +function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new utils.Buf32(512); + distfix = new utils.Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { state.lens[sym++] = 8; } + while (sym < 256) { state.lens[sym++] = 9; } + while (sym < 280) { state.lens[sym++] = 7; } + while (sym < 288) { state.lens[sym++] = 8; } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); + + /* distance table */ + sym = 0; + while (sym < 32) { state.lens[sym++] = 5; } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; +} + + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new utils.Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } + else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + utils.arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + utils.arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } + else { + state.wnext += dist; + if (state.wnext === state.wsize) { state.wnext = 0; } + if (state.whave < state.wsize) { state.whave += dist; } + } + } + return 0; +} + +function inflate(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ + [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR; + } + + state = strm.state; + if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0/*crc32(0L, Z_NULL, 0)*/; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f)/*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } + else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + else if (state.head) { + state.head.extra = null/*Z_NULL*/; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { copy = have; } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more convenient processing later + state.head.extra = new Array(state.head.extra_len); + } + utils.arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { break inf_leave; } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/)) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { break inf_leave; } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/)) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { break inf_leave; } + } + else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT; + } + strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01)/*BITS(1)*/; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03)/*BITS(2)*/) { + case 0: /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { copy = have; } + if (copy > left) { copy = left; } + if (copy === 0) { break inf_leave; } + //--- zmemcpy(put, next, copy); --- + utils.arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// +//#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } +//#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { bits: state.lenbits }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } + else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03);//BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } + else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07);//BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f);//BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { break; } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { bits: state.lenbits }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { bits: state.distbits }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES) { break inf_leave; } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { break; } + //--- PULLBYTE() ---// + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } +//#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +//#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { break inf_leave; } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility +//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR +// Trace((stderr, "inflate.c too far\n")); +// copy -= state.whave; +// if (copy > state.length) { copy = state.length; } +// if (copy > left) { copy = left; } +// left -= copy; +// state.length -= copy; +// do { +// output[put++] = 0; +// } while (--copy); +// if (state.length === 0) { state.mode = LEN; } +// break; +//#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } + else { + from = state.wnext - copy; + } + if (copy > state.length) { copy = state.length; } + from_source = state.window; + } + else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { copy = left; } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { state.mode = LEN; } + break; + case LIT: + if (left === 0) { break inf_leave; } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + // Use '|' instead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { break inf_leave; } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { + state.mode = MEM; + return Z_MEM_ERROR; + } + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { + ret = Z_BUF_ERROR; + } + return ret; +} + +function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { + return Z_STREAM_ERROR; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK; +} + +function inflateGetHeader(strm, head) { + var state; + + /* check state */ + if (!strm || !strm.state) { return Z_STREAM_ERROR; } + state = strm.state; + if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } + + /* save header structure */ + state.head = head; + head.done = false; + return Z_OK; +} + +function inflateSetDictionary(strm, dictionary) { + var dictLength = dictionary.length; + + var state; + var dictid; + var ret; + + /* check state */ + if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; } + state = strm.state; + + if (state.wrap !== 0 && state.mode !== DICT) { + return Z_STREAM_ERROR; + } + + /* check for correct dictionary identifier */ + if (state.mode === DICT) { + dictid = 1; /* adler32(0, null, 0)*/ + /* dictid = adler32(dictid, dictionary, dictLength); */ + dictid = adler32(dictid, dictionary, dictLength, 0); + if (dictid !== state.check) { + return Z_DATA_ERROR; + } + } + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary, dictLength, dictLength); + if (ret) { + state.mode = MEM; + return Z_MEM_ERROR; + } + state.havedict = 1; + // Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +exports.inflateReset = inflateReset; +exports.inflateReset2 = inflateReset2; +exports.inflateResetKeep = inflateResetKeep; +exports.inflateInit = inflateInit; +exports.inflateInit2 = inflateInit2; +exports.inflate = inflate; +exports.inflateEnd = inflateEnd; +exports.inflateGetHeader = inflateGetHeader; +exports.inflateSetDictionary = inflateSetDictionary; +exports.inflateInfo = 'pako inflate (from Nodeca project)'; + +/* Not implemented +exports.inflateCopy = inflateCopy; +exports.inflateGetDictionary = inflateGetDictionary; +exports.inflateMark = inflateMark; +exports.inflatePrime = inflatePrime; +exports.inflateSync = inflateSync; +exports.inflateSyncPoint = inflateSyncPoint; +exports.inflateUndermine = inflateUndermine; +*/ + +},{"../utils/common":35,"./adler32":36,"./crc32":38,"./inffast":40,"./inftrees":42}],42:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); + +var MAXBITS = 15; +var ENOUGH_LENS = 852; +var ENOUGH_DISTS = 592; +//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + +var CODES = 0; +var LENS = 1; +var DISTS = 2; + +var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 +]; + +var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 +]; + +var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 +]; + +var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 +]; + +module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) +{ + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; +// var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { break; } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { break; } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } + else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } + else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { break; } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { break; } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS && used > ENOUGH_LENS) || + (type === DISTS && used > ENOUGH_DISTS)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; +}; + +},{"../utils/common":35}],43:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +module.exports = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ +}; + +},{}],44:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +var utils = require('../utils/common'); + +/* Public constants ==========================================================*/ +/* ===========================================================================*/ + + +//var Z_FILTERED = 1; +//var Z_HUFFMAN_ONLY = 2; +//var Z_RLE = 3; +var Z_FIXED = 4; +//var Z_DEFAULT_STRATEGY = 0; + +/* Possible values of the data_type field (though see inflate()) */ +var Z_BINARY = 0; +var Z_TEXT = 1; +//var Z_ASCII = 1; // = Z_TEXT +var Z_UNKNOWN = 2; + +/*============================================================================*/ + + +function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } + +// From zutil.h + +var STORED_BLOCK = 0; +var STATIC_TREES = 1; +var DYN_TREES = 2; +/* The three kinds of block type */ + +var MIN_MATCH = 3; +var MAX_MATCH = 258; +/* The minimum and maximum match lengths */ + +// From deflate.h +/* =========================================================================== + * Internal compression state. + */ + +var LENGTH_CODES = 29; +/* number of length codes, not counting the special END_BLOCK code */ + +var LITERALS = 256; +/* number of literal bytes 0..255 */ + +var L_CODES = LITERALS + 1 + LENGTH_CODES; +/* number of Literal or Length codes, including the END_BLOCK code */ + +var D_CODES = 30; +/* number of distance codes */ + +var BL_CODES = 19; +/* number of codes used to transfer the bit lengths */ + +var HEAP_SIZE = 2 * L_CODES + 1; +/* maximum heap size */ + +var MAX_BITS = 15; +/* All codes must not exceed MAX_BITS bits */ + +var Buf_size = 16; +/* size of bit buffer in bi_buf */ + + +/* =========================================================================== + * Constants + */ + +var MAX_BL_BITS = 7; +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +var END_BLOCK = 256; +/* end of block literal code */ + +var REP_3_6 = 16; +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +var REPZ_3_10 = 17; +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +var REPZ_11_138 = 18; +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +/* eslint-disable comma-spacing,array-bracket-spacing */ +var extra_lbits = /* extra bits for each length code */ + [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; + +var extra_dbits = /* extra bits for each distance code */ + [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; + +var extra_blbits = /* extra bits for each bit length code */ + [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; + +var bl_order = + [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; +/* eslint-enable comma-spacing,array-bracket-spacing */ + +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +// We pre-fill arrays with 0 to avoid uninitialized gaps + +var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + +// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1 +var static_ltree = new Array((L_CODES + 2) * 2); +zero(static_ltree); +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +var static_dtree = new Array(D_CODES * 2); +zero(static_dtree); +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +var _dist_code = new Array(DIST_CODE_LEN); +zero(_dist_code); +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); +zero(_length_code); +/* length code for each normalized match length (0 == MIN_MATCH) */ + +var base_length = new Array(LENGTH_CODES); +zero(base_length); +/* First normalized length for each code (0 = MIN_MATCH) */ + +var base_dist = new Array(D_CODES); +zero(base_dist); +/* First normalized distance for each code (0 = distance of 1) */ + + +function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; +} + + +var static_l_desc; +var static_d_desc; +var static_bl_desc; + + +function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ +} + + + +function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; +} + + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +function put_short(s, w) { +// put_byte(s, (uch)((w) & 0xff)); +// put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; +} + + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } +} + + +function send_code(s, c, tree) { + send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); +} + + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; +} + + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } +} + + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +function gen_bitlen(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1]/*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { continue; } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2]/*.Freq*/; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); + } + } + if (overflow === 0) { return; } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { bits--; } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { continue; } + if (tree[m * 2 + 1]/*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; + tree[m * 2 + 1]/*.Len*/ = bits; + } + n--; + } + } +} + + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +function gen_codes(tree, max_code, bl_count) +// ct_data *tree; /* the tree to decorate */ +// int max_code; /* largest code with non zero frequency */ +// ushf *bl_count; /* number of codes at each bit length */ +{ + var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1]/*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1]/*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1]/*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n * 2 + 1]/*.Len*/ = 5; + static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); + + //static_init_done = true; +} + + +/* =========================================================================== + * Initialize a new block. + */ +function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } + for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } + + s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; +} + + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +function bi_windup(s) +{ + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +function copy_block(s, buf, len, header) +//DeflateState *s; +//charf *buf; /* the input data */ +//unsigned len; /* its length */ +//int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } +// while (len--) { +// put_byte(s, *buf++); +// } + utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || + (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); +} + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +function pqdownheap(s, tree, k) +// deflate_state *s; +// ct_data *tree; /* the tree to restore */ +// int k; /* node to move down */ +{ + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { break; } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; +} + + +// inlined manually +// var SMALLEST = 1; + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +function compress_block(s, ltree, dtree) +// deflate_state *s; +// const ct_data *ltree; /* literal tree */ +// const ct_data *dtree; /* distance tree */ +{ + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); +} + + +/* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ +function build_tree(s, desc) +// deflate_state *s; +// tree_desc *desc; /* the tree descriptor */ +{ + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n * 2]/*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1]/*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2]/*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1]/*.Len*/; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1/*SMALLEST*/]; + s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1/*SMALLEST*/); + /***/ + + m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1/*SMALLEST*/] = node++; + pqdownheap(s, tree, 1/*SMALLEST*/); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); +} + + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +function scan_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2]/*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } + s.bl_tree[REP_3_6 * 2]/*.Freq*/++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; + + } else { + s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +function send_tree(s, tree, max_code) +// deflate_state *s; +// ct_data *tree; /* the tree to be scanned */ +// int max_code; /* and its largest code of non zero frequency */ +{ + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } +} + + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; +} + + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +function send_all_trees(s, lcodes, dcodes, blcodes) +// deflate_state *s; +// int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { + return Z_BINARY; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + for (n = 32; n < LITERALS; n++) { + if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { + return Z_TEXT; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + + +var static_init_done = false; + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +function _tr_init(s) +{ + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); +} + + +/* =========================================================================== + * Send a stored block + */ +function _tr_stored_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ +} + + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); +} + + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +function _tr_flush_block(s, buf, stored_len, last) +//DeflateState *s; +//charf *buf; /* input block, or NULL if too old */ +//ulg stored_len; /* length of input block */ +//int last; /* one if this is the last block for a file */ +{ + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +function _tr_tally(s, dist, lc) +// deflate_state *s; +// unsigned dist; /* distance of matched string */ +// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2]/*.Freq*/++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; + s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; + } + +// (!) This block is disabled in zlib defaults, +// don't enable it for binary compatibility + +//#ifdef TRUNCATE_BLOCK +// /* Try to guess if it is profitable to stop the current block here */ +// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { +// /* Compute an upper bound for the compressed length */ +// out_length = s.last_lit*8; +// in_length = s.strstart - s.block_start; +// +// for (dcode = 0; dcode < D_CODES; dcode++) { +// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); +// } +// out_length >>>= 3; +// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", +// // s->last_lit, in_length, out_length, +// // 100L - out_length*100L/in_length)); +// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { +// return true; +// } +// } +//#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +exports._tr_init = _tr_init; +exports._tr_stored_block = _tr_stored_block; +exports._tr_flush_block = _tr_flush_block; +exports._tr_tally = _tr_tally; +exports._tr_align = _tr_align; + +},{"../utils/common":35}],45:[function(require,module,exports){ +'use strict'; + +// (C) 1995-2013 Jean-loup Gailly and Mark Adler +// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin +// +// This software is provided 'as-is', without any express or implied +// warranty. In no event will the authors be held liable for any damages +// arising from the use of this software. +// +// Permission is granted to anyone to use this software for any purpose, +// including commercial applications, and to alter it and redistribute it +// freely, subject to the following restrictions: +// +// 1. The origin of this software must not be misrepresented; you must not +// claim that you wrote the original software. If you use this software +// in a product, an acknowledgment in the product documentation would be +// appreciated but is not required. +// 2. Altered source versions must be plainly marked as such, and must not be +// misrepresented as being the original software. +// 3. This notice may not be removed or altered from any source distribution. + +function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; +} + +module.exports = ZStream; + +},{}],46:[function(require,module,exports){ +(function (process){ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + +}).call(this,require('_process')) +},{"_process":47}],47:[function(require,module,exports){ +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; + +process.listeners = function (name) { return [] } + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],48:[function(require,module,exports){ +module.exports = require('./lib/_stream_duplex.js'); + +},{"./lib/_stream_duplex.js":49}],49:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } +}); + +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); + + processNextTick(cb, err); +}; + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} +},{"./_stream_readable":51,"./_stream_writable":53,"core-util-is":29,"inherits":32,"process-nextick-args":46}],50:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":52,"core-util-is":29,"inherits":32}],51:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; + +/**/ + +var processNextTick = require('process-nextick-args'); +/**/ + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + +/**/ +var Duplex; +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +// TODO(bmeurer): Change this back to const once hole checks are +// properly optimized away early in Ignition+TurboFan. +/**/ +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var BufferList = require('./internal/streams/BufferList'); +var destroyImpl = require('./internal/streams/destroy'); +var StringDecoder; + +util.inherits(Readable, Stream); + +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; + } +} + +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // has it been destroyed + this.destroyed = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options) { + if (typeof options.read === 'function') this._read = options.read; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } + + Stream.call(this); +} + +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); + +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; + + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; + } + + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); +}; + +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } + + return needMoreData(state); +} + +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} + +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, unpipeInfo); + }return this; + } + + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; + + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this, unpipeInfo); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); + } + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":49,"./internal/streams/BufferList":54,"./internal/streams/destroy":55,"./internal/streams/stream":56,"_process":47,"core-util-is":29,"events":30,"inherits":32,"isarray":34,"process-nextick-args":46,"safe-buffer":62,"string_decoder/":57,"util":25}],52:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) { + return stream.emit('error', new Error('write callback called multiple times')); + } + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er, data) { + done(stream, er, data); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +Transform.prototype._destroy = function (err, cb) { + var _this = this; + + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this.emit('close'); + }); +}; + +function done(stream, er, data) { + if (er) return stream.emit('error', er); + + if (data !== null && data !== undefined) stream.push(data); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} +},{"./_stream_duplex":49,"core-util-is":29,"inherits":32}],53:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +/**/ + +var processNextTick = require('process-nextick-args'); +/**/ + +module.exports = Writable; + +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/**/ + +/**/ +var Duplex; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream = require('./internal/streams/stream'); +/**/ + +/**/ +var Buffer = require('safe-buffer').Buffer; +var OurUint8Array = global.Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} +/**/ + +var destroyImpl = require('./internal/streams/destroy'); + +util.inherits(Writable, Stream); + +function nop() {} + +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); + + // if _final has been called + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // has it been destroyed + this.destroyed = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); + +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + + return object && object._writableState instanceof WritableState; + } + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} + +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + + if (typeof options.destroy === 'function') this._destroy = options.destroy; + + if (typeof options.final === 'function') this._final = options.final; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} + +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = _isUint8Array(chunk) && !state.objectMode; + + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + processNextTick(cb, er); + // this can emit finish, and it will always happen + // after error + processNextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + processNextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = corkReq; + } else { + state.corkedRequestsFree = corkReq; + } +} + +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); + +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./_stream_duplex":49,"./internal/streams/destroy":55,"./internal/streams/stream":56,"_process":47,"core-util-is":29,"inherits":32,"process-nextick-args":46,"safe-buffer":62,"util-deprecate":64}],54:[function(require,module,exports){ +'use strict'; + +/**/ + +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + +var Buffer = require('safe-buffer').Buffer; +/**/ + +function copyBuffer(src, target, offset) { + src.copy(target, offset); +} + +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); + + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + return BufferList; +}(); +},{"safe-buffer":62}],55:[function(require,module,exports){ +'use strict'; + +/**/ + +var processNextTick = require('process-nextick-args'); +/**/ + +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; + + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; + + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { + processNextTick(emitErrorNT, this, err); + } + return; + } + + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; + } + + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; + } + + this._destroy(err || null, function (err) { + if (!cb && err) { + processNextTick(emitErrorNT, _this, err); + if (_this._writableState) { + _this._writableState.errorEmitted = true; + } + } else if (cb) { + cb(err); + } + }); +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; + } + + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; + } +} + +function emitErrorNT(self, err) { + self.emit('error', err); +} + +module.exports = { + destroy: destroy, + undestroy: undestroy +}; +},{"process-nextick-args":46}],56:[function(require,module,exports){ +module.exports = require('events').EventEmitter; + +},{"events":30}],57:[function(require,module,exports){ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } +}; + +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; + +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.StringDecoder = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); +} + +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; + +StringDecoder.prototype.end = utf8End; + +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; + +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; + +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return -1; +} + +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; +} + +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'.repeat(p); + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'.repeat(p + 1); + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'.repeat(p + 2); + } + } + } +} + +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} + +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); +} + +// For UTF-8, a replacement character for each buffered byte of a (partial) +// character needs to be added to the output. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); + return r; +} + +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); +} + +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; +} + +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); +} + +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} + +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} + +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; +} +},{"safe-buffer":62}],58:[function(require,module,exports){ +module.exports = require('./readable').PassThrough + +},{"./readable":59}],59:[function(require,module,exports){ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +},{"./lib/_stream_duplex.js":49,"./lib/_stream_passthrough.js":50,"./lib/_stream_readable.js":51,"./lib/_stream_transform.js":52,"./lib/_stream_writable.js":53}],60:[function(require,module,exports){ +module.exports = require('./readable').Transform + +},{"./readable":59}],61:[function(require,module,exports){ +module.exports = require('./lib/_stream_writable.js'); + +},{"./lib/_stream_writable.js":53}],62:[function(require,module,exports){ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} + +},{"buffer":28}],63:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":30,"inherits":32,"readable-stream/duplex.js":48,"readable-stream/passthrough.js":58,"readable-stream/readable.js":59,"readable-stream/transform.js":60,"readable-stream/writable.js":61}],64:[function(require,module,exports){ +(function (global){ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],65:[function(require,module,exports){ +arguments[4][32][0].apply(exports,arguments) +},{"dup":32}],66:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],67:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":66,"_process":47,"inherits":65}]},{},[20])(20) +}); \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/base.css b/node_modules/pngjs/coverage/lcov-report/base.css new file mode 100644 index 0000000..ac7c23c --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/base.css @@ -0,0 +1,354 @@ +body, +html { + margin: 0; + padding: 0; + height: 100%; +} +body { + font-family: Helvetica Neue, Helvetica, Arial; + font-size: 14px; + color: #333; +} +.small { + font-size: 12px; +} +*, +*:after, +*:before { + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} +h1 { + font-size: 20px; + margin: 0; +} +h2 { + font-size: 14px; +} +pre { + font: 12px/1.4 Consolas, "Liberation Mono", Menlo, Courier, monospace; + margin: 0; + padding: 0; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} +a { + color: #0074d9; + text-decoration: none; +} +a:hover { + text-decoration: underline; +} +.strong { + font-weight: bold; +} +.space-top1 { + padding: 10px 0 0 0; +} +.pad2y { + padding: 20px 0; +} +.pad1y { + padding: 10px 0; +} +.pad2x { + padding: 0 20px; +} +.pad2 { + padding: 20px; +} +.pad1 { + padding: 10px; +} +.space-left2 { + padding-left: 55px; +} +.space-right2 { + padding-right: 20px; +} +.center { + text-align: center; +} +.clearfix { + display: block; +} +.clearfix:after { + content: ""; + display: block; + height: 0; + clear: both; + visibility: hidden; +} +.fl { + float: left; +} +@media only screen and (max-width: 640px) { + .col3 { + width: 100%; + max-width: 100%; + } + .hide-mobile { + display: none !important; + } +} + +.quiet { + color: #7f7f7f; + color: rgba(0, 0, 0, 0.5); +} +.quiet a { + opacity: 0.7; +} + +.fraction { + font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace; + font-size: 10px; + color: #555; + background: #e8e8e8; + padding: 4px 5px; + border-radius: 3px; + vertical-align: middle; +} + +div.path a:link, +div.path a:visited { + color: #333; +} +table.coverage { + border-collapse: collapse; + margin: 10px 0 0 0; + padding: 0; +} + +table.coverage td { + margin: 0; + padding: 0; + vertical-align: top; +} +table.coverage td.line-count { + text-align: right; + padding: 0 5px 0 20px; +} +table.coverage td.line-coverage { + text-align: right; + padding-right: 10px; + min-width: 20px; +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 100%; +} +.missing-if-branch { + display: inline-block; + margin-right: 5px; + border-radius: 3px; + position: relative; + padding: 0 4px; + background: #333; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} +.missing-if-branch .typ, +.skip-if-branch .typ { + color: inherit !important; +} +.coverage-summary { + border-collapse: collapse; + width: 100%; +} +.coverage-summary tr { + border-bottom: 1px solid #bbb; +} +.keyline-all { + border: 1px solid #ddd; +} +.coverage-summary td, +.coverage-summary th { + padding: 10px; +} +.coverage-summary tbody { + border: 1px solid #bbb; +} +.coverage-summary td { + border-right: 1px solid #bbb; +} +.coverage-summary td:last-child { + border-right: none; +} +.coverage-summary th { + text-align: left; + font-weight: normal; + white-space: nowrap; +} +.coverage-summary th.file { + border-right: none !important; +} +.coverage-summary th.pct { +} +.coverage-summary th.pic, +.coverage-summary th.abs, +.coverage-summary td.pct, +.coverage-summary td.abs { + text-align: right; +} +.coverage-summary td.file { + white-space: nowrap; +} +.coverage-summary td.pic { + min-width: 120px !important; +} +.coverage-summary tfoot td { +} + +.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} +.status-line { + height: 10px; +} +/* yellow */ +.cbranch-no { + background: yellow !important; + color: #111; +} +/* dark red */ +.red.solid, +.status-line.low, +.low .cover-fill { + background: #c21f39; +} +.low .chart { + border: 1px solid #c21f39; +} +.highlighted, +.highlighted .cstat-no, +.highlighted .fstat-no, +.highlighted .cbranch-no { + background: #c21f39 !important; +} +/* medium red */ +.cstat-no, +.fstat-no, +.cbranch-no, +.cbranch-no { + background: #f6c6ce; +} +/* light red */ +.low, +.cline-no { + background: #fce1e5; +} +/* light green */ +.high, +.cline-yes { + background: rgb(230, 245, 208); +} +/* medium green */ +.cstat-yes { + background: rgb(161, 215, 106); +} +/* dark green */ +.status-line.high, +.high .cover-fill { + background: rgb(77, 146, 33); +} +.high .chart { + border: 1px solid rgb(77, 146, 33); +} +/* dark yellow (gold) */ +.status-line.medium, +.medium .cover-fill { + background: #f9cd0b; +} +.medium .chart { + border: 1px solid #f9cd0b; +} +/* light yellow */ +.medium { + background: #fff4c2; +} + +.cstat-skip { + background: #ddd; + color: #111; +} +.fstat-skip { + background: #ddd; + color: #111 !important; +} +.cbranch-skip { + background: #ddd !important; + color: #111; +} + +span.cline-neutral { + background: #eaeaea; +} + +.coverage-summary td.empty { + opacity: 0.5; + padding-top: 4px; + padding-bottom: 4px; + line-height: 1; + color: #888; +} + +.cover-fill, +.cover-empty { + display: inline-block; + height: 12px; +} +.chart { + line-height: 0; +} +.cover-empty { + background: white; +} +.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { + color: #999 !important; +} +.ignore-none { + color: #999; + font-weight: normal; +} + +.wrapper { + min-height: 100%; + height: auto !important; + height: 100%; + margin: 0 auto -48px; +} +.footer, +.push { + height: 48px; +} diff --git a/node_modules/pngjs/coverage/lcov-report/bitmapper.js.html b/node_modules/pngjs/coverage/lcov-report/bitmapper.js.html new file mode 100644 index 0000000..bafa89b --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/bitmapper.js.html @@ -0,0 +1,881 @@ + + + + + + Code coverage report for bitmapper.js + + + + + + + + + +
+
+

All files bitmapper.js

+
+ +
+ 94.37% + Statements + 134/142 +
+ + +
+ 72.41% + Branches + 21/29 +
+ + +
+ 89.47% + Functions + 17/19 +
+ + +
+ 94.16% + Lines + 129/137 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268  +  +1x +  +1x +  +  +  +  +  +  +313632x +  +  +  +313632x +313632x +313632x +313632x +313632x +  +  +  +  +  +8192x +  +  +  +8192x +8192x +8192x +8192x +8192x +  +  +  +  +  +1228160x +  +  +  +1228160x +1228160x +1228160x +1228160x +  +  +  +  +  +272640x +  +  +  +272640x +272640x +272640x +272640x +  +  +  +1x +  +  +  +  +  +  +1193380x +1193380x +1193380x +1193380x +1193380x +  +  +  +  +  +8192x +8192x +8192x +8192x +8192x +  +  +  +  +  +24576x +24576x +24576x +24576x +  +  +  +  +  +8192x +8192x +8192x +8192x +  +  +  +  +209x +209x +  +  +334250x +  +  +334250x +334250x +  +334250x +  +  +  +149504x +149504x +149504x +149504x +  +49612x +49612x +49612x +49612x +  +2968x +2968x +2968x +2968x +2968x +2968x +  +132166x +132166x +132166x +132166x +132166x +132166x +132166x +132166x +132166x +132166x +  +  +  +209x +  +1234340x +334250x +  +1234340x +1234340x +1234340x +  +  +8106x +  +  +209x +  +  +  +  +  +  +  +  +210x +210x +210x +210x +7288x +1822624x +1822624x +1822624x +  +  +210x +  +  +  +  +529x +529x +529x +529x +8106x +1234340x +1234340x +1234340x +  +8106x +  +  +  +1x +335x +335x +335x +335x +335x +  +  +335x +209x +  +  +335x +269x +  +66x +  +335x +335x +  +  +  +335x +72x +72x +  +263x +263x +2732114x +2732114x +2732114x +  +263x +  +  +335x +739x +210x +  +  +  +  +  +  +  +  +529x +  +  +  +  +  +  +  +  +  +335x +126x +  +  +  +209x +  +  +335x +  + 
"use strict";
+ 
+let interlaceUtils = require("./interlace");
+ 
+let pixelBppMapper = [
+  // 0 - dummy entry
+  function () {},
+ 
+  // 1 - L
+  // 0: 0, 1: 0, 2: 0, 3: 0xff
+  function (pxData, data, pxPos, rawPos) {
+    Iif (rawPos === data.length) {
+      throw new Error("Ran out of data");
+    }
+ 
+    let pixel = data[rawPos];
+    pxData[pxPos] = pixel;
+    pxData[pxPos + 1] = pixel;
+    pxData[pxPos + 2] = pixel;
+    pxData[pxPos + 3] = 0xff;
+  },
+ 
+  // 2 - LA
+  // 0: 0, 1: 0, 2: 0, 3: 1
+  function (pxData, data, pxPos, rawPos) {
+    Iif (rawPos + 1 >= data.length) {
+      throw new Error("Ran out of data");
+    }
+ 
+    let pixel = data[rawPos];
+    pxData[pxPos] = pixel;
+    pxData[pxPos + 1] = pixel;
+    pxData[pxPos + 2] = pixel;
+    pxData[pxPos + 3] = data[rawPos + 1];
+  },
+ 
+  // 3 - RGB
+  // 0: 0, 1: 1, 2: 2, 3: 0xff
+  function (pxData, data, pxPos, rawPos) {
+    Iif (rawPos + 2 >= data.length) {
+      throw new Error("Ran out of data");
+    }
+ 
+    pxData[pxPos] = data[rawPos];
+    pxData[pxPos + 1] = data[rawPos + 1];
+    pxData[pxPos + 2] = data[rawPos + 2];
+    pxData[pxPos + 3] = 0xff;
+  },
+ 
+  // 4 - RGBA
+  // 0: 0, 1: 1, 2: 2, 3: 3
+  function (pxData, data, pxPos, rawPos) {
+    Iif (rawPos + 3 >= data.length) {
+      throw new Error("Ran out of data");
+    }
+ 
+    pxData[pxPos] = data[rawPos];
+    pxData[pxPos + 1] = data[rawPos + 1];
+    pxData[pxPos + 2] = data[rawPos + 2];
+    pxData[pxPos + 3] = data[rawPos + 3];
+  },
+];
+ 
+let pixelBppCustomMapper = [
+  // 0 - dummy entry
+  function () {},
+ 
+  // 1 - L
+  // 0: 0, 1: 0, 2: 0, 3: 0xff
+  function (pxData, pixelData, pxPos, maxBit) {
+    let pixel = pixelData[0];
+    pxData[pxPos] = pixel;
+    pxData[pxPos + 1] = pixel;
+    pxData[pxPos + 2] = pixel;
+    pxData[pxPos + 3] = maxBit;
+  },
+ 
+  // 2 - LA
+  // 0: 0, 1: 0, 2: 0, 3: 1
+  function (pxData, pixelData, pxPos) {
+    let pixel = pixelData[0];
+    pxData[pxPos] = pixel;
+    pxData[pxPos + 1] = pixel;
+    pxData[pxPos + 2] = pixel;
+    pxData[pxPos + 3] = pixelData[1];
+  },
+ 
+  // 3 - RGB
+  // 0: 0, 1: 1, 2: 2, 3: 0xff
+  function (pxData, pixelData, pxPos, maxBit) {
+    pxData[pxPos] = pixelData[0];
+    pxData[pxPos + 1] = pixelData[1];
+    pxData[pxPos + 2] = pixelData[2];
+    pxData[pxPos + 3] = maxBit;
+  },
+ 
+  // 4 - RGBA
+  // 0: 0, 1: 1, 2: 2, 3: 3
+  function (pxData, pixelData, pxPos) {
+    pxData[pxPos] = pixelData[0];
+    pxData[pxPos + 1] = pixelData[1];
+    pxData[pxPos + 2] = pixelData[2];
+    pxData[pxPos + 3] = pixelData[3];
+  },
+];
+ 
+function bitRetriever(data, depth) {
+  let leftOver = [];
+  let i = 0;
+ 
+  function split() {
+    Iif (i === data.length) {
+      throw new Error("Ran out of data");
+    }
+    let byte = data[i];
+    i++;
+    let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1;
+    switch (depth) {
+      default:
+        throw new Error("unrecognised depth");
+      case 16:
+        byte2 = data[i];
+        i++;
+        leftOver.push((byte << 8) + byte2);
+        break;
+      case 4:
+        byte2 = byte & 0x0f;
+        byte1 = byte >> 4;
+        leftOver.push(byte1, byte2);
+        break;
+      case 2:
+        byte4 = byte & 3;
+        byte3 = (byte >> 2) & 3;
+        byte2 = (byte >> 4) & 3;
+        byte1 = (byte >> 6) & 3;
+        leftOver.push(byte1, byte2, byte3, byte4);
+        break;
+      case 1:
+        byte8 = byte & 1;
+        byte7 = (byte >> 1) & 1;
+        byte6 = (byte >> 2) & 1;
+        byte5 = (byte >> 3) & 1;
+        byte4 = (byte >> 4) & 1;
+        byte3 = (byte >> 5) & 1;
+        byte2 = (byte >> 6) & 1;
+        byte1 = (byte >> 7) & 1;
+        leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8);
+        break;
+    }
+  }
+ 
+  return {
+    get: function (count) {
+      while (leftOver.length < count) {
+        split();
+      }
+      let returner = leftOver.slice(0, count);
+      leftOver = leftOver.slice(count);
+      return returner;
+    },
+    resetAfterLine: function () {
+      leftOver.length = 0;
+    },
+    end: function () {
+      Iif (i !== data.length) {
+        throw new Error("extra data found");
+      }
+    },
+  };
+}
+ 
+function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) {
+  // eslint-disable-line max-params
+  let imageWidth = image.width;
+  let imageHeight = image.height;
+  let imagePass = image.index;
+  for (let y = 0; y < imageHeight; y++) {
+    for (let x = 0; x < imageWidth; x++) {
+      let pxPos = getPxPos(x, y, imagePass);
+      pixelBppMapper[bpp](pxData, data, pxPos, rawPos);
+      rawPos += bpp; //eslint-disable-line no-param-reassign
+    }
+  }
+  return rawPos;
+}
+ 
+function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) {
+  // eslint-disable-line max-params
+  let imageWidth = image.width;
+  let imageHeight = image.height;
+  let imagePass = image.index;
+  for (let y = 0; y < imageHeight; y++) {
+    for (let x = 0; x < imageWidth; x++) {
+      let pixelData = bits.get(bpp);
+      let pxPos = getPxPos(x, y, imagePass);
+      pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit);
+    }
+    bits.resetAfterLine();
+  }
+}
+ 
+exports.dataToBitMap = function (data, bitmapInfo) {
+  let width = bitmapInfo.width;
+  let height = bitmapInfo.height;
+  let depth = bitmapInfo.depth;
+  let bpp = bitmapInfo.bpp;
+  let interlace = bitmapInfo.interlace;
+  let bits;
+ 
+  if (depth !== 8) {
+    bits = bitRetriever(data, depth);
+  }
+  let pxData;
+  if (depth <= 8) {
+    pxData = Buffer.alloc(width * height * 4);
+  } else {
+    pxData = new Uint16Array(width * height * 4);
+  }
+  let maxBit = Math.pow(2, depth) - 1;
+  let rawPos = 0;
+  let images;
+  let getPxPos;
+ 
+  if (interlace) {
+    images = interlaceUtils.getImagePasses(width, height);
+    getPxPos = interlaceUtils.getInterlaceIterator(width, height);
+  } else {
+    let nonInterlacedPxPos = 0;
+    getPxPos = function () {
+      let returner = nonInterlacedPxPos;
+      nonInterlacedPxPos += 4;
+      return returner;
+    };
+    images = [{ width: width, height: height }];
+  }
+ 
+  for (let imageIndex = 0; imageIndex < images.length; imageIndex++) {
+    if (depth === 8) {
+      rawPos = mapImage8Bit(
+        images[imageIndex],
+        pxData,
+        getPxPos,
+        bpp,
+        data,
+        rawPos
+      );
+    } else {
+      mapImageCustomBit(
+        images[imageIndex],
+        pxData,
+        getPxPos,
+        bpp,
+        bits,
+        maxBit
+      );
+    }
+  }
+  if (depth === 8) {
+    Iif (rawPos !== data.length) {
+      throw new Error("extra data found");
+    }
+  } else {
+    bits.end();
+  }
+ 
+  return pxData;
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/bitpacker.js.html b/node_modules/pngjs/coverage/lcov-report/bitpacker.js.html new file mode 100644 index 0000000..50cca23 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/bitpacker.js.html @@ -0,0 +1,554 @@ + + + + + + Code coverage report for bitpacker.js + + + + + + + + + +
+
+

All files bitpacker.js

+
+ +
+ 11.36% + Statements + 10/88 +
+ + +
+ 6.12% + Branches + 3/49 +
+ + +
+ 66.67% + Functions + 2/3 +
+ + +
+ 11.63% + Lines + 10/86 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159  +  +1x +  +1x +  +325x +  +  +325x +325x +325x +325x +  +325x +  +  +325x +325x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  + 
"use strict";
+ 
+let constants = require("./constants");
+ 
+module.exports = function (dataIn, width, height, options) {
+  let outHasAlpha =
+    [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf(
+      options.colorType
+    ) !== -1;
+  Eif (options.colorType === options.inputColorType) {
+    let bigEndian = (function () {
+      let buffer = new ArrayBuffer(2);
+      new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
+      // Int16Array uses the platform's endianness.
+      return new Int16Array(buffer)[0] !== 256;
+    })();
+    // If no need to convert to grayscale and alpha is present/absent in both, take a fast route
+    Eif (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) {
+      return dataIn;
+    }
+  }
+ 
+  // map to a UInt16 array if data is 16bit, fix endianness below
+  let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer);
+ 
+  let maxValue = 255;
+  let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType];
+  if (inBpp === 4 && !options.inputHasAlpha) {
+    inBpp = 3;
+  }
+  let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType];
+  if (options.bitDepth === 16) {
+    maxValue = 65535;
+    outBpp *= 2;
+  }
+  let outData = Buffer.alloc(width * height * outBpp);
+ 
+  let inIndex = 0;
+  let outIndex = 0;
+ 
+  let bgColor = options.bgColor || {};
+  if (bgColor.red === undefined) {
+    bgColor.red = maxValue;
+  }
+  if (bgColor.green === undefined) {
+    bgColor.green = maxValue;
+  }
+  if (bgColor.blue === undefined) {
+    bgColor.blue = maxValue;
+  }
+ 
+  function getRGBA() {
+    let red;
+    let green;
+    let blue;
+    let alpha = maxValue;
+    switch (options.inputColorType) {
+      case constants.COLORTYPE_COLOR_ALPHA:
+        alpha = data[inIndex + 3];
+        red = data[inIndex];
+        green = data[inIndex + 1];
+        blue = data[inIndex + 2];
+        break;
+      case constants.COLORTYPE_COLOR:
+        red = data[inIndex];
+        green = data[inIndex + 1];
+        blue = data[inIndex + 2];
+        break;
+      case constants.COLORTYPE_ALPHA:
+        alpha = data[inIndex + 1];
+        red = data[inIndex];
+        green = red;
+        blue = red;
+        break;
+      case constants.COLORTYPE_GRAYSCALE:
+        red = data[inIndex];
+        green = red;
+        blue = red;
+        break;
+      default:
+        throw new Error(
+          "input color type:" +
+            options.inputColorType +
+            " is not supported at present"
+        );
+    }
+ 
+    if (options.inputHasAlpha) {
+      if (!outHasAlpha) {
+        alpha /= maxValue;
+        red = Math.min(
+          Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0),
+          maxValue
+        );
+        green = Math.min(
+          Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0),
+          maxValue
+        );
+        blue = Math.min(
+          Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0),
+          maxValue
+        );
+      }
+    }
+    return { red: red, green: green, blue: blue, alpha: alpha };
+  }
+ 
+  for (let y = 0; y < height; y++) {
+    for (let x = 0; x < width; x++) {
+      let rgba = getRGBA(data, inIndex);
+ 
+      switch (options.colorType) {
+        case constants.COLORTYPE_COLOR_ALPHA:
+        case constants.COLORTYPE_COLOR:
+          if (options.bitDepth === 8) {
+            outData[outIndex] = rgba.red;
+            outData[outIndex + 1] = rgba.green;
+            outData[outIndex + 2] = rgba.blue;
+            if (outHasAlpha) {
+              outData[outIndex + 3] = rgba.alpha;
+            }
+          } else {
+            outData.writeUInt16BE(rgba.red, outIndex);
+            outData.writeUInt16BE(rgba.green, outIndex + 2);
+            outData.writeUInt16BE(rgba.blue, outIndex + 4);
+            if (outHasAlpha) {
+              outData.writeUInt16BE(rgba.alpha, outIndex + 6);
+            }
+          }
+          break;
+        case constants.COLORTYPE_ALPHA:
+        case constants.COLORTYPE_GRAYSCALE: {
+          // Convert to grayscale and alpha
+          let grayscale = (rgba.red + rgba.green + rgba.blue) / 3;
+          if (options.bitDepth === 8) {
+            outData[outIndex] = grayscale;
+            if (outHasAlpha) {
+              outData[outIndex + 1] = rgba.alpha;
+            }
+          } else {
+            outData.writeUInt16BE(grayscale, outIndex);
+            if (outHasAlpha) {
+              outData.writeUInt16BE(rgba.alpha, outIndex + 2);
+            }
+          }
+          break;
+        }
+        default:
+          throw new Error("unrecognised color Type " + options.colorType);
+      }
+ 
+      inIndex += inBpp;
+      outIndex += outBpp;
+    }
+  }
+ 
+  return outData;
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/block-navigation.js b/node_modules/pngjs/coverage/lcov-report/block-navigation.js new file mode 100644 index 0000000..81d08c0 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/block-navigation.js @@ -0,0 +1,77 @@ +/* eslint-disable */ +var jumpToCode = (function init() { + // Classes of code we would like to highlight in the file view + var missingCoverageClasses = [".cbranch-no", ".cstat-no", ".fstat-no"]; + + // Elements to highlight in the file listing view + var fileListingElements = ["td.pct.low"]; + + // We don't want to select elements that are direct descendants of another match + var notSelector = ":not(" + missingCoverageClasses.join("):not(") + ") > "; // becomes `:not(a):not(b) > ` + + // Selecter that finds elements on the page to which we can jump + var selector = + fileListingElements.join(", ") + + ", " + + notSelector + + missingCoverageClasses.join(", " + notSelector); // becomes `:not(a):not(b) > a, :not(a):not(b) > b` + + // The NodeList of matching elements + var missingCoverageElements = document.querySelectorAll(selector); + + var currentIndex; + + function toggleClass(index) { + missingCoverageElements.item(currentIndex).classList.remove("highlighted"); + missingCoverageElements.item(index).classList.add("highlighted"); + } + + function makeCurrent(index) { + toggleClass(index); + currentIndex = index; + missingCoverageElements.item(index).scrollIntoView({ + behavior: "smooth", + block: "center", + inline: "center", + }); + } + + function goToPrevious() { + var nextIndex = 0; + if (typeof currentIndex !== "number" || currentIndex === 0) { + nextIndex = missingCoverageElements.length - 1; + } else if (missingCoverageElements.length > 1) { + nextIndex = currentIndex - 1; + } + + makeCurrent(nextIndex); + } + + function goToNext() { + var nextIndex = 0; + + if ( + typeof currentIndex === "number" && + currentIndex < missingCoverageElements.length - 1 + ) { + nextIndex = currentIndex + 1; + } + + makeCurrent(nextIndex); + } + + return function jump(event) { + switch (event.which) { + case 78: // n + case 74: // j + goToNext(); + break; + case 66: // b + case 75: // k + case 80: // p + goToPrevious(); + break; + } + }; +})(); +window.addEventListener("keydown", jumpToCode); diff --git a/node_modules/pngjs/coverage/lcov-report/chunkstream.js.html b/node_modules/pngjs/coverage/lcov-report/chunkstream.js.html new file mode 100644 index 0000000..552ffba --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/chunkstream.js.html @@ -0,0 +1,647 @@ + + + + + + Code coverage report for chunkstream.js + + + + + + + + + +
+
+

All files chunkstream.js

+
+ +
+ 90.11% + Statements + 82/91 +
+ + +
+ 81.4% + Branches + 35/43 +
+ + +
+ 100% + Functions + 10/10 +
+ + +
+ 90.11% + Lines + 82/91 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190  +  +1x +1x +  +1x +529x +  +529x +529x +  +529x +529x +  +529x +529x +  +1x +  +1x +13318x +  +  +  +  +  +13318x +  +13318x +  +  +13318x +  +  +  +  +  +  +  +  +1x +943x +  +  +  +  +  +943x +943x +  +  +  +  +943x +943x +  +943x +  +  +943x +346x +  +  +943x +  +  +1x +311x +  +  +  +311x +  +  +311x +  +  +  +  +311x +309x +  +2x +2x +  +  +  +1x +  +1x +311x +3x +  +  +311x +  +  +1x +327x +  +  +  +327x +327x +327x +  +327x +  +  +1x +  +741x +  +  +741x +  +  +741x +568x +568x +  +568x +  +  +173x +173x +  +173x +  +  +  +1x +12408x +  +12408x +12408x +12408x +  +  +12408x +12617x +12617x +  +12617x +12617x +  +  +12617x +11863x +  +  +  +  +12408x +532x +  +  +12408x +  +12408x +  +  +1x +14263x +  +14263x +15656x +  +  +15656x +741x +14915x +  +  +12408x +  +  +  +2507x +  +  +  +14263x +2x +  +  +  +  +  + 
"use strict";
+ 
+let util = require("util");
+let Stream = require("stream");
+ 
+let ChunkStream = (module.exports = function () {
+  Stream.call(this);
+ 
+  this._buffers = [];
+  this._buffered = 0;
+ 
+  this._reads = [];
+  this._paused = false;
+ 
+  this._encoding = "utf8";
+  this.writable = true;
+});
+util.inherits(ChunkStream, Stream);
+ 
+ChunkStream.prototype.read = function (length, callback) {
+  this._reads.push({
+    length: Math.abs(length), // if length < 0 then at most this length
+    allowLess: length < 0,
+    func: callback,
+  });
+ 
+  process.nextTick(
+    function () {
+      this._process();
+ 
+      // its paused and there is not enought data then ask for more
+      Iif (this._paused && this._reads.length > 0) {
+        this._paused = false;
+ 
+        this.emit("drain");
+      }
+    }.bind(this)
+  );
+};
+ 
+ChunkStream.prototype.write = function (data, encoding) {
+  Iif (!this.writable) {
+    this.emit("error", new Error("Stream not writable"));
+    return false;
+  }
+ 
+  let dataBuffer;
+  Eif (Buffer.isBuffer(data)) {
+    dataBuffer = data;
+  } else {
+    dataBuffer = Buffer.from(data, encoding || this._encoding);
+  }
+ 
+  this._buffers.push(dataBuffer);
+  this._buffered += dataBuffer.length;
+ 
+  this._process();
+ 
+  // ok if there are no more read requests
+  if (this._reads && this._reads.length === 0) {
+    this._paused = true;
+  }
+ 
+  return this.writable && !this._paused;
+};
+ 
+ChunkStream.prototype.end = function (data, encoding) {
+  Iif (data) {
+    this.write(data, encoding);
+  }
+ 
+  this.writable = false;
+ 
+  // already destroyed
+  Iif (!this._buffers) {
+    return;
+  }
+ 
+  // enqueue or handle end
+  if (this._buffers.length === 0) {
+    this._end();
+  } else {
+    this._buffers.push(null);
+    this._process();
+  }
+};
+ 
+ChunkStream.prototype.destroySoon = ChunkStream.prototype.end;
+ 
+ChunkStream.prototype._end = function () {
+  if (this._reads.length > 0) {
+    this.emit("error", new Error("Unexpected end of input"));
+  }
+ 
+  this.destroy();
+};
+ 
+ChunkStream.prototype.destroy = function () {
+  Iif (!this._buffers) {
+    return;
+  }
+ 
+  this.writable = false;
+  this._reads = null;
+  this._buffers = null;
+ 
+  this.emit("close");
+};
+ 
+ChunkStream.prototype._processReadAllowingLess = function (read) {
+  // ok there is any data so that we can satisfy this request
+  this._reads.shift(); // == read
+ 
+  // first we need to peek into first buffer
+  let smallerBuf = this._buffers[0];
+ 
+  // ok there is more data than we need
+  if (smallerBuf.length > read.length) {
+    this._buffered -= read.length;
+    this._buffers[0] = smallerBuf.slice(read.length);
+ 
+    read.func.call(this, smallerBuf.slice(0, read.length));
+  } else {
+    // ok this is less than maximum length so use it all
+    this._buffered -= smallerBuf.length;
+    this._buffers.shift(); // == smallerBuf
+ 
+    read.func.call(this, smallerBuf);
+  }
+};
+ 
+ChunkStream.prototype._processRead = function (read) {
+  this._reads.shift(); // == read
+ 
+  let pos = 0;
+  let count = 0;
+  let data = Buffer.alloc(read.length);
+ 
+  // create buffer for all data
+  while (pos < read.length) {
+    let buf = this._buffers[count++];
+    let len = Math.min(buf.length, read.length - pos);
+ 
+    buf.copy(data, pos, 0, len);
+    pos += len;
+ 
+    // last buffer wasn't used all so just slice it and leave
+    if (len !== buf.length) {
+      this._buffers[--count] = buf.slice(len);
+    }
+  }
+ 
+  // remove all used buffers
+  if (count > 0) {
+    this._buffers.splice(0, count);
+  }
+ 
+  this._buffered -= read.length;
+ 
+  read.func.call(this, data);
+};
+ 
+ChunkStream.prototype._process = function () {
+  try {
+    // as long as there is any data and read requests
+    while (this._buffered > 0 && this._reads && this._reads.length > 0) {
+      let read = this._reads[0];
+ 
+      // read any data (but no more than length)
+      if (read.allowLess) {
+        this._processReadAllowingLess(read);
+      } else if (this._buffered >= read.length) {
+        // ok we can meet some expectations
+ 
+        this._processRead(read);
+      } else {
+        // not enought data to satisfy first request in queue
+        // so we need to wait for more
+        break;
+      }
+    }
+ 
+    if (this._buffers && !this.writable) {
+      this._end();
+    }
+  } catch (ex) {
+    this.emit("error", ex);
+  }
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/constants.js.html b/node_modules/pngjs/coverage/lcov-report/constants.js.html new file mode 100644 index 0000000..a6edd80 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/constants.js.html @@ -0,0 +1,176 @@ + + + + + + Code coverage report for constants.js + + + + + + + + + +
+
+

All files constants.js

+
+ +
+ 100% + Statements + 1/1 +
+ + +
+ 100% + Branches + 0/0 +
+ + +
+ 100% + Functions + 0/0 +
+ + +
+ 100% + Lines + 1/1 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  + 
"use strict";
+ 
+module.exports = {
+  PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
+ 
+  TYPE_IHDR: 0x49484452,
+  TYPE_IEND: 0x49454e44,
+  TYPE_IDAT: 0x49444154,
+  TYPE_PLTE: 0x504c5445,
+  TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase
+  TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase
+ 
+  // color-type bits
+  COLORTYPE_GRAYSCALE: 0,
+  COLORTYPE_PALETTE: 1,
+  COLORTYPE_COLOR: 2,
+  COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha
+ 
+  // color-type combinations
+  COLORTYPE_PALETTE_COLOR: 3,
+  COLORTYPE_COLOR_ALPHA: 6,
+ 
+  COLORTYPE_TO_BPP_MAP: {
+    0: 1,
+    2: 3,
+    3: 1,
+    4: 2,
+    6: 4,
+  },
+ 
+  GAMMA_DIVISION: 100000,
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/crc.js.html b/node_modules/pngjs/coverage/lcov-report/crc.js.html new file mode 100644 index 0000000..53fc72a --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/crc.js.html @@ -0,0 +1,200 @@ + + + + + + Code coverage report for crc.js + + + + + + + + + +
+
+

All files crc.js

+
+ +
+ 100% + Statements + 26/26 +
+ + +
+ 100% + Branches + 2/2 +
+ + +
+ 100% + Functions + 5/5 +
+ + +
+ 100% + Lines + 22/22 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41  +  +1x +  +1x +1x +256x +256x +2048x +1024x +  +1024x +  +  +256x +  +  +  +1x +2461x +  +  +1x +4839x +823519x +  +4839x +  +  +1x +2195x +  +  +1x +1592x +1592x +305287x +  +1592x +  + 
"use strict";
+ 
+let crcTable = [];
+ 
+(function () {
+  for (let i = 0; i < 256; i++) {
+    let currentCrc = i;
+    for (let j = 0; j < 8; j++) {
+      if (currentCrc & 1) {
+        currentCrc = 0xedb88320 ^ (currentCrc >>> 1);
+      } else {
+        currentCrc = currentCrc >>> 1;
+      }
+    }
+    crcTable[i] = currentCrc;
+  }
+})();
+ 
+let CrcCalculator = (module.exports = function () {
+  this._crc = -1;
+});
+ 
+CrcCalculator.prototype.write = function (data) {
+  for (let i = 0; i < data.length; i++) {
+    this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8);
+  }
+  return true;
+};
+ 
+CrcCalculator.prototype.crc32 = function () {
+  return this._crc ^ -1;
+};
+ 
+CrcCalculator.crc32 = function (buf) {
+  let crc = -1;
+  for (let i = 0; i < buf.length; i++) {
+    crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
+  }
+  return crc ^ -1;
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/favicon.png b/node_modules/pngjs/coverage/lcov-report/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..6691817834a957c938e7f09640a37a645fb31457 GIT binary patch literal 540 zcmV+%0^|LOP)wSzy{h>9elhJ=8GnBQmf?)AI(^#wDA_`!QTxaXXE&bjxo zTGCc%V|W`}Lwz0rDO*qBbGY-M@aNENIZ1rK?nOAibaC*vb%CF;I_~lkJawax%_+1J zLn(#pv_v{f0`v`Cfp6()7MB(>IoTAiQdKxgxX?VyV&KVZ7b$vn<8|Z<9$35C+G_8SH0x6Y(xB&~bmn%r}ceRwbc0000 + + + + Code coverage report for filter-pack.js + + + + + + + + + +
+
+

All files filter-pack.js

+
+ +
+ 95.83% + Statements + 92/96 +
+ + +
+ 81.82% + Branches + 36/44 +
+ + +
+ 100% + Functions + 11/11 +
+ + +
+ 95.24% + Lines + 80/84 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172  +  +1x +  +  +44x +5136x +  +  +  +  +10490x +10490x +  +10490x +2776736x +  +10490x +  +  +  +637x +107032x +107032x +  +107032x +  +  +  +  +10490x +10490x +2776736x +2776736x +  +2776736x +  +  +10490x +  +  +  +2670x +581344x +581344x +  +581344x +  +  +  +  +10490x +10490x +10490x +2776736x +2776736x +  +2776736x +  +  +10490x +  +  +  +208x +204096x +204096x +204096x +  +204096x +  +  +  +  +10490x +10490x +2776736x +2776736x +2776736x +  +2776736x +  +  +10490x +  +  +  +6931x +1879128x +1879128x +  +1879128x +1879128x +  +1879128x +  +  +  +  +10490x +10490x +2776736x +2776736x +  +2776736x +2776736x +  +2776736x +  +  +10490x +  +  +1x +  +  +  +  +  +  +  +1x +  +  +  +  +  +  +  +1x +  +325x +325x +  +  +  +  +  +  +325x +  +  +325x +325x +325x +325x +  +325x +  +325x +10490x +  +10490x +  +10490x +52450x +52450x +35370x +35370x +  +  +  +  +10490x +10490x +10490x +10490x +10490x +  +325x +  + 
"use strict";
+ 
+let paethPredictor = require("./paeth-predictor");
+ 
+function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) {
+  for (let x = 0; x < byteWidth; x++) {
+    rawData[rawPos + x] = pxData[pxPos + x];
+  }
+}
+ 
+function filterSumNone(pxData, pxPos, byteWidth) {
+  let sum = 0;
+  let length = pxPos + byteWidth;
+ 
+  for (let i = pxPos; i < length; i++) {
+    sum += Math.abs(pxData[i]);
+  }
+  return sum;
+}
+ 
+function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
+  for (let x = 0; x < byteWidth; x++) {
+    let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+    let val = pxData[pxPos + x] - left;
+ 
+    rawData[rawPos + x] = val;
+  }
+}
+ 
+function filterSumSub(pxData, pxPos, byteWidth, bpp) {
+  let sum = 0;
+  for (let x = 0; x < byteWidth; x++) {
+    let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+    let val = pxData[pxPos + x] - left;
+ 
+    sum += Math.abs(val);
+  }
+ 
+  return sum;
+}
+ 
+function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) {
+  for (let x = 0; x < byteWidth; x++) {
+    let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+    let val = pxData[pxPos + x] - up;
+ 
+    rawData[rawPos + x] = val;
+  }
+}
+ 
+function filterSumUp(pxData, pxPos, byteWidth) {
+  let sum = 0;
+  let length = pxPos + byteWidth;
+  for (let x = pxPos; x < length; x++) {
+    let up = pxPos > 0 ? pxData[x - byteWidth] : 0;
+    let val = pxData[x] - up;
+ 
+    sum += Math.abs(val);
+  }
+ 
+  return sum;
+}
+ 
+function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
+  for (let x = 0; x < byteWidth; x++) {
+    let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+    let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+    let val = pxData[pxPos + x] - ((left + up) >> 1);
+ 
+    rawData[rawPos + x] = val;
+  }
+}
+ 
+function filterSumAvg(pxData, pxPos, byteWidth, bpp) {
+  let sum = 0;
+  for (let x = 0; x < byteWidth; x++) {
+    let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+    let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+    let val = pxData[pxPos + x] - ((left + up) >> 1);
+ 
+    sum += Math.abs(val);
+  }
+ 
+  return sum;
+}
+ 
+function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) {
+  for (let x = 0; x < byteWidth; x++) {
+    let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+    let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+    let upleft =
+      pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
+    let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
+ 
+    rawData[rawPos + x] = val;
+  }
+}
+ 
+function filterSumPaeth(pxData, pxPos, byteWidth, bpp) {
+  let sum = 0;
+  for (let x = 0; x < byteWidth; x++) {
+    let left = x >= bpp ? pxData[pxPos + x - bpp] : 0;
+    let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0;
+    let upleft =
+      pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0;
+    let val = pxData[pxPos + x] - paethPredictor(left, up, upleft);
+ 
+    sum += Math.abs(val);
+  }
+ 
+  return sum;
+}
+ 
+let filters = {
+  0: filterNone,
+  1: filterSub,
+  2: filterUp,
+  3: filterAvg,
+  4: filterPaeth,
+};
+ 
+let filterSums = {
+  0: filterSumNone,
+  1: filterSumSub,
+  2: filterSumUp,
+  3: filterSumAvg,
+  4: filterSumPaeth,
+};
+ 
+module.exports = function (pxData, width, height, options, bpp) {
+  let filterTypes;
+  Eif (!("filterType" in options) || options.filterType === -1) {
+    filterTypes = [0, 1, 2, 3, 4];
+  } else if (typeof options.filterType === "number") {
+    filterTypes = [options.filterType];
+  } else {
+    throw new Error("unrecognised filter types");
+  }
+ 
+  Iif (options.bitDepth === 16) {
+    bpp *= 2;
+  }
+  let byteWidth = width * bpp;
+  let rawPos = 0;
+  let pxPos = 0;
+  let rawData = Buffer.alloc((byteWidth + 1) * height);
+ 
+  let sel = filterTypes[0];
+ 
+  for (let y = 0; y < height; y++) {
+    Eif (filterTypes.length > 1) {
+      // find best filter for this line (with lowest sum of values)
+      let min = Infinity;
+ 
+      for (let i = 0; i < filterTypes.length; i++) {
+        let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp);
+        if (sum < min) {
+          sel = filterTypes[i];
+          min = sum;
+        }
+      }
+    }
+ 
+    rawData[rawPos] = sel;
+    rawPos++;
+    filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp);
+    rawPos += byteWidth;
+    pxPos += byteWidth;
+  }
+  return rawData;
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/filter-parse-async.js.html b/node_modules/pngjs/coverage/lcov-report/filter-parse-async.js.html new file mode 100644 index 0000000..06f25f1 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/filter-parse-async.js.html @@ -0,0 +1,152 @@ + + + + + + Code coverage report for filter-parse-async.js + + + + + + + + + +
+
+

All files filter-parse-async.js

+
+ +
+ 100% + Statements + 12/12 +
+ + +
+ 100% + Branches + 0/0 +
+ + +
+ 100% + Functions + 3/3 +
+ + +
+ 100% + Lines + 12/12 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25  +  +1x +1x +1x +  +1x +176x +  +176x +176x +176x +  +  +9057x +  +  +173x +  +  +  +176x +  +1x + 
"use strict";
+ 
+let util = require("util");
+let ChunkStream = require("./chunkstream");
+let Filter = require("./filter-parse");
+ 
+let FilterAsync = (module.exports = function (bitmapInfo) {
+  ChunkStream.call(this);
+ 
+  let buffers = [];
+  let that = this;
+  this._filter = new Filter(bitmapInfo, {
+    read: this.read.bind(this),
+    write: function (buffer) {
+      buffers.push(buffer);
+    },
+    complete: function () {
+      that.emit("complete", Buffer.concat(buffers));
+    },
+  });
+ 
+  this._filter.start();
+});
+util.inherits(FilterAsync, ChunkStream);
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/filter-parse-sync.js.html b/node_modules/pngjs/coverage/lcov-report/filter-parse-sync.js.html new file mode 100644 index 0000000..df91a35 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/filter-parse-sync.js.html @@ -0,0 +1,143 @@ + + + + + + Code coverage report for filter-parse-sync.js + + + + + + + + + +
+
+

All files filter-parse-sync.js

+
+ +
+ 100% + Statements + 10/10 +
+ + +
+ 100% + Branches + 0/0 +
+ + +
+ 100% + Functions + 3/3 +
+ + +
+ 100% + Lines + 10/10 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22  +  +1x +1x +  +1x +162x +162x +162x +  +  +6337x +  +  +  +  +162x +162x +  +162x +  + 
"use strict";
+ 
+let SyncReader = require("./sync-reader");
+let Filter = require("./filter-parse");
+ 
+exports.process = function (inBuffer, bitmapInfo) {
+  let outBuffers = [];
+  let reader = new SyncReader(inBuffer);
+  let filter = new Filter(bitmapInfo, {
+    read: reader.read.bind(reader),
+    write: function (bufferPart) {
+      outBuffers.push(bufferPart);
+    },
+    complete: function () {},
+  });
+ 
+  filter.start();
+  reader.process();
+ 
+  return Buffer.concat(outBuffers);
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/filter-parse.js.html b/node_modules/pngjs/coverage/lcov-report/filter-parse.js.html new file mode 100644 index 0000000..945757c --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/filter-parse.js.html @@ -0,0 +1,611 @@ + + + + + + Code coverage report for filter-parse.js + + + + + + + + + +
+
+

All files filter-parse.js

+
+ +
+ 98.96% + Statements + 95/96 +
+ + +
+ 97.14% + Branches + 34/35 +
+ + +
+ 100% + Functions + 8/8 +
+ + +
+ 98.9% + Lines + 90/91 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178  +  +1x +1x +  +  +742x +742x +531x +  +742x +  +  +1x +338x +338x +338x +338x +338x +  +338x +338x +338x +  +338x +338x +338x +72x +72x +476x +  +  +  +  +  +  +266x +  +  +  +  +  +  +  +  +  +  +338x +127x +211x +66x +  +145x +  +  +  +1x +338x +  +  +  +  +  +1x +  +  +  +  +1939x +1939x +  +1939x +3563504x +3563504x +3563504x +  +  +  +1x +  +  +  +  +800x +  +800x +330256x +330256x +330256x +  +  +  +1x +  +  +  +  +172x +172x +172x +  +172x +9952x +9952x +9952x +9952x +9952x +  +  +  +1x +  +  +  +  +4165x +4165x +4165x +  +4165x +1152544x +1152544x +1152544x +1152544x +1152544x +1152544x +  +  +  +1x +15394x +  +15394x +15394x +  +15394x +8318x +  +7076x +  +7076x +  +1939x +1939x +  +800x +800x +  +172x +172x +  +4165x +4165x +  +  +  +  +  +15394x +  +15394x +15394x +739x +739x +739x +  +14655x +  +  +15394x +  +15059x +  +335x +335x +  +  + 
"use strict";
+ 
+let interlaceUtils = require("./interlace");
+let paethPredictor = require("./paeth-predictor");
+ 
+function getByteWidth(width, bpp, depth) {
+  let byteWidth = width * bpp;
+  if (depth !== 8) {
+    byteWidth = Math.ceil(byteWidth / (8 / depth));
+  }
+  return byteWidth;
+}
+ 
+let Filter = (module.exports = function (bitmapInfo, dependencies) {
+  let width = bitmapInfo.width;
+  let height = bitmapInfo.height;
+  let interlace = bitmapInfo.interlace;
+  let bpp = bitmapInfo.bpp;
+  let depth = bitmapInfo.depth;
+ 
+  this.read = dependencies.read;
+  this.write = dependencies.write;
+  this.complete = dependencies.complete;
+ 
+  this._imageIndex = 0;
+  this._images = [];
+  if (interlace) {
+    let passes = interlaceUtils.getImagePasses(width, height);
+    for (let i = 0; i < passes.length; i++) {
+      this._images.push({
+        byteWidth: getByteWidth(passes[i].width, bpp, depth),
+        height: passes[i].height,
+        lineIndex: 0,
+      });
+    }
+  } else {
+    this._images.push({
+      byteWidth: getByteWidth(width, bpp, depth),
+      height: height,
+      lineIndex: 0,
+    });
+  }
+ 
+  // when filtering the line we look at the pixel to the left
+  // the spec also says it is done on a byte level regardless of the number of pixels
+  // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back
+  // a pixel rather than just a different byte part. However if we are sub byte, we ignore.
+  if (depth === 8) {
+    this._xComparison = bpp;
+  } else if (depth === 16) {
+    this._xComparison = bpp * 2;
+  } else {
+    this._xComparison = 1;
+  }
+});
+ 
+Filter.prototype.start = function () {
+  this.read(
+    this._images[this._imageIndex].byteWidth + 1,
+    this._reverseFilterLine.bind(this)
+  );
+};
+ 
+Filter.prototype._unFilterType1 = function (
+  rawData,
+  unfilteredLine,
+  byteWidth
+) {
+  let xComparison = this._xComparison;
+  let xBiggerThan = xComparison - 1;
+ 
+  for (let x = 0; x < byteWidth; x++) {
+    let rawByte = rawData[1 + x];
+    let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
+    unfilteredLine[x] = rawByte + f1Left;
+  }
+};
+ 
+Filter.prototype._unFilterType2 = function (
+  rawData,
+  unfilteredLine,
+  byteWidth
+) {
+  let lastLine = this._lastLine;
+ 
+  for (let x = 0; x < byteWidth; x++) {
+    let rawByte = rawData[1 + x];
+    let f2Up = lastLine ? lastLine[x] : 0;
+    unfilteredLine[x] = rawByte + f2Up;
+  }
+};
+ 
+Filter.prototype._unFilterType3 = function (
+  rawData,
+  unfilteredLine,
+  byteWidth
+) {
+  let xComparison = this._xComparison;
+  let xBiggerThan = xComparison - 1;
+  let lastLine = this._lastLine;
+ 
+  for (let x = 0; x < byteWidth; x++) {
+    let rawByte = rawData[1 + x];
+    let f3Up = lastLine ? lastLine[x] : 0;
+    let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
+    let f3Add = Math.floor((f3Left + f3Up) / 2);
+    unfilteredLine[x] = rawByte + f3Add;
+  }
+};
+ 
+Filter.prototype._unFilterType4 = function (
+  rawData,
+  unfilteredLine,
+  byteWidth
+) {
+  let xComparison = this._xComparison;
+  let xBiggerThan = xComparison - 1;
+  let lastLine = this._lastLine;
+ 
+  for (let x = 0; x < byteWidth; x++) {
+    let rawByte = rawData[1 + x];
+    let f4Up = lastLine ? lastLine[x] : 0;
+    let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0;
+    let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0;
+    let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft);
+    unfilteredLine[x] = rawByte + f4Add;
+  }
+};
+ 
+Filter.prototype._reverseFilterLine = function (rawData) {
+  let filter = rawData[0];
+  let unfilteredLine;
+  let currentImage = this._images[this._imageIndex];
+  let byteWidth = currentImage.byteWidth;
+ 
+  if (filter === 0) {
+    unfilteredLine = rawData.slice(1, byteWidth + 1);
+  } else {
+    unfilteredLine = Buffer.alloc(byteWidth);
+ 
+    switch (filter) {
+      case 1:
+        this._unFilterType1(rawData, unfilteredLine, byteWidth);
+        break;
+      case 2:
+        this._unFilterType2(rawData, unfilteredLine, byteWidth);
+        break;
+      case 3:
+        this._unFilterType3(rawData, unfilteredLine, byteWidth);
+        break;
+      case 4:
+        this._unFilterType4(rawData, unfilteredLine, byteWidth);
+        break;
+      default:
+        throw new Error("Unrecognised filter type - " + filter);
+    }
+  }
+ 
+  this.write(unfilteredLine);
+ 
+  currentImage.lineIndex++;
+  if (currentImage.lineIndex >= currentImage.height) {
+    this._lastLine = null;
+    this._imageIndex++;
+    currentImage = this._images[this._imageIndex];
+  } else {
+    this._lastLine = unfilteredLine;
+  }
+ 
+  if (currentImage) {
+    // read, using the byte width that may be from the new current image
+    this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this));
+  } else {
+    this._lastLine = null;
+    this.complete();
+  }
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/format-normaliser.js.html b/node_modules/pngjs/coverage/lcov-report/format-normaliser.js.html new file mode 100644 index 0000000..c61afcf --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/format-normaliser.js.html @@ -0,0 +1,359 @@ + + + + + + Code coverage report for format-normaliser.js + + + + + + + + + +
+
+

All files format-normaliser.js

+
+ +
+ 98.21% + Statements + 55/56 +
+ + +
+ 95.24% + Branches + 20/21 +
+ + +
+ 100% + Functions + 4/4 +
+ + +
+ 97.87% + Lines + 46/47 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94  +  +  +131x +  +131x +4912x +1418436x +  +1418436x +  +  +  +1418436x +5673744x +  +1418436x +  +  +  +  +  +12x +12x +384x +12288x +  +12288x +6144x +2762x +  +6144x +  +  +  +  +2718x +  +12288x +5480x +21920x +  +  +12288x +  +  +  +  +  +106x +106x +106x +  +106x +3392x +108544x +434176x +  +  +  +108544x +  +  +  +  +1x +335x +335x +335x +335x +335x +335x +  +335x +  +335x +  +131x +  +204x +12x +  +  +204x +  +106x +66x +  +106x +  +  +335x +  + 
"use strict";
+ 
+function dePalette(indata, outdata, width, height, palette) {
+  let pxPos = 0;
+  // use values from palette
+  for (let y = 0; y < height; y++) {
+    for (let x = 0; x < width; x++) {
+      let color = palette[indata[pxPos]];
+ 
+      Iif (!color) {
+        throw new Error("index " + indata[pxPos] + " not in palette");
+      }
+ 
+      for (let i = 0; i < 4; i++) {
+        outdata[pxPos + i] = color[i];
+      }
+      pxPos += 4;
+    }
+  }
+}
+ 
+function replaceTransparentColor(indata, outdata, width, height, transColor) {
+  let pxPos = 0;
+  for (let y = 0; y < height; y++) {
+    for (let x = 0; x < width; x++) {
+      let makeTrans = false;
+ 
+      if (transColor.length === 1) {
+        if (transColor[0] === indata[pxPos]) {
+          makeTrans = true;
+        }
+      } else if (
+        transColor[0] === indata[pxPos] &&
+        transColor[1] === indata[pxPos + 1] &&
+        transColor[2] === indata[pxPos + 2]
+      ) {
+        makeTrans = true;
+      }
+      if (makeTrans) {
+        for (let i = 0; i < 4; i++) {
+          outdata[pxPos + i] = 0;
+        }
+      }
+      pxPos += 4;
+    }
+  }
+}
+ 
+function scaleDepth(indata, outdata, width, height, depth) {
+  let maxOutSample = 255;
+  let maxInSample = Math.pow(2, depth) - 1;
+  let pxPos = 0;
+ 
+  for (let y = 0; y < height; y++) {
+    for (let x = 0; x < width; x++) {
+      for (let i = 0; i < 4; i++) {
+        outdata[pxPos + i] = Math.floor(
+          (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5
+        );
+      }
+      pxPos += 4;
+    }
+  }
+}
+ 
+module.exports = function (indata, imageData) {
+  let depth = imageData.depth;
+  let width = imageData.width;
+  let height = imageData.height;
+  let colorType = imageData.colorType;
+  let transColor = imageData.transColor;
+  let palette = imageData.palette;
+ 
+  let outdata = indata; // only different for 16 bits
+ 
+  if (colorType === 3) {
+    // paletted
+    dePalette(indata, outdata, width, height, palette);
+  } else {
+    if (transColor) {
+      replaceTransparentColor(indata, outdata, width, height, transColor);
+    }
+    // if it needs scaling
+    if (depth !== 8) {
+      // if we need to change the buffer size
+      if (depth === 16) {
+        outdata = Buffer.alloc(width * height * 4);
+      }
+      scaleDepth(indata, outdata, width, height, depth);
+    }
+  }
+  return outdata;
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/index.html b/node_modules/pngjs/coverage/lcov-report/index.html new file mode 100644 index 0000000..51ecafd --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/index.html @@ -0,0 +1,426 @@ + + + + + + Code coverage report for All files + + + + + + + + + +
+
+

All files

+
+ +
+ 82.72% + Statements + 1034/1250 +
+ + +
+ 67.59% + Branches + 317/469 +
+ + +
+ 90.26% + Functions + 139/154 +
+ + +
+ 82.53% + Lines + 992/1202 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FileStatementsBranchesFunctionsLines
bitmapper.js +
+
94.37%134/14272.41%21/2989.47%17/1994.16%129/137
bitpacker.js +
+
11.36%10/886.12%3/4966.67%2/311.63%10/86
chunkstream.js +
+
90.11%82/9181.4%35/43100%10/1090.11%82/91
constants.js +
+
100%1/1100%0/0100%0/0100%1/1
crc.js +
+
100%26/26100%2/2100%5/5100%22/22
filter-pack.js +
+
95.83%92/9681.82%36/44100%11/1195.24%80/84
filter-parse-async.js +
+
100%12/12100%0/0100%3/3100%12/12
filter-parse-sync.js +
+
100%10/10100%0/0100%3/3100%10/10
filter-parse.js +
+
98.96%95/9697.14%34/35100%8/898.9%90/91
format-normaliser.js +
+
98.21%55/5695.24%20/21100%4/497.87%46/47
interlace.js +
+
100%32/32100%8/8100%3/3100%29/29
packer-async.js +
+
100%24/2475%3/4100%4/4100%24/24
packer-sync.js +
+
25%6/248.33%1/120%0/125%6/24
packer.js +
+
94.74%54/5767.86%19/28100%9/994.74%54/57
paeth-predictor.js +
+
100%10/10100%6/6100%1/1100%10/10
parser-async.js +
+
88.75%71/8072.73%16/2284.62%11/1388.75%71/80
parser-sync.js +
+
93.33%42/4578.57%11/14100%8/893.33%42/45
parser.js +
+
90.57%144/15985.45%47/55100%20/2090.32%140/155
png-sync.js +
+
83.33%5/6100%2/250%1/283.33%5/6
png.js +
+
54.17%52/9641.18%14/3456.25%9/1656.52%52/92
sync-inflate.js +
+
75.31%61/8162%31/5087.5%7/875.31%61/81
sync-reader.js +
+
88.89%16/1872.73%8/11100%3/388.89%16/18
+
+
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/interlace.js.html b/node_modules/pngjs/coverage/lcov-report/interlace.js.html new file mode 100644 index 0000000..d67b087 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/interlace.js.html @@ -0,0 +1,365 @@ + + + + + + Code coverage report for interlace.js + + + + + + + + + +
+
+

All files interlace.js

+
+ +
+ 100% + Statements + 32/32 +
+ + +
+ 100% + Branches + 8/8 +
+ + +
+ 100% + Functions + 3/3 +
+ + +
+ 100% + Lines + 29/29 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +144x +144x +144x +144x +144x +144x +1008x +1008x +1008x +1008x +1556x +672x +  +884x +  +  +1008x +1360x +552x +  +808x +  +  +1008x +952x +  +  +144x +  +  +1x +72x +324850x +  +324850x +  +324850x +  +324850x +  +324850x +  +  + 
"use strict";
+ 
+// Adam 7
+//   0 1 2 3 4 5 6 7
+// 0 x 6 4 6 x 6 4 6
+// 1 7 7 7 7 7 7 7 7
+// 2 5 6 5 6 5 6 5 6
+// 3 7 7 7 7 7 7 7 7
+// 4 3 6 4 6 3 6 4 6
+// 5 7 7 7 7 7 7 7 7
+// 6 5 6 5 6 5 6 5 6
+// 7 7 7 7 7 7 7 7 7
+ 
+let imagePasses = [
+  {
+    // pass 1 - 1px
+    x: [0],
+    y: [0],
+  },
+  {
+    // pass 2 - 1px
+    x: [4],
+    y: [0],
+  },
+  {
+    // pass 3 - 2px
+    x: [0, 4],
+    y: [4],
+  },
+  {
+    // pass 4 - 4px
+    x: [2, 6],
+    y: [0, 4],
+  },
+  {
+    // pass 5 - 8px
+    x: [0, 2, 4, 6],
+    y: [2, 6],
+  },
+  {
+    // pass 6 - 16px
+    x: [1, 3, 5, 7],
+    y: [0, 2, 4, 6],
+  },
+  {
+    // pass 7 - 32px
+    x: [0, 1, 2, 3, 4, 5, 6, 7],
+    y: [1, 3, 5, 7],
+  },
+];
+ 
+exports.getImagePasses = function (width, height) {
+  let images = [];
+  let xLeftOver = width % 8;
+  let yLeftOver = height % 8;
+  let xRepeats = (width - xLeftOver) / 8;
+  let yRepeats = (height - yLeftOver) / 8;
+  for (let i = 0; i < imagePasses.length; i++) {
+    let pass = imagePasses[i];
+    let passWidth = xRepeats * pass.x.length;
+    let passHeight = yRepeats * pass.y.length;
+    for (let j = 0; j < pass.x.length; j++) {
+      if (pass.x[j] < xLeftOver) {
+        passWidth++;
+      } else {
+        break;
+      }
+    }
+    for (let j = 0; j < pass.y.length; j++) {
+      if (pass.y[j] < yLeftOver) {
+        passHeight++;
+      } else {
+        break;
+      }
+    }
+    if (passWidth > 0 && passHeight > 0) {
+      images.push({ width: passWidth, height: passHeight, index: i });
+    }
+  }
+  return images;
+};
+ 
+exports.getInterlaceIterator = function (width) {
+  return function (x, y, pass) {
+    let outerXLeftOver = x % imagePasses[pass].x.length;
+    let outerX =
+      ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 +
+      imagePasses[pass].x[outerXLeftOver];
+    let outerYLeftOver = y % imagePasses[pass].y.length;
+    let outerY =
+      ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 +
+      imagePasses[pass].y[outerYLeftOver];
+    return outerX * 4 + outerY * width * 4;
+  };
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/packer-async.js.html b/node_modules/pngjs/coverage/lcov-report/packer-async.js.html new file mode 100644 index 0000000..55365c7 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/packer-async.js.html @@ -0,0 +1,230 @@ + + + + + + Code coverage report for packer-async.js + + + + + + + + + +
+
+

All files packer-async.js

+
+ +
+ 100% + Statements + 24/24 +
+ + +
+ 75% + Branches + 3/4 +
+ + +
+ 100% + Functions + 4/4 +
+ + +
+ 100% + Lines + 24/24 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51  +  +1x +1x +1x +1x +  +1x +353x +  +353x +  +353x +353x +  +353x +  +1x +  +1x +  +325x +325x +  +325x +290x +  +  +325x +  +  +325x +  +325x +  +  +652x +  +  +  +325x +  +  +325x +325x +  +  +  +325x +  + 
"use strict";
+ 
+let util = require("util");
+let Stream = require("stream");
+let constants = require("./constants");
+let Packer = require("./packer");
+ 
+let PackerAsync = (module.exports = function (opt) {
+  Stream.call(this);
+ 
+  let options = opt || {};
+ 
+  this._packer = new Packer(options);
+  this._deflate = this._packer.createDeflate();
+ 
+  this.readable = true;
+});
+util.inherits(PackerAsync, Stream);
+ 
+PackerAsync.prototype.pack = function (data, width, height, gamma) {
+  // Signature
+  this.emit("data", Buffer.from(constants.PNG_SIGNATURE));
+  this.emit("data", this._packer.packIHDR(width, height));
+ 
+  if (gamma) {
+    this.emit("data", this._packer.packGAMA(gamma));
+  }
+ 
+  let filteredData = this._packer.filterData(data, width, height);
+ 
+  // compress it
+  this._deflate.on("error", this.emit.bind(this, "error"));
+ 
+  this._deflate.on(
+    "data",
+    function (compressedData) {
+      this.emit("data", this._packer.packIDAT(compressedData));
+    }.bind(this)
+  );
+ 
+  this._deflate.on(
+    "end",
+    function () {
+      this.emit("data", this._packer.packIEND());
+      this.emit("end");
+    }.bind(this)
+  );
+ 
+  this._deflate.end(filteredData);
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/packer-sync.js.html b/node_modules/pngjs/coverage/lcov-report/packer-sync.js.html new file mode 100644 index 0000000..86283b5 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/packer-sync.js.html @@ -0,0 +1,248 @@ + + + + + + Code coverage report for packer-sync.js + + + + + + + + + +
+
+

All files packer-sync.js

+
+ +
+ 25% + Statements + 6/24 +
+ + +
+ 8.33% + Branches + 1/12 +
+ + +
+ 0% + Functions + 0/1 +
+ + +
+ 25% + Lines + 6/24 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57  +  +1x +1x +1x +  +  +1x +1x +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  + 
"use strict";
+ 
+let hasSyncZlib = true;
+let zlib = require("zlib");
+Iif (!zlib.deflateSync) {
+  hasSyncZlib = false;
+}
+let constants = require("./constants");
+let Packer = require("./packer");
+ 
+module.exports = function (metaData, opt) {
+  if (!hasSyncZlib) {
+    throw new Error(
+      "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
+    );
+  }
+ 
+  let options = opt || {};
+ 
+  let packer = new Packer(options);
+ 
+  let chunks = [];
+ 
+  // Signature
+  chunks.push(Buffer.from(constants.PNG_SIGNATURE));
+ 
+  // Header
+  chunks.push(packer.packIHDR(metaData.width, metaData.height));
+ 
+  if (metaData.gamma) {
+    chunks.push(packer.packGAMA(metaData.gamma));
+  }
+ 
+  let filteredData = packer.filterData(
+    metaData.data,
+    metaData.width,
+    metaData.height
+  );
+ 
+  // compress it
+  let compressedData = zlib.deflateSync(
+    filteredData,
+    packer.getDeflateOptions()
+  );
+  filteredData = null;
+ 
+  if (!compressedData || !compressedData.length) {
+    throw new Error("bad png - invalid compressed data response");
+  }
+  chunks.push(packer.packIDAT(compressedData));
+ 
+  // End
+  chunks.push(packer.packIEND());
+ 
+  return Buffer.concat(chunks);
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/packer.js.html b/node_modules/pngjs/coverage/lcov-report/packer.js.html new file mode 100644 index 0000000..606e193 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/packer.js.html @@ -0,0 +1,467 @@ + + + + + + Code coverage report for packer.js + + + + + + + + + +
+
+

All files packer.js

+
+ +
+ 94.74% + Statements + 54/57 +
+ + +
+ 67.86% + Branches + 19/28 +
+ + +
+ 100% + Functions + 9/9 +
+ + +
+ 94.74% + Lines + 54/57 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130  +  +1x +1x +1x +1x +1x +  +1x +353x +  +353x +353x +  +353x +  +353x +  +353x +353x +  +353x +  +  +  +353x +  +  +  +  +353x +  +  +  +  +  +  +  +  +  +  +  +353x +  +  +  +  +  +  +  +  +  +  +  +  +  +353x +  +  +  +  +  +  +1x +353x +  +  +  +  +  +  +1x +353x +  +  +1x +  +325x +  +  +325x +325x +325x +  +  +1x +1592x +1592x +  +1592x +1592x +  +1592x +1267x +  +  +1592x +  +  +  +1592x +  +  +1x +290x +290x +290x +  +  +1x +325x +325x +325x +325x +325x +325x +325x +325x +  +325x +  +  +1x +652x +  +  +1x +325x +  + 
"use strict";
+ 
+let constants = require("./constants");
+let CrcStream = require("./crc");
+let bitPacker = require("./bitpacker");
+let filter = require("./filter-pack");
+let zlib = require("zlib");
+ 
+let Packer = (module.exports = function (options) {
+  this._options = options;
+ 
+  options.deflateChunkSize = options.deflateChunkSize || 32 * 1024;
+  options.deflateLevel =
+    options.deflateLevel != null ? options.deflateLevel : 9;
+  options.deflateStrategy =
+    options.deflateStrategy != null ? options.deflateStrategy : 3;
+  options.inputHasAlpha =
+    options.inputHasAlpha != null ? options.inputHasAlpha : true;
+  options.deflateFactory = options.deflateFactory || zlib.createDeflate;
+  options.bitDepth = options.bitDepth || 8;
+  // This is outputColorType
+  options.colorType =
+    typeof options.colorType === "number"
+      ? options.colorType
+      : constants.COLORTYPE_COLOR_ALPHA;
+  options.inputColorType =
+    typeof options.inputColorType === "number"
+      ? options.inputColorType
+      : constants.COLORTYPE_COLOR_ALPHA;
+ 
+  Iif (
+    [
+      constants.COLORTYPE_GRAYSCALE,
+      constants.COLORTYPE_COLOR,
+      constants.COLORTYPE_COLOR_ALPHA,
+      constants.COLORTYPE_ALPHA,
+    ].indexOf(options.colorType) === -1
+  ) {
+    throw new Error(
+      "option color type:" + options.colorType + " is not supported at present"
+    );
+  }
+  Iif (
+    [
+      constants.COLORTYPE_GRAYSCALE,
+      constants.COLORTYPE_COLOR,
+      constants.COLORTYPE_COLOR_ALPHA,
+      constants.COLORTYPE_ALPHA,
+    ].indexOf(options.inputColorType) === -1
+  ) {
+    throw new Error(
+      "option input color type:" +
+        options.inputColorType +
+        " is not supported at present"
+    );
+  }
+  Iif (options.bitDepth !== 8 && options.bitDepth !== 16) {
+    throw new Error(
+      "option bit depth:" + options.bitDepth + " is not supported at present"
+    );
+  }
+});
+ 
+Packer.prototype.getDeflateOptions = function () {
+  return {
+    chunkSize: this._options.deflateChunkSize,
+    level: this._options.deflateLevel,
+    strategy: this._options.deflateStrategy,
+  };
+};
+ 
+Packer.prototype.createDeflate = function () {
+  return this._options.deflateFactory(this.getDeflateOptions());
+};
+ 
+Packer.prototype.filterData = function (data, width, height) {
+  // convert to correct format for filtering (e.g. right bpp and bit depth)
+  let packedData = bitPacker(data, width, height, this._options);
+ 
+  // filter pixel data
+  let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType];
+  let filteredData = filter(packedData, width, height, this._options, bpp);
+  return filteredData;
+};
+ 
+Packer.prototype._packChunk = function (type, data) {
+  let len = data ? data.length : 0;
+  let buf = Buffer.alloc(len + 12);
+ 
+  buf.writeUInt32BE(len, 0);
+  buf.writeUInt32BE(type, 4);
+ 
+  if (data) {
+    data.copy(buf, 8);
+  }
+ 
+  buf.writeInt32BE(
+    CrcStream.crc32(buf.slice(4, buf.length - 4)),
+    buf.length - 4
+  );
+  return buf;
+};
+ 
+Packer.prototype.packGAMA = function (gamma) {
+  let buf = Buffer.alloc(4);
+  buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0);
+  return this._packChunk(constants.TYPE_gAMA, buf);
+};
+ 
+Packer.prototype.packIHDR = function (width, height) {
+  let buf = Buffer.alloc(13);
+  buf.writeUInt32BE(width, 0);
+  buf.writeUInt32BE(height, 4);
+  buf[8] = this._options.bitDepth; // Bit depth
+  buf[9] = this._options.colorType; // colorType
+  buf[10] = 0; // compression
+  buf[11] = 0; // filter
+  buf[12] = 0; // interlace
+ 
+  return this._packChunk(constants.TYPE_IHDR, buf);
+};
+ 
+Packer.prototype.packIDAT = function (data) {
+  return this._packChunk(constants.TYPE_IDAT, data);
+};
+ 
+Packer.prototype.packIEND = function () {
+  return this._packChunk(constants.TYPE_IEND, null);
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/paeth-predictor.js.html b/node_modules/pngjs/coverage/lcov-report/paeth-predictor.js.html new file mode 100644 index 0000000..6385999 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/paeth-predictor.js.html @@ -0,0 +1,128 @@ + + + + + + Code coverage report for paeth-predictor.js + + + + + + + + + +
+
+

All files paeth-predictor.js

+
+ +
+ 100% + Statements + 10/10 +
+ + +
+ 100% + Branches + 6/6 +
+ + +
+ 100% + Functions + 1/1 +
+ + +
+ 100% + Lines + 10/10 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17  +  +1x +5808408x +5808408x +5808408x +5808408x +  +5808408x +5156742x +  +651666x +539893x +  +111773x +  + 
"use strict";
+ 
+module.exports = function paethPredictor(left, above, upLeft) {
+  let paeth = left + above - upLeft;
+  let pLeft = Math.abs(paeth - left);
+  let pAbove = Math.abs(paeth - above);
+  let pUpLeft = Math.abs(paeth - upLeft);
+ 
+  if (pLeft <= pAbove && pLeft <= pUpLeft) {
+    return left;
+  }
+  if (pAbove <= pUpLeft) {
+    return above;
+  }
+  return upLeft;
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/parser-async.js.html b/node_modules/pngjs/coverage/lcov-report/parser-async.js.html new file mode 100644 index 0000000..77074ff --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/parser-async.js.html @@ -0,0 +1,575 @@ + + + + + + Code coverage report for parser-async.js + + + + + + + + + +
+
+

All files parser-async.js

+
+ +
+ 88.75% + Statements + 71/80 +
+ + +
+ 72.73% + Branches + 16/22 +
+ + +
+ 84.62% + Functions + 11/13 +
+ + +
+ 88.75% + Lines + 71/80 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166  +  +1x +1x +1x +1x +1x +1x +1x +  +1x +353x +  +353x +  +  +  +  +  +  +  +  +  +  +  +353x +353x +  +353x +  +1x +  +1x +14x +  +14x +  +14x +  +14x +1x +  +  +14x +2x +  +  +  +2x +  +  +14x +  +  +1x +741x +174x +36x +  +36x +36x +  +36x +  +  +138x +  +  +  +  +  +138x +138x +  +138x +138x +  +138x +138x +  +  +  +  +  +  +138x +  +138x +138x +487x +  +  +  +487x +  +  +  +487x +  +487x +  +  +138x +  +  +741x +  +  +1x +176x +176x +  +176x +  +  +1x +7x +  +  +1x +77x +  +  +1x +15x +  +  +1x +  +  +174x +  +  +1x +173x +  +  +  +173x +1x +  +  +172x +  +  +  +1x +173x +  +  +  +  +  +173x +173x +  +173x +173x +  +  +  +  +  +173x +  + 
"use strict";
+ 
+let util = require("util");
+let zlib = require("zlib");
+let ChunkStream = require("./chunkstream");
+let FilterAsync = require("./filter-parse-async");
+let Parser = require("./parser");
+let bitmapper = require("./bitmapper");
+let formatNormaliser = require("./format-normaliser");
+ 
+let ParserAsync = (module.exports = function (options) {
+  ChunkStream.call(this);
+ 
+  this._parser = new Parser(options, {
+    read: this.read.bind(this),
+    error: this._handleError.bind(this),
+    metadata: this._handleMetaData.bind(this),
+    gamma: this.emit.bind(this, "gamma"),
+    palette: this._handlePalette.bind(this),
+    transColor: this._handleTransColor.bind(this),
+    finished: this._finished.bind(this),
+    inflateData: this._inflateData.bind(this),
+    simpleTransparency: this._simpleTransparency.bind(this),
+    headersFinished: this._headersFinished.bind(this),
+  });
+  this._options = options;
+  this.writable = true;
+ 
+  this._parser.start();
+});
+util.inherits(ParserAsync, ChunkStream);
+ 
+ParserAsync.prototype._handleError = function (err) {
+  this.emit("error", err);
+ 
+  this.writable = false;
+ 
+  this.destroy();
+ 
+  if (this._inflate && this._inflate.destroy) {
+    this._inflate.destroy();
+  }
+ 
+  if (this._filter) {
+    this._filter.destroy();
+    // For backward compatibility with Node 7 and below.
+    // Suppress errors due to _inflate calling write() even after
+    // it's destroy()'ed.
+    this._filter.on("error", function () {});
+  }
+ 
+  this.errord = true;
+};
+ 
+ParserAsync.prototype._inflateData = function (data) {
+  if (!this._inflate) {
+    if (this._bitmapInfo.interlace) {
+      this._inflate = zlib.createInflate();
+ 
+      this._inflate.on("error", this.emit.bind(this, "error"));
+      this._filter.on("complete", this._complete.bind(this));
+ 
+      this._inflate.pipe(this._filter);
+    } else {
+      let rowSize =
+        ((this._bitmapInfo.width *
+          this._bitmapInfo.bpp *
+          this._bitmapInfo.depth +
+          7) >>
+          3) +
+        1;
+      let imageSize = rowSize * this._bitmapInfo.height;
+      let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK);
+ 
+      this._inflate = zlib.createInflate({ chunkSize: chunkSize });
+      let leftToInflate = imageSize;
+ 
+      let emitError = this.emit.bind(this, "error");
+      this._inflate.on("error", function (err) {
+        if (!leftToInflate) {
+          return;
+        }
+ 
+        emitError(err);
+      });
+      this._filter.on("complete", this._complete.bind(this));
+ 
+      let filterWrite = this._filter.write.bind(this._filter);
+      this._inflate.on("data", function (chunk) {
+        Iif (!leftToInflate) {
+          return;
+        }
+ 
+        Iif (chunk.length > leftToInflate) {
+          chunk = chunk.slice(0, leftToInflate);
+        }
+ 
+        leftToInflate -= chunk.length;
+ 
+        filterWrite(chunk);
+      });
+ 
+      this._inflate.on("end", this._filter.end.bind(this._filter));
+    }
+  }
+  this._inflate.write(data);
+};
+ 
+ParserAsync.prototype._handleMetaData = function (metaData) {
+  this._metaData = metaData;
+  this._bitmapInfo = Object.create(metaData);
+ 
+  this._filter = new FilterAsync(this._bitmapInfo);
+};
+ 
+ParserAsync.prototype._handleTransColor = function (transColor) {
+  this._bitmapInfo.transColor = transColor;
+};
+ 
+ParserAsync.prototype._handlePalette = function (palette) {
+  this._bitmapInfo.palette = palette;
+};
+ 
+ParserAsync.prototype._simpleTransparency = function () {
+  this._metaData.alpha = true;
+};
+ 
+ParserAsync.prototype._headersFinished = function () {
+  // Up until this point, we don't know if we have a tRNS chunk (alpha)
+  // so we can't emit metadata any earlier
+  this.emit("metadata", this._metaData);
+};
+ 
+ParserAsync.prototype._finished = function () {
+  Iif (this.errord) {
+    return;
+  }
+ 
+  if (!this._inflate) {
+    this.emit("error", "No Inflate block");
+  } else {
+    // no more data to inflate
+    this._inflate.end();
+  }
+};
+ 
+ParserAsync.prototype._complete = function (filteredData) {
+  Iif (this.errord) {
+    return;
+  }
+ 
+  let normalisedBitmapData;
+ 
+  try {
+    let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo);
+ 
+    normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo);
+    bitmapData = null;
+  } catch (ex) {
+    this._handleError(ex);
+    return;
+  }
+ 
+  this.emit("parsed", normalisedBitmapData);
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/parser-sync.js.html b/node_modules/pngjs/coverage/lcov-report/parser-sync.js.html new file mode 100644 index 0000000..6ced1a9 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/parser-sync.js.html @@ -0,0 +1,404 @@ + + + + + + Code coverage report for parser-sync.js + + + + + + + + + +
+
+

All files parser-sync.js

+
+ +
+ 93.33% + Statements + 42/45 +
+ + +
+ 78.57% + Branches + 11/14 +
+ + +
+ 100% + Functions + 8/8 +
+ + +
+ 93.33% + Lines + 42/45 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109  +  +1x +1x +1x +1x +  +  +1x +1x +1x +1x +1x +  +1x +176x +  +  +  +  +  +  +  +13x +  +  +  +  +165x +  +  +  +5x +  +  +  +73x +  +  +  +12x +  +  +  +  +147x +  +  +176x +  +492x +  +  +176x +  +176x +  +  +  +  +  +  +  +  +  +  +176x +176x +  +176x +13x +  +  +  +163x +163x +  +  +163x +36x +  +  +127x +127x +127x +  +  +  +  +162x +  +162x +  +  +  +162x +162x +  +162x +162x +  +162x +  +162x +162x +  +162x +  + 
"use strict";
+ 
+let hasSyncZlib = true;
+let zlib = require("zlib");
+let inflateSync = require("./sync-inflate");
+Iif (!zlib.deflateSync) {
+  hasSyncZlib = false;
+}
+let SyncReader = require("./sync-reader");
+let FilterSync = require("./filter-parse-sync");
+let Parser = require("./parser");
+let bitmapper = require("./bitmapper");
+let formatNormaliser = require("./format-normaliser");
+ 
+module.exports = function (buffer, options) {
+  Iif (!hasSyncZlib) {
+    throw new Error(
+      "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0"
+    );
+  }
+ 
+  let err;
+  function handleError(_err_) {
+    err = _err_;
+  }
+ 
+  let metaData;
+  function handleMetaData(_metaData_) {
+    metaData = _metaData_;
+  }
+ 
+  function handleTransColor(transColor) {
+    metaData.transColor = transColor;
+  }
+ 
+  function handlePalette(palette) {
+    metaData.palette = palette;
+  }
+ 
+  function handleSimpleTransparency() {
+    metaData.alpha = true;
+  }
+ 
+  let gamma;
+  function handleGamma(_gamma_) {
+    gamma = _gamma_;
+  }
+ 
+  let inflateDataList = [];
+  function handleInflateData(inflatedData) {
+    inflateDataList.push(inflatedData);
+  }
+ 
+  let reader = new SyncReader(buffer);
+ 
+  let parser = new Parser(options, {
+    read: reader.read.bind(reader),
+    error: handleError,
+    metadata: handleMetaData,
+    gamma: handleGamma,
+    palette: handlePalette,
+    transColor: handleTransColor,
+    inflateData: handleInflateData,
+    simpleTransparency: handleSimpleTransparency,
+  });
+ 
+  parser.start();
+  reader.process();
+ 
+  if (err) {
+    throw err;
+  }
+ 
+  //join together the inflate datas
+  let inflateData = Buffer.concat(inflateDataList);
+  inflateDataList.length = 0;
+ 
+  let inflatedData;
+  if (metaData.interlace) {
+    inflatedData = zlib.inflateSync(inflateData);
+  } else {
+    let rowSize =
+      ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1;
+    let imageSize = rowSize * metaData.height;
+    inflatedData = inflateSync(inflateData, {
+      chunkSize: imageSize,
+      maxLength: imageSize,
+    });
+  }
+  inflateData = null;
+ 
+  Iif (!inflatedData || !inflatedData.length) {
+    throw new Error("bad png - invalid inflate data response");
+  }
+ 
+  let unfilteredData = FilterSync.process(inflatedData, metaData);
+  inflateData = null;
+ 
+  let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData);
+  unfilteredData = null;
+ 
+  let normalisedBitmapData = formatNormaliser(bitmapData, metaData);
+ 
+  metaData.data = normalisedBitmapData;
+  metaData.gamma = gamma || 0;
+ 
+  return metaData;
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/parser.js.html b/node_modules/pngjs/coverage/lcov-report/parser.js.html new file mode 100644 index 0000000..efc9504 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/parser.js.html @@ -0,0 +1,950 @@ + + + + + + Code coverage report for parser.js + + + + + + + + + +
+
+

All files parser.js

+
+ +
+ 90.57% + Statements + 144/159 +
+ + +
+ 85.45% + Branches + 47/55 +
+ + +
+ 100% + Functions + 20/20 +
+ + +
+ 90.32% + Lines + 140/155 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195 +196 +197 +198 +199 +200 +201 +202 +203 +204 +205 +206 +207 +208 +209 +210 +211 +212 +213 +214 +215 +216 +217 +218 +219 +220 +221 +222 +223 +224 +225 +226 +227 +228 +229 +230 +231 +232 +233 +234 +235 +236 +237 +238 +239 +240 +241 +242 +243 +244 +245 +246 +247 +248 +249 +250 +251 +252 +253 +254 +255 +256 +257 +258 +259 +260 +261 +262 +263 +264 +265 +266 +267 +268 +269 +270 +271 +272 +273 +274 +275 +276 +277 +278 +279 +280 +281 +282 +283 +284 +285 +286 +287 +288 +289 +290 +291  +  +1x +1x +  +1x +529x +529x +  +529x +529x +529x +  +  +529x +529x +  +529x +529x +529x +529x +529x +529x +529x +  +529x +529x +529x +529x +529x +529x +529x +529x +529x +529x +529x +  +  +1x +529x +  +  +1x +365x +  +365x +2867x +13x +13x +  +  +352x +  +  +1x +  +2461x +  +  +2461x +2461x +2461x +9844x +  +  +  +  +  +2461x +  +  +  +2461x +  +  +  +  +2461x +2461x +  +2461x +2205x +  +  +256x +  +  +  +  +256x +  +  +1x +256x +  +  +1x +2195x +  +  +1x +2195x +2195x +  +  +2195x +4x +4x +  +  +2191x +1855x +  +  +  +1x +351x +  +1x +351x +  +351x +351x +351x +351x +351x +351x +351x +  +  +  +  +  +  +351x +  +  +  +  +  +  +6x +6x +  +345x +4x +4x +  +341x +  +  +  +341x +  +  +  +341x +  +  +  +  +341x +  +341x +  +341x +  +341x +  +  +  +  +  +  +  +  +  +  +  +341x +  +  +1x +135x +  +1x +135x +  +135x +  +  +135x +7350x +  +  +135x +  +135x +  +  +1x +27x +27x +  +1x +27x +  +  +27x +15x +  +  +  +15x +  +  +  +15x +529x +  +15x +  +  +  +  +27x +  +6x +  +27x +6x +  +  +  +  +  +  +27x +  +  +1x +296x +  +1x +296x +296x +  +296x +  +  +1x +1233x +337x +337x +  +1233x +  +1x +1233x +  +1233x +  +  +  +  +  +  +1233x +1233x +  +1233x +173x +  +1060x +  +  +  +1x +336x +  +1x +336x +  +336x +336x +  +336x +173x +  +  + 
"use strict";
+ 
+let constants = require("./constants");
+let CrcCalculator = require("./crc");
+ 
+let Parser = (module.exports = function (options, dependencies) {
+  this._options = options;
+  options.checkCRC = options.checkCRC !== false;
+ 
+  this._hasIHDR = false;
+  this._hasIEND = false;
+  this._emittedHeadersFinished = false;
+ 
+  // input flags/metadata
+  this._palette = [];
+  this._colorType = 0;
+ 
+  this._chunks = {};
+  this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this);
+  this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this);
+  this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this);
+  this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this);
+  this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this);
+  this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this);
+ 
+  this.read = dependencies.read;
+  this.error = dependencies.error;
+  this.metadata = dependencies.metadata;
+  this.gamma = dependencies.gamma;
+  this.transColor = dependencies.transColor;
+  this.palette = dependencies.palette;
+  this.parsed = dependencies.parsed;
+  this.inflateData = dependencies.inflateData;
+  this.finished = dependencies.finished;
+  this.simpleTransparency = dependencies.simpleTransparency;
+  this.headersFinished = dependencies.headersFinished || function () {};
+});
+ 
+Parser.prototype.start = function () {
+  this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this));
+};
+ 
+Parser.prototype._parseSignature = function (data) {
+  let signature = constants.PNG_SIGNATURE;
+ 
+  for (let i = 0; i < signature.length; i++) {
+    if (data[i] !== signature[i]) {
+      this.error(new Error("Invalid file signature"));
+      return;
+    }
+  }
+  this.read(8, this._parseChunkBegin.bind(this));
+};
+ 
+Parser.prototype._parseChunkBegin = function (data) {
+  // chunk content length
+  let length = data.readUInt32BE(0);
+ 
+  // chunk type
+  let type = data.readUInt32BE(4);
+  let name = "";
+  for (let i = 4; i < 8; i++) {
+    name += String.fromCharCode(data[i]);
+  }
+ 
+  //console.log('chunk ', name, length);
+ 
+  // chunk flags
+  let ancillary = Boolean(data[4] & 0x20); // or critical
+  //    priv = Boolean(data[5] & 0x20), // or public
+  //    safeToCopy = Boolean(data[7] & 0x20); // or unsafe
+ 
+  Iif (!this._hasIHDR && type !== constants.TYPE_IHDR) {
+    this.error(new Error("Expected IHDR on beggining"));
+    return;
+  }
+ 
+  this._crc = new CrcCalculator();
+  this._crc.write(Buffer.from(name));
+ 
+  if (this._chunks[type]) {
+    return this._chunks[type](length);
+  }
+ 
+  Iif (!ancillary) {
+    this.error(new Error("Unsupported critical chunk type " + name));
+    return;
+  }
+ 
+  this.read(length + 4, this._skipChunk.bind(this));
+};
+ 
+Parser.prototype._skipChunk = function (/*data*/) {
+  this.read(8, this._parseChunkBegin.bind(this));
+};
+ 
+Parser.prototype._handleChunkEnd = function () {
+  this.read(4, this._parseChunkEnd.bind(this));
+};
+ 
+Parser.prototype._parseChunkEnd = function (data) {
+  let fileCrc = data.readInt32BE(0);
+  let calcCrc = this._crc.crc32();
+ 
+  // check CRC
+  if (this._options.checkCRC && calcCrc !== fileCrc) {
+    this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc));
+    return;
+  }
+ 
+  if (!this._hasIEND) {
+    this.read(8, this._parseChunkBegin.bind(this));
+  }
+};
+ 
+Parser.prototype._handleIHDR = function (length) {
+  this.read(length, this._parseIHDR.bind(this));
+};
+Parser.prototype._parseIHDR = function (data) {
+  this._crc.write(data);
+ 
+  let width = data.readUInt32BE(0);
+  let height = data.readUInt32BE(4);
+  let depth = data[8];
+  let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha
+  let compr = data[10];
+  let filter = data[11];
+  let interlace = data[12];
+ 
+  // console.log('    width', width, 'height', height,
+  //     'depth', depth, 'colorType', colorType,
+  //     'compr', compr, 'filter', filter, 'interlace', interlace
+  // );
+ 
+  if (
+    depth !== 8 &&
+    depth !== 4 &&
+    depth !== 2 &&
+    depth !== 1 &&
+    depth !== 16
+  ) {
+    this.error(new Error("Unsupported bit depth " + depth));
+    return;
+  }
+  if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) {
+    this.error(new Error("Unsupported color type"));
+    return;
+  }
+  Iif (compr !== 0) {
+    this.error(new Error("Unsupported compression method"));
+    return;
+  }
+  Iif (filter !== 0) {
+    this.error(new Error("Unsupported filter method"));
+    return;
+  }
+  Iif (interlace !== 0 && interlace !== 1) {
+    this.error(new Error("Unsupported interlace method"));
+    return;
+  }
+ 
+  this._colorType = colorType;
+ 
+  let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType];
+ 
+  this._hasIHDR = true;
+ 
+  this.metadata({
+    width: width,
+    height: height,
+    depth: depth,
+    interlace: Boolean(interlace),
+    palette: Boolean(colorType & constants.COLORTYPE_PALETTE),
+    color: Boolean(colorType & constants.COLORTYPE_COLOR),
+    alpha: Boolean(colorType & constants.COLORTYPE_ALPHA),
+    bpp: bpp,
+    colorType: colorType,
+  });
+ 
+  this._handleChunkEnd();
+};
+ 
+Parser.prototype._handlePLTE = function (length) {
+  this.read(length, this._parsePLTE.bind(this));
+};
+Parser.prototype._parsePLTE = function (data) {
+  this._crc.write(data);
+ 
+  let entries = Math.floor(data.length / 3);
+  // console.log('Palette:', entries);
+ 
+  for (let i = 0; i < entries; i++) {
+    this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]);
+  }
+ 
+  this.palette(this._palette);
+ 
+  this._handleChunkEnd();
+};
+ 
+Parser.prototype._handleTRNS = function (length) {
+  this.simpleTransparency();
+  this.read(length, this._parseTRNS.bind(this));
+};
+Parser.prototype._parseTRNS = function (data) {
+  this._crc.write(data);
+ 
+  // palette
+  if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) {
+    Iif (this._palette.length === 0) {
+      this.error(new Error("Transparency chunk must be after palette"));
+      return;
+    }
+    Iif (data.length > this._palette.length) {
+      this.error(new Error("More transparent colors than palette size"));
+      return;
+    }
+    for (let i = 0; i < data.length; i++) {
+      this._palette[i][3] = data[i];
+    }
+    this.palette(this._palette);
+  }
+ 
+  // for colorType 0 (grayscale) and 2 (rgb)
+  // there might be one gray/color defined as transparent
+  if (this._colorType === constants.COLORTYPE_GRAYSCALE) {
+    // grey, 2 bytes
+    this.transColor([data.readUInt16BE(0)]);
+  }
+  if (this._colorType === constants.COLORTYPE_COLOR) {
+    this.transColor([
+      data.readUInt16BE(0),
+      data.readUInt16BE(2),
+      data.readUInt16BE(4),
+    ]);
+  }
+ 
+  this._handleChunkEnd();
+};
+ 
+Parser.prototype._handleGAMA = function (length) {
+  this.read(length, this._parseGAMA.bind(this));
+};
+Parser.prototype._parseGAMA = function (data) {
+  this._crc.write(data);
+  this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION);
+ 
+  this._handleChunkEnd();
+};
+ 
+Parser.prototype._handleIDAT = function (length) {
+  if (!this._emittedHeadersFinished) {
+    this._emittedHeadersFinished = true;
+    this.headersFinished();
+  }
+  this.read(-length, this._parseIDAT.bind(this, length));
+};
+Parser.prototype._parseIDAT = function (length, data) {
+  this._crc.write(data);
+ 
+  Iif (
+    this._colorType === constants.COLORTYPE_PALETTE_COLOR &&
+    this._palette.length === 0
+  ) {
+    throw new Error("Expected palette not found");
+  }
+ 
+  this.inflateData(data);
+  let leftOverLength = length - data.length;
+ 
+  if (leftOverLength > 0) {
+    this._handleIDAT(leftOverLength);
+  } else {
+    this._handleChunkEnd();
+  }
+};
+ 
+Parser.prototype._handleIEND = function (length) {
+  this.read(length, this._parseIEND.bind(this));
+};
+Parser.prototype._parseIEND = function (data) {
+  this._crc.write(data);
+ 
+  this._hasIEND = true;
+  this._handleChunkEnd();
+ 
+  if (this.finished) {
+    this.finished();
+  }
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/png-sync.js.html b/node_modules/pngjs/coverage/lcov-report/png-sync.js.html new file mode 100644 index 0000000..848f6a6 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/png-sync.js.html @@ -0,0 +1,116 @@ + + + + + + Code coverage report for png-sync.js + + + + + + + + + +
+
+

All files png-sync.js

+
+ +
+ 83.33% + Statements + 5/6 +
+ + +
+ 100% + Branches + 2/2 +
+ + +
+ 50% + Functions + 1/2 +
+ + +
+ 83.33% + Lines + 5/6 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13  +  +1x +1x +  +1x +176x +  +  +1x +  +  + 
"use strict";
+ 
+let parse = require("./parser-sync");
+let pack = require("./packer-sync");
+ 
+exports.read = function (buffer, options) {
+  return parse(buffer, options || {});
+};
+ 
+exports.write = function (png, options) {
+  return pack(png, options);
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/png.js.html b/node_modules/pngjs/coverage/lcov-report/png.js.html new file mode 100644 index 0000000..baa8803 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/png.js.html @@ -0,0 +1,662 @@ + + + + + + Code coverage report for png.js + + + + + + + + + +
+
+

All files png.js

+
+ +
+ 54.17% + Statements + 52/96 +
+ + +
+ 41.18% + Branches + 14/34 +
+ + +
+ 56.25% + Functions + 9/16 +
+ + +
+ 56.52% + Lines + 52/92 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169 +170 +171 +172 +173 +174 +175 +176 +177 +178 +179 +180 +181 +182 +183 +184 +185 +186 +187 +188 +189 +190 +191 +192 +193 +194 +195  +  +1x +1x +1x +1x +1x +  +1x +353x +  +353x +  +  +353x +353x +  +353x +  +  +  +  +353x +  +  +  +353x +353x +  +353x +  +353x +353x +353x +353x +353x +  +  +173x +173x +  +  +  +353x +353x +353x +353x +353x +  +1x +  +1x +  +1x +325x +  +  +  +  +325x +  +325x +  +  +  +325x +  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +412x +412x +  +  +1x +175x +  +  +1x +174x +174x +  +174x +  +  +1x +149x +  +  +1x +378x +  +  +  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +1x +  +  + 
"use strict";
+ 
+let util = require("util");
+let Stream = require("stream");
+let Parser = require("./parser-async");
+let Packer = require("./packer-async");
+let PNGSync = require("./png-sync");
+ 
+let PNG = (exports.PNG = function (options) {
+  Stream.call(this);
+ 
+  options = options || {}; // eslint-disable-line no-param-reassign
+ 
+  // coerce pixel dimensions to integers (also coerces undefined -> 0):
+  this.width = options.width | 0;
+  this.height = options.height | 0;
+ 
+  this.data =
+    this.width > 0 && this.height > 0
+      ? Buffer.alloc(4 * this.width * this.height)
+      : null;
+ 
+  Iif (options.fill && this.data) {
+    this.data.fill(0);
+  }
+ 
+  this.gamma = 0;
+  this.readable = this.writable = true;
+ 
+  this._parser = new Parser(options);
+ 
+  this._parser.on("error", this.emit.bind(this, "error"));
+  this._parser.on("close", this._handleClose.bind(this));
+  this._parser.on("metadata", this._metadata.bind(this));
+  this._parser.on("gamma", this._gamma.bind(this));
+  this._parser.on(
+    "parsed",
+    function (data) {
+      this.data = data;
+      this.emit("parsed", data);
+    }.bind(this)
+  );
+ 
+  this._packer = new Packer(options);
+  this._packer.on("data", this.emit.bind(this, "data"));
+  this._packer.on("end", this.emit.bind(this, "end"));
+  this._parser.on("close", this._handleClose.bind(this));
+  this._packer.on("error", this.emit.bind(this, "error"));
+});
+util.inherits(PNG, Stream);
+ 
+PNG.sync = PNGSync;
+ 
+PNG.prototype.pack = function () {
+  Iif (!this.data || !this.data.length) {
+    this.emit("error", "No data provided");
+    return this;
+  }
+ 
+  process.nextTick(
+    function () {
+      this._packer.pack(this.data, this.width, this.height, this.gamma);
+    }.bind(this)
+  );
+ 
+  return this;
+};
+ 
+PNG.prototype.parse = function (data, callback) {
+  if (callback) {
+    let onParsed, onError;
+ 
+    onParsed = function (parsedData) {
+      this.removeListener("error", onError);
+ 
+      this.data = parsedData;
+      callback(null, this);
+    }.bind(this);
+ 
+    onError = function (err) {
+      this.removeListener("parsed", onParsed);
+ 
+      callback(err, null);
+    }.bind(this);
+ 
+    this.once("parsed", onParsed);
+    this.once("error", onError);
+  }
+ 
+  this.end(data);
+  return this;
+};
+ 
+PNG.prototype.write = function (data) {
+  this._parser.write(data);
+  return true;
+};
+ 
+PNG.prototype.end = function (data) {
+  this._parser.end(data);
+};
+ 
+PNG.prototype._metadata = function (metadata) {
+  this.width = metadata.width;
+  this.height = metadata.height;
+ 
+  this.emit("metadata", metadata);
+};
+ 
+PNG.prototype._gamma = function (gamma) {
+  this.gamma = gamma;
+};
+ 
+PNG.prototype._handleClose = function () {
+  Iif (!this._parser.writable && !this._packer.readable) {
+    this.emit("close");
+  }
+};
+ 
+PNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) {
+  // eslint-disable-line max-params
+  // coerce pixel dimensions to integers (also coerces undefined -> 0):
+  /* eslint-disable no-param-reassign */
+  srcX |= 0;
+  srcY |= 0;
+  width |= 0;
+  height |= 0;
+  deltaX |= 0;
+  deltaY |= 0;
+  /* eslint-enable no-param-reassign */
+ 
+  if (
+    srcX > src.width ||
+    srcY > src.height ||
+    srcX + width > src.width ||
+    srcY + height > src.height
+  ) {
+    throw new Error("bitblt reading outside image");
+  }
+ 
+  if (
+    deltaX > dst.width ||
+    deltaY > dst.height ||
+    deltaX + width > dst.width ||
+    deltaY + height > dst.height
+  ) {
+    throw new Error("bitblt writing outside image");
+  }
+ 
+  for (let y = 0; y < height; y++) {
+    src.data.copy(
+      dst.data,
+      ((deltaY + y) * dst.width + deltaX) << 2,
+      ((srcY + y) * src.width + srcX) << 2,
+      ((srcY + y) * src.width + srcX + width) << 2
+    );
+  }
+};
+ 
+PNG.prototype.bitblt = function (
+  dst,
+  srcX,
+  srcY,
+  width,
+  height,
+  deltaX,
+  deltaY
+) {
+  // eslint-disable-line max-params
+ 
+  PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY);
+  return this;
+};
+ 
+PNG.adjustGamma = function (src) {
+  if (src.gamma) {
+    for (let y = 0; y < src.height; y++) {
+      for (let x = 0; x < src.width; x++) {
+        let idx = (src.width * y + x) << 2;
+ 
+        for (let i = 0; i < 3; i++) {
+          let sample = src.data[idx + i] / 255;
+          sample = Math.pow(sample, 1 / 2.2 / src.gamma);
+          src.data[idx + i] = Math.round(sample * 255);
+        }
+      }
+    }
+    src.gamma = 0;
+  }
+};
+ 
+PNG.prototype.adjustGamma = function () {
+  PNG.adjustGamma(this);
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/prettify.css b/node_modules/pngjs/coverage/lcov-report/prettify.css new file mode 100644 index 0000000..006492c --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/prettify.css @@ -0,0 +1,101 @@ +.pln { + color: #000; +} +@media screen { + .str { + color: #080; + } + .kwd { + color: #008; + } + .com { + color: #800; + } + .typ { + color: #606; + } + .lit { + color: #066; + } + .pun, + .opn, + .clo { + color: #660; + } + .tag { + color: #008; + } + .atn { + color: #606; + } + .atv { + color: #080; + } + .dec, + .var { + color: #606; + } + .fun { + color: red; + } +} +@media print, projection { + .str { + color: #060; + } + .kwd { + color: #006; + font-weight: bold; + } + .com { + color: #600; + font-style: italic; + } + .typ { + color: #404; + font-weight: bold; + } + .lit { + color: #044; + } + .pun, + .opn, + .clo { + color: #440; + } + .tag { + color: #006; + font-weight: bold; + } + .atn { + color: #404; + } + .atv { + color: #060; + } +} +pre.prettyprint { + padding: 2px; + border: 1px solid #888; +} +ol.linenums { + margin-top: 0; + margin-bottom: 0; +} +li.L0, +li.L1, +li.L2, +li.L3, +li.L5, +li.L6, +li.L7, +li.L8 { + list-style-type: none; +} +li.L1, +li.L3, +li.L5, +li.L7, +li.L9 { + background: #eee; +} diff --git a/node_modules/pngjs/coverage/lcov-report/prettify.js b/node_modules/pngjs/coverage/lcov-report/prettify.js new file mode 100644 index 0000000..7c0a2fe --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/prettify.js @@ -0,0 +1,1007 @@ +/* eslint-disable */ +window.PR_SHOULD_USE_CONTINUATION = true; +(function () { + var h = ["break,continue,do,else,for,if,return,while"]; + var u = [ + h, + "auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile", + ]; + var p = [ + u, + "catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof", + ]; + var l = [ + p, + "alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where", + ]; + var x = [ + p, + "abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient", + ]; + var R = [ + x, + "as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var", + ]; + var r = + "all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes"; + var w = [ + p, + "debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN", + ]; + var s = + "caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END"; + var I = [ + h, + "and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None", + ]; + var f = [ + h, + "alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END", + ]; + var H = [h, "case,done,elif,esac,eval,fi,function,in,local,set,then,until"]; + var A = [l, R, w, s + I, f, H]; + var e = /^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/; + var C = "str"; + var z = "kwd"; + var j = "com"; + var O = "typ"; + var G = "lit"; + var L = "pun"; + var F = "pln"; + var m = "tag"; + var E = "dec"; + var J = "src"; + var P = "atn"; + var n = "atv"; + var N = "nocode"; + var M = + "(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*"; + function k(Z) { + var ad = 0; + var S = false; + var ac = false; + for (var V = 0, U = Z.length; V < U; ++V) { + var ae = Z[V]; + if (ae.ignoreCase) { + ac = true; + } else { + if ( + /[a-z]/i.test( + ae.source.replace(/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi, "") + ) + ) { + S = true; + ac = false; + break; + } + } + } + var Y = { b: 8, t: 9, n: 10, v: 11, f: 12, r: 13 }; + function ab(ah) { + var ag = ah.charCodeAt(0); + if (ag !== 92) { + return ag; + } + var af = ah.charAt(1); + ag = Y[af]; + if (ag) { + return ag; + } else { + if ("0" <= af && af <= "7") { + return parseInt(ah.substring(1), 8); + } else { + if (af === "u" || af === "x") { + return parseInt(ah.substring(2), 16); + } else { + return ah.charCodeAt(1); + } + } + } + } + function T(af) { + if (af < 32) { + return (af < 16 ? "\\x0" : "\\x") + af.toString(16); + } + var ag = String.fromCharCode(af); + if (ag === "\\" || ag === "-" || ag === "[" || ag === "]") { + ag = "\\" + ag; + } + return ag; + } + function X(am) { + var aq = am + .substring(1, am.length - 1) + .match( + new RegExp( + "\\\\u[0-9A-Fa-f]{4}|\\\\x[0-9A-Fa-f]{2}|\\\\[0-3][0-7]{0,2}|\\\\[0-7]{1,2}|\\\\[\\s\\S]|-|[^-\\\\]", + "g" + ) + ); + var ak = []; + var af = []; + var ao = aq[0] === "^"; + for (var ar = ao ? 1 : 0, aj = aq.length; ar < aj; ++ar) { + var ah = aq[ar]; + if (/\\[bdsw]/i.test(ah)) { + ak.push(ah); + } else { + var ag = ab(ah); + var al; + if (ar + 2 < aj && "-" === aq[ar + 1]) { + al = ab(aq[ar + 2]); + ar += 2; + } else { + al = ag; + } + af.push([ag, al]); + if (!(al < 65 || ag > 122)) { + if (!(al < 65 || ag > 90)) { + af.push([Math.max(65, ag) | 32, Math.min(al, 90) | 32]); + } + if (!(al < 97 || ag > 122)) { + af.push([Math.max(97, ag) & ~32, Math.min(al, 122) & ~32]); + } + } + } + } + af.sort(function (av, au) { + return av[0] - au[0] || au[1] - av[1]; + }); + var ai = []; + var ap = [NaN, NaN]; + for (var ar = 0; ar < af.length; ++ar) { + var at = af[ar]; + if (at[0] <= ap[1] + 1) { + ap[1] = Math.max(ap[1], at[1]); + } else { + ai.push((ap = at)); + } + } + var an = ["["]; + if (ao) { + an.push("^"); + } + an.push.apply(an, ak); + for (var ar = 0; ar < ai.length; ++ar) { + var at = ai[ar]; + an.push(T(at[0])); + if (at[1] > at[0]) { + if (at[1] + 1 > at[0]) { + an.push("-"); + } + an.push(T(at[1])); + } + } + an.push("]"); + return an.join(""); + } + function W(al) { + var aj = al.source.match( + new RegExp( + "(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)", + "g" + ) + ); + var ah = aj.length; + var an = []; + for (var ak = 0, am = 0; ak < ah; ++ak) { + var ag = aj[ak]; + if (ag === "(") { + ++am; + } else { + if ("\\" === ag.charAt(0)) { + var af = +ag.substring(1); + if (af && af <= am) { + an[af] = -1; + } + } + } + } + for (var ak = 1; ak < an.length; ++ak) { + if (-1 === an[ak]) { + an[ak] = ++ad; + } + } + for (var ak = 0, am = 0; ak < ah; ++ak) { + var ag = aj[ak]; + if (ag === "(") { + ++am; + if (an[am] === undefined) { + aj[ak] = "(?:"; + } + } else { + if ("\\" === ag.charAt(0)) { + var af = +ag.substring(1); + if (af && af <= am) { + aj[ak] = "\\" + an[am]; + } + } + } + } + for (var ak = 0, am = 0; ak < ah; ++ak) { + if ("^" === aj[ak] && "^" !== aj[ak + 1]) { + aj[ak] = ""; + } + } + if (al.ignoreCase && S) { + for (var ak = 0; ak < ah; ++ak) { + var ag = aj[ak]; + var ai = ag.charAt(0); + if (ag.length >= 2 && ai === "[") { + aj[ak] = X(ag); + } else { + if (ai !== "\\") { + aj[ak] = ag.replace(/[a-zA-Z]/g, function (ao) { + var ap = ao.charCodeAt(0); + return "[" + String.fromCharCode(ap & ~32, ap | 32) + "]"; + }); + } + } + } + } + return aj.join(""); + } + var aa = []; + for (var V = 0, U = Z.length; V < U; ++V) { + var ae = Z[V]; + if (ae.global || ae.multiline) { + throw new Error("" + ae); + } + aa.push("(?:" + W(ae) + ")"); + } + return new RegExp(aa.join("|"), ac ? "gi" : "g"); + } + function a(V) { + var U = /(?:^|\s)nocode(?:\s|$)/; + var X = []; + var T = 0; + var Z = []; + var W = 0; + var S; + if (V.currentStyle) { + S = V.currentStyle.whiteSpace; + } else { + if (window.getComputedStyle) { + S = document.defaultView + .getComputedStyle(V, null) + .getPropertyValue("white-space"); + } + } + var Y = S && "pre" === S.substring(0, 3); + function aa(ab) { + switch (ab.nodeType) { + case 1: + if (U.test(ab.className)) { + return; + } + for (var ae = ab.firstChild; ae; ae = ae.nextSibling) { + aa(ae); + } + var ad = ab.nodeName; + if ("BR" === ad || "LI" === ad) { + X[W] = "\n"; + Z[W << 1] = T++; + Z[(W++ << 1) | 1] = ab; + } + break; + case 3: + case 4: + var ac = ab.nodeValue; + if (ac.length) { + if (!Y) { + ac = ac.replace(/[ \t\r\n]+/g, " "); + } else { + ac = ac.replace(/\r\n?/g, "\n"); + } + X[W] = ac; + Z[W << 1] = T; + T += ac.length; + Z[(W++ << 1) | 1] = ab; + } + break; + } + } + aa(V); + return { sourceCode: X.join("").replace(/\n$/, ""), spans: Z }; + } + function B(S, U, W, T) { + if (!U) { + return; + } + var V = { sourceCode: U, basePos: S }; + W(V); + T.push.apply(T, V.decorations); + } + var v = /\S/; + function o(S) { + var V = undefined; + for (var U = S.firstChild; U; U = U.nextSibling) { + var T = U.nodeType; + V = T === 1 ? (V ? S : U) : T === 3 ? (v.test(U.nodeValue) ? S : V) : V; + } + return V === S ? undefined : V; + } + function g(U, T) { + var S = {}; + var V; + (function () { + var ad = U.concat(T); + var ah = []; + var ag = {}; + for (var ab = 0, Z = ad.length; ab < Z; ++ab) { + var Y = ad[ab]; + var ac = Y[3]; + if (ac) { + for (var ae = ac.length; --ae >= 0; ) { + S[ac.charAt(ae)] = Y; + } + } + var af = Y[1]; + var aa = "" + af; + if (!ag.hasOwnProperty(aa)) { + ah.push(af); + ag[aa] = null; + } + } + ah.push(/[\0-\uffff]/); + V = k(ah); + })(); + var X = T.length; + var W = function (ah) { + var Z = ah.sourceCode, + Y = ah.basePos; + var ad = [Y, F]; + var af = 0; + var an = Z.match(V) || []; + var aj = {}; + for (var ae = 0, aq = an.length; ae < aq; ++ae) { + var ag = an[ae]; + var ap = aj[ag]; + var ai = void 0; + var am; + if (typeof ap === "string") { + am = false; + } else { + var aa = S[ag.charAt(0)]; + if (aa) { + ai = ag.match(aa[1]); + ap = aa[0]; + } else { + for (var ao = 0; ao < X; ++ao) { + aa = T[ao]; + ai = ag.match(aa[1]); + if (ai) { + ap = aa[0]; + break; + } + } + if (!ai) { + ap = F; + } + } + am = ap.length >= 5 && "lang-" === ap.substring(0, 5); + if (am && !(ai && typeof ai[1] === "string")) { + am = false; + ap = J; + } + if (!am) { + aj[ag] = ap; + } + } + var ab = af; + af += ag.length; + if (!am) { + ad.push(Y + ab, ap); + } else { + var al = ai[1]; + var ak = ag.indexOf(al); + var ac = ak + al.length; + if (ai[2]) { + ac = ag.length - ai[2].length; + ak = ac - al.length; + } + var ar = ap.substring(5); + B(Y + ab, ag.substring(0, ak), W, ad); + B(Y + ab + ak, al, q(ar, al), ad); + B(Y + ab + ac, ag.substring(ac), W, ad); + } + } + ah.decorations = ad; + }; + return W; + } + function i(T) { + var W = [], + S = []; + if (T.tripleQuotedStrings) { + W.push([ + C, + /^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/, + null, + "'\"", + ]); + } else { + if (T.multiLineStrings) { + W.push([ + C, + /^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/, + null, + "'\"`", + ]); + } else { + W.push([ + C, + /^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/, + null, + "\"'", + ]); + } + } + if (T.verbatimStrings) { + S.push([C, /^@\"(?:[^\"]|\"\")*(?:\"|$)/, null]); + } + var Y = T.hashComments; + if (Y) { + if (T.cStyleComments) { + if (Y > 1) { + W.push([j, /^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/, null, "#"]); + } else { + W.push([ + j, + /^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/, + null, + "#", + ]); + } + S.push([ + C, + /^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/, + null, + ]); + } else { + W.push([j, /^#[^\r\n]*/, null, "#"]); + } + } + if (T.cStyleComments) { + S.push([j, /^\/\/[^\r\n]*/, null]); + S.push([j, /^\/\*[\s\S]*?(?:\*\/|$)/, null]); + } + if (T.regexLiterals) { + var X = + "/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/"; + S.push(["lang-regex", new RegExp("^" + M + "(" + X + ")")]); + } + var V = T.types; + if (V) { + S.push([O, V]); + } + var U = ("" + T.keywords).replace(/^ | $/g, ""); + if (U.length) { + S.push([ + z, + new RegExp("^(?:" + U.replace(/[\s,]+/g, "|") + ")\\b"), + null, + ]); + } + W.push([F, /^\s+/, null, " \r\n\t\xA0"]); + S.push( + [G, /^@[a-z_$][a-z_$@0-9]*/i, null], + [O, /^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/, null], + [F, /^[a-z_$][a-z_$@0-9]*/i, null], + [ + G, + new RegExp( + "^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*", + "i" + ), + null, + "0123456789", + ], + [F, /^\\[\s\S]?/, null], + [L, /^.[^\s\w\.$@\'\"\`\/\#\\]*/, null] + ); + return g(W, S); + } + var K = i({ + keywords: A, + hashComments: true, + cStyleComments: true, + multiLineStrings: true, + regexLiterals: true, + }); + function Q(V, ag) { + var U = /(?:^|\s)nocode(?:\s|$)/; + var ab = /\r\n?|\n/; + var ac = V.ownerDocument; + var S; + if (V.currentStyle) { + S = V.currentStyle.whiteSpace; + } else { + if (window.getComputedStyle) { + S = ac.defaultView + .getComputedStyle(V, null) + .getPropertyValue("white-space"); + } + } + var Z = S && "pre" === S.substring(0, 3); + var af = ac.createElement("LI"); + while (V.firstChild) { + af.appendChild(V.firstChild); + } + var W = [af]; + function ae(al) { + switch (al.nodeType) { + case 1: + if (U.test(al.className)) { + break; + } + if ("BR" === al.nodeName) { + ad(al); + if (al.parentNode) { + al.parentNode.removeChild(al); + } + } else { + for (var an = al.firstChild; an; an = an.nextSibling) { + ae(an); + } + } + break; + case 3: + case 4: + if (Z) { + var am = al.nodeValue; + var aj = am.match(ab); + if (aj) { + var ai = am.substring(0, aj.index); + al.nodeValue = ai; + var ah = am.substring(aj.index + aj[0].length); + if (ah) { + var ak = al.parentNode; + ak.insertBefore(ac.createTextNode(ah), al.nextSibling); + } + ad(al); + if (!ai) { + al.parentNode.removeChild(al); + } + } + } + break; + } + } + function ad(ak) { + while (!ak.nextSibling) { + ak = ak.parentNode; + if (!ak) { + return; + } + } + function ai(al, ar) { + var aq = ar ? al.cloneNode(false) : al; + var ao = al.parentNode; + if (ao) { + var ap = ai(ao, 1); + var an = al.nextSibling; + ap.appendChild(aq); + for (var am = an; am; am = an) { + an = am.nextSibling; + ap.appendChild(am); + } + } + return aq; + } + var ah = ai(ak.nextSibling, 0); + for (var aj; (aj = ah.parentNode) && aj.nodeType === 1; ) { + ah = aj; + } + W.push(ah); + } + for (var Y = 0; Y < W.length; ++Y) { + ae(W[Y]); + } + if (ag === (ag | 0)) { + W[0].setAttribute("value", ag); + } + var aa = ac.createElement("OL"); + aa.className = "linenums"; + var X = Math.max(0, (ag - 1) | 0) || 0; + for (var Y = 0, T = W.length; Y < T; ++Y) { + af = W[Y]; + af.className = "L" + ((Y + X) % 10); + if (!af.firstChild) { + af.appendChild(ac.createTextNode("\xA0")); + } + aa.appendChild(af); + } + V.appendChild(aa); + } + function D(ac) { + var aj = /\bMSIE\b/.test(navigator.userAgent); + var am = /\n/g; + var al = ac.sourceCode; + var an = al.length; + var V = 0; + var aa = ac.spans; + var T = aa.length; + var ah = 0; + var X = ac.decorations; + var Y = X.length; + var Z = 0; + X[Y] = an; + var ar, aq; + for (aq = ar = 0; aq < Y; ) { + if (X[aq] !== X[aq + 2]) { + X[ar++] = X[aq++]; + X[ar++] = X[aq++]; + } else { + aq += 2; + } + } + Y = ar; + for (aq = ar = 0; aq < Y; ) { + var at = X[aq]; + var ab = X[aq + 1]; + var W = aq + 2; + while (W + 2 <= Y && X[W + 1] === ab) { + W += 2; + } + X[ar++] = at; + X[ar++] = ab; + aq = W; + } + Y = X.length = ar; + var ae = null; + while (ah < T) { + var af = aa[ah]; + var S = aa[ah + 2] || an; + var ag = X[Z]; + var ap = X[Z + 2] || an; + var W = Math.min(S, ap); + var ak = aa[ah + 1]; + var U; + if (ak.nodeType !== 1 && (U = al.substring(V, W))) { + if (aj) { + U = U.replace(am, "\r"); + } + ak.nodeValue = U; + var ai = ak.ownerDocument; + var ao = ai.createElement("SPAN"); + ao.className = X[Z + 1]; + var ad = ak.parentNode; + ad.replaceChild(ao, ak); + ao.appendChild(ak); + if (V < S) { + aa[ah + 1] = ak = ai.createTextNode(al.substring(W, S)); + ad.insertBefore(ak, ao.nextSibling); + } + } + V = W; + if (V >= S) { + ah += 2; + } + if (V >= ap) { + Z += 2; + } + } + } + var t = {}; + function c(U, V) { + for (var S = V.length; --S >= 0; ) { + var T = V[S]; + if (!t.hasOwnProperty(T)) { + t[T] = U; + } else { + if (window.console) { + console.warn("cannot override language handler %s", T); + } + } + } + } + function q(T, S) { + if (!(T && t.hasOwnProperty(T))) { + T = /^\s*]*(?:>|$)/], + [j, /^<\!--[\s\S]*?(?:-\->|$)/], + ["lang-", /^<\?([\s\S]+?)(?:\?>|$)/], + ["lang-", /^<%([\s\S]+?)(?:%>|$)/], + [L, /^(?:<[%?]|[%?]>)/], + ["lang-", /^]*>([\s\S]+?)<\/xmp\b[^>]*>/i], + ["lang-js", /^]*>([\s\S]*?)(<\/script\b[^>]*>)/i], + ["lang-css", /^]*>([\s\S]*?)(<\/style\b[^>]*>)/i], + ["lang-in.tag", /^(<\/?[a-z][^<>]*>)/i], + ] + ), + ["default-markup", "htm", "html", "mxml", "xhtml", "xml", "xsl"] + ); + c( + g( + [ + [F, /^[\s]+/, null, " \t\r\n"], + [n, /^(?:\"[^\"]*\"?|\'[^\']*\'?)/, null, "\"'"], + ], + [ + [m, /^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i], + [P, /^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i], + ["lang-uq.val", /^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/], + [L, /^[=<>\/]+/], + ["lang-js", /^on\w+\s*=\s*\"([^\"]+)\"/i], + ["lang-js", /^on\w+\s*=\s*\'([^\']+)\'/i], + ["lang-js", /^on\w+\s*=\s*([^\"\'>\s]+)/i], + ["lang-css", /^style\s*=\s*\"([^\"]+)\"/i], + ["lang-css", /^style\s*=\s*\'([^\']+)\'/i], + ["lang-css", /^style\s*=\s*([^\"\'>\s]+)/i], + ] + ), + ["in.tag"] + ); + c(g([], [[n, /^[\s\S]+/]]), ["uq.val"]); + c(i({ keywords: l, hashComments: true, cStyleComments: true, types: e }), [ + "c", + "cc", + "cpp", + "cxx", + "cyc", + "m", + ]); + c(i({ keywords: "null,true,false" }), ["json"]); + c( + i({ + keywords: R, + hashComments: true, + cStyleComments: true, + verbatimStrings: true, + types: e, + }), + ["cs"] + ); + c(i({ keywords: x, cStyleComments: true }), ["java"]); + c(i({ keywords: H, hashComments: true, multiLineStrings: true }), [ + "bsh", + "csh", + "sh", + ]); + c( + i({ + keywords: I, + hashComments: true, + multiLineStrings: true, + tripleQuotedStrings: true, + }), + ["cv", "py"] + ); + c( + i({ + keywords: s, + hashComments: true, + multiLineStrings: true, + regexLiterals: true, + }), + ["perl", "pl", "pm"] + ); + c( + i({ + keywords: f, + hashComments: true, + multiLineStrings: true, + regexLiterals: true, + }), + ["rb"] + ); + c(i({ keywords: w, cStyleComments: true, regexLiterals: true }), ["js"]); + c( + i({ + keywords: r, + hashComments: 3, + cStyleComments: true, + multilineStrings: true, + tripleQuotedStrings: true, + regexLiterals: true, + }), + ["coffee"] + ); + c(g([], [[C, /^[\s\S]+/]]), ["regex"]); + function d(V) { + var U = V.langExtension; + try { + var S = a(V.sourceNode); + var T = S.sourceCode; + V.sourceCode = T; + V.spans = S.spans; + V.basePos = 0; + q(U, T)(V); + D(V); + } catch (W) { + if ("console" in window) { + console.log(W && W.stack ? W.stack : W); + } + } + } + function y(W, V, U) { + var S = document.createElement("PRE"); + S.innerHTML = W; + if (U) { + Q(S, U); + } + var T = { langExtension: V, numberLines: U, sourceNode: S }; + d(T); + return S.innerHTML; + } + function b(ad) { + function Y(af) { + return document.getElementsByTagName(af); + } + var ac = [Y("pre"), Y("code"), Y("xmp")]; + var T = []; + for (var aa = 0; aa < ac.length; ++aa) { + for (var Z = 0, V = ac[aa].length; Z < V; ++Z) { + T.push(ac[aa][Z]); + } + } + ac = null; + var W = Date; + if (!W.now) { + W = { + now: function () { + return +new Date(); + }, + }; + } + var X = 0; + var S; + var ab = /\blang(?:uage)?-([\w.]+)(?!\S)/; + var ae = /\bprettyprint\b/; + function U() { + var ag = window.PR_SHOULD_USE_CONTINUATION ? W.now() + 250 : Infinity; + for (; X < T.length && W.now() < ag; X++) { + var aj = T[X]; + var ai = aj.className; + if (ai.indexOf("prettyprint") >= 0) { + var ah = ai.match(ab); + var am; + if (!ah && (am = o(aj)) && "CODE" === am.tagName) { + ah = am.className.match(ab); + } + if (ah) { + ah = ah[1]; + } + var al = false; + for (var ak = aj.parentNode; ak; ak = ak.parentNode) { + if ( + (ak.tagName === "pre" || + ak.tagName === "code" || + ak.tagName === "xmp") && + ak.className && + ak.className.indexOf("prettyprint") >= 0 + ) { + al = true; + break; + } + } + if (!al) { + var af = aj.className.match(/\blinenums\b(?::(\d+))?/); + af = af ? (af[1] && af[1].length ? +af[1] : true) : false; + if (af) { + Q(aj, af); + } + S = { langExtension: ah, sourceNode: aj, numberLines: af }; + d(S); + } + } + } + if (X < T.length) { + setTimeout(U, 250); + } else { + if (ad) { + ad(); + } + } + } + U(); + } + window.prettyPrintOne = y; + window.prettyPrint = b; + window.PR = { + createSimpleLexer: g, + registerLangHandler: c, + sourceDecorator: i, + PR_ATTRIB_NAME: P, + PR_ATTRIB_VALUE: n, + PR_COMMENT: j, + PR_DECLARATION: E, + PR_KEYWORD: z, + PR_LITERAL: G, + PR_NOCODE: N, + PR_PLAIN: F, + PR_PUNCTUATION: L, + PR_SOURCE: J, + PR_STRING: C, + PR_TAG: m, + PR_TYPE: O, + }; +})(); +PR.registerLangHandler( + PR.createSimpleLexer( + [], + [ + [PR.PR_DECLARATION, /^]*(?:>|$)/], + [PR.PR_COMMENT, /^<\!--[\s\S]*?(?:-\->|$)/], + [PR.PR_PUNCTUATION, /^(?:<[%?]|[%?]>)/], + ["lang-", /^<\?([\s\S]+?)(?:\?>|$)/], + ["lang-", /^<%([\s\S]+?)(?:%>|$)/], + ["lang-", /^]*>([\s\S]+?)<\/xmp\b[^>]*>/i], + [ + "lang-handlebars", + /^]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i, + ], + ["lang-js", /^]*>([\s\S]*?)(<\/script\b[^>]*>)/i], + ["lang-css", /^]*>([\s\S]*?)(<\/style\b[^>]*>)/i], + ["lang-in.tag", /^(<\/?[a-z][^<>]*>)/i], + [PR.PR_DECLARATION, /^{{[#^>/]?\s*[\w.][^}]*}}/], + [PR.PR_DECLARATION, /^{{&?\s*[\w.][^}]*}}/], + [PR.PR_DECLARATION, /^{{{>?\s*[\w.][^}]*}}}/], + [PR.PR_COMMENT, /^{{![^}]*}}/], + ] + ), + ["handlebars", "hbs"] +); +PR.registerLangHandler( + PR.createSimpleLexer( + [[PR.PR_PLAIN, /^[ \t\r\n\f]+/, null, " \t\r\n\f"]], + [ + [ + PR.PR_STRING, + /^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/, + null, + ], + [ + PR.PR_STRING, + /^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/, + null, + ], + ["lang-css-str", /^url\(([^\)\"\']*)\)/i], + [ + PR.PR_KEYWORD, + /^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i, + null, + ], + [ + "lang-css-kw", + /^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i, + ], + [PR.PR_COMMENT, /^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//], + [PR.PR_COMMENT, /^(?:)/], + [PR.PR_LITERAL, /^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i], + [PR.PR_LITERAL, /^#(?:[0-9a-f]{3}){1,2}/i], + [ + PR.PR_PLAIN, + /^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i, + ], + [PR.PR_PUNCTUATION, /^[^\s\w\'\"]+/], + ] + ), + ["css"] +); +PR.registerLangHandler( + PR.createSimpleLexer( + [], + [ + [ + PR.PR_KEYWORD, + /^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i, + ], + ] + ), + ["css-kw"] +); +PR.registerLangHandler( + PR.createSimpleLexer([], [[PR.PR_STRING, /^[^\)\"\']+/]]), + ["css-str"] +); diff --git a/node_modules/pngjs/coverage/lcov-report/sort-arrow-sprite.png b/node_modules/pngjs/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..03f704a609c6fd0dbfdac63466a7d7c958b5cbf3 GIT binary patch literal 209 zcmeAS@N?(olHy`uVBq!ia0vp^>_9Bd!3HEZxJ@+%Qj#UE5hcO-X(i=}MX3yqDfvmM z3ZA)%>8U}fi7AzZCsS>Jii$m5978H@?Fn+^JD|Y9yzj{W`447Gxa{7*dM7nnnD-Lb z6^}Hx2)'; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll("td"), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute("data-value"); + if (col.type === "number") { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll("tr"), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function (a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector(".coverage-summary tbody"), + rowNodes = tableBody.querySelectorAll("tr"), + rows = [], + i; + + if (desc) { + finalSorter = function (a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, "").replace(/ sorted-desc$/, ""); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc + ? " sorted-desc" + : " sorted"; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function () { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i = 0; i < cols.length; i += 1) { + if (cols[i].sortable) { + // add the click event handler on the th so users + // dont have to click on those tiny arrows + el = getNthColumn(i).querySelector(".sorter").parentElement; + if (el.addEventListener) { + el.addEventListener("click", ithSorter(i)); + } else { + el.attachEvent("onclick", ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function () { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener("load", addSorting); diff --git a/node_modules/pngjs/coverage/lcov-report/sync-inflate.js.html b/node_modules/pngjs/coverage/lcov-report/sync-inflate.js.html new file mode 100644 index 0000000..9ae5a14 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/sync-inflate.js.html @@ -0,0 +1,584 @@ + + + + + + Code coverage report for sync-inflate.js + + + + + + + + + +
+
+

All files sync-inflate.js

+
+ +
+ 75.31% + Statements + 61/81 +
+ + +
+ 62% + Branches + 31/50 +
+ + +
+ 87.5% + Functions + 7/8 +
+ + +
+ 75.31% + Lines + 61/81 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68 +69 +70 +71 +72 +73 +74 +75 +76 +77 +78 +79 +80 +81 +82 +83 +84 +85 +86 +87 +88 +89 +90 +91 +92 +93 +94 +95 +96 +97 +98 +99 +100 +101 +102 +103 +104 +105 +106 +107 +108 +109 +110 +111 +112 +113 +114 +115 +116 +117 +118 +119 +120 +121 +122 +123 +124 +125 +126 +127 +128 +129 +130 +131 +132 +133 +134 +135 +136 +137 +138 +139 +140 +141 +142 +143 +144 +145 +146 +147 +148 +149 +150 +151 +152 +153 +154 +155 +156 +157 +158 +159 +160 +161 +162 +163 +164 +165 +166 +167 +168 +169  +  +1x +1x +1x +  +1x +  +  +127x +  +  +  +127x +9x +  +  +127x +  +  +127x +127x +  +127x +127x +  +  +  +  +  +  +  +  +126x +  +  +  +  +126x +  +  +  +126x +126x +  +  +1x +127x +  +  +  +127x +  +127x +127x +127x +127x +  +127x +127x +  +  +127x +1x +  +  +  +126x +  +  +  +126x +126x +  +126x +126x +126x +  +126x +9x +  +  +126x +126x +126x +  +126x +126x +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +  +127x +  +127x +127x +  +  +  +  +  +  +  +  +  +127x +  +  +127x +1x +  +  +126x +  +  +  +  +  +  +  +  +126x +126x +  +126x +  +  +1x +  +  +127x +  +  +127x +  +  +  +127x +127x +  +  +  +127x +  +  +  +127x +  +  +1x +1x +1x +1x + 
"use strict";
+ 
+let assert = require("assert").ok;
+let zlib = require("zlib");
+let util = require("util");
+ 
+let kMaxLength = require("buffer").kMaxLength;
+ 
+function Inflate(opts) {
+  Iif (!(this instanceof Inflate)) {
+    return new Inflate(opts);
+  }
+ 
+  if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) {
+    opts.chunkSize = zlib.Z_MIN_CHUNK;
+  }
+ 
+  zlib.Inflate.call(this, opts);
+ 
+  // Node 8 --> 9 compatibility check
+  this._offset = this._offset === undefined ? this._outOffset : this._offset;
+  this._buffer = this._buffer || this._outBuffer;
+ 
+  Eif (opts && opts.maxLength != null) {
+    this._maxLength = opts.maxLength;
+  }
+}
+ 
+function createInflate(opts) {
+  return new Inflate(opts);
+}
+ 
+function _close(engine, callback) {
+  Iif (callback) {
+    process.nextTick(callback);
+  }
+ 
+  // Caller may invoke .close after a zlib error (which will null _handle).
+  Iif (!engine._handle) {
+    return;
+  }
+ 
+  engine._handle.close();
+  engine._handle = null;
+}
+ 
+Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) {
+  Iif (typeof asyncCb === "function") {
+    return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb);
+  }
+ 
+  let self = this;
+ 
+  let availInBefore = chunk && chunk.length;
+  let availOutBefore = this._chunkSize - this._offset;
+  let leftToInflate = this._maxLength;
+  let inOff = 0;
+ 
+  let buffers = [];
+  let nread = 0;
+ 
+  let error;
+  this.on("error", function (err) {
+    error = err;
+  });
+ 
+  function handleChunk(availInAfter, availOutAfter) {
+    Iif (self._hadError) {
+      return;
+    }
+ 
+    let have = availOutBefore - availOutAfter;
+    assert(have >= 0, "have should not go down");
+ 
+    Eif (have > 0) {
+      let out = self._buffer.slice(self._offset, self._offset + have);
+      self._offset += have;
+ 
+      if (out.length > leftToInflate) {
+        out = out.slice(0, leftToInflate);
+      }
+ 
+      buffers.push(out);
+      nread += out.length;
+      leftToInflate -= out.length;
+ 
+      Eif (leftToInflate === 0) {
+        return false;
+      }
+    }
+ 
+    if (availOutAfter === 0 || self._offset >= self._chunkSize) {
+      availOutBefore = self._chunkSize;
+      self._offset = 0;
+      self._buffer = Buffer.allocUnsafe(self._chunkSize);
+    }
+ 
+    if (availOutAfter === 0) {
+      inOff += availInBefore - availInAfter;
+      availInBefore = availInAfter;
+ 
+      return true;
+    }
+ 
+    return false;
+  }
+ 
+  assert(this._handle, "zlib binding closed");
+  let res;
+  do {
+    res = this._handle.writeSync(
+      flushFlag,
+      chunk, // in
+      inOff, // in_off
+      availInBefore, // in_len
+      this._buffer, // out
+      this._offset, //out_off
+      availOutBefore
+    ); // out_len
+    // Node 8 --> 9 compatibility check
+    res = res || this._writeState;
+  } while (!this._hadError && handleChunk(res[0], res[1]));
+ 
+  if (this._hadError) {
+    throw error;
+  }
+ 
+  Iif (nread >= kMaxLength) {
+    _close(this);
+    throw new RangeError(
+      "Cannot create final Buffer. It would be larger than 0x" +
+        kMaxLength.toString(16) +
+        " bytes"
+    );
+  }
+ 
+  let buf = Buffer.concat(buffers, nread);
+  _close(this);
+ 
+  return buf;
+};
+ 
+util.inherits(Inflate, zlib.Inflate);
+ 
+function zlibBufferSync(engine, buffer) {
+  Iif (typeof buffer === "string") {
+    buffer = Buffer.from(buffer);
+  }
+  Iif (!(buffer instanceof Buffer)) {
+    throw new TypeError("Not a string or buffer");
+  }
+ 
+  let flushFlag = engine._finishFlushFlag;
+  Iif (flushFlag == null) {
+    flushFlag = zlib.Z_FINISH;
+  }
+ 
+  return engine._processChunk(buffer, flushFlag);
+}
+ 
+function inflateSync(buffer, opts) {
+  return zlibBufferSync(new Inflate(opts), buffer);
+}
+ 
+module.exports = exports = inflateSync;
+exports.Inflate = Inflate;
+exports.createInflate = createInflate;
+exports.inflateSync = inflateSync;
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov-report/sync-reader.js.html b/node_modules/pngjs/coverage/lcov-report/sync-reader.js.html new file mode 100644 index 0000000..576dd88 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov-report/sync-reader.js.html @@ -0,0 +1,215 @@ + + + + + + Code coverage report for sync-reader.js + + + + + + + + + +
+
+

All files sync-reader.js

+
+ +
+ 88.89% + Statements + 16/18 +
+ + +
+ 72.73% + Branches + 8/11 +
+ + +
+ 100% + Functions + 3/3 +
+ + +
+ 88.89% + Lines + 16/18 +
+ + +
+

+ Press n or j to go to the next uncovered block, b, p or k for the previous block. +

+
+
+

+
1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46  +  +1x +338x +338x +  +  +1x +9900x +  +  +  +  +  +  +1x +  +338x +9900x +  +9900x +  +  +  +  +9900x +  +9900x +  +9900x +  +9900x +  +  +  +  +  +338x +  +  +  +338x +13x +  +  + 
"use strict";
+ 
+let SyncReader = (module.exports = function (buffer) {
+  this._buffer = buffer;
+  this._reads = [];
+});
+ 
+SyncReader.prototype.read = function (length, callback) {
+  this._reads.push({
+    length: Math.abs(length), // if length < 0 then at most this length
+    allowLess: length < 0,
+    func: callback,
+  });
+};
+ 
+SyncReader.prototype.process = function () {
+  // as long as there is any data and read requests
+  while (this._reads.length > 0 && this._buffer.length) {
+    let read = this._reads[0];
+ 
+    Eif (
+      this._buffer.length &&
+      (this._buffer.length >= read.length || read.allowLess)
+    ) {
+      // ok there is any data so that we can satisfy this request
+      this._reads.shift(); // == read
+ 
+      let buf = this._buffer;
+ 
+      this._buffer = buf.slice(read.length);
+ 
+      read.func.call(this, buf.slice(0, read.length));
+    } else {
+      break;
+    }
+  }
+ 
+  Iif (this._reads.length > 0) {
+    return new Error("There are some read requests waitng on finished stream");
+  }
+ 
+  if (this._buffer.length > 0) {
+    return new Error("unrecognised content at end of stream");
+  }
+};
+ 
+ +
+
+ + + + + + + + + \ No newline at end of file diff --git a/node_modules/pngjs/coverage/lcov.info b/node_modules/pngjs/coverage/lcov.info new file mode 100644 index 0000000..1a7a647 --- /dev/null +++ b/node_modules/pngjs/coverage/lcov.info @@ -0,0 +1,2177 @@ +TN: +SF:lib\bitmapper.js +FN:7,(anonymous_0) +FN:11,(anonymous_1) +FN:25,(anonymous_2) +FN:39,(anonymous_3) +FN:52,(anonymous_4) +FN:66,(anonymous_5) +FN:70,(anonymous_6) +FN:80,(anonymous_7) +FN:90,(anonymous_8) +FN:99,(anonymous_9) +FN:107,bitRetriever +FN:111,split +FN:153,(anonymous_12) +FN:161,(anonymous_13) +FN:164,(anonymous_14) +FN:172,mapImage8Bit +FN:187,mapImageCustomBit +FN:202,(anonymous_17) +FN:229,(anonymous_18) +FNF:19 +FNH:17 +FNDA:0,(anonymous_0) +FNDA:313632,(anonymous_1) +FNDA:8192,(anonymous_2) +FNDA:1228160,(anonymous_3) +FNDA:272640,(anonymous_4) +FNDA:0,(anonymous_5) +FNDA:1193380,(anonymous_6) +FNDA:8192,(anonymous_7) +FNDA:24576,(anonymous_8) +FNDA:8192,(anonymous_9) +FNDA:209,bitRetriever +FNDA:334250,split +FNDA:1234340,(anonymous_12) +FNDA:8106,(anonymous_13) +FNDA:209,(anonymous_14) +FNDA:210,mapImage8Bit +FNDA:529,mapImageCustomBit +FNDA:335,(anonymous_17) +FNDA:2732114,(anonymous_18) +DA:3,1 +DA:5,1 +DA:12,313632 +DA:13,0 +DA:16,313632 +DA:17,313632 +DA:18,313632 +DA:19,313632 +DA:20,313632 +DA:26,8192 +DA:27,0 +DA:30,8192 +DA:31,8192 +DA:32,8192 +DA:33,8192 +DA:34,8192 +DA:40,1228160 +DA:41,0 +DA:44,1228160 +DA:45,1228160 +DA:46,1228160 +DA:47,1228160 +DA:53,272640 +DA:54,0 +DA:57,272640 +DA:58,272640 +DA:59,272640 +DA:60,272640 +DA:64,1 +DA:71,1193380 +DA:72,1193380 +DA:73,1193380 +DA:74,1193380 +DA:75,1193380 +DA:81,8192 +DA:82,8192 +DA:83,8192 +DA:84,8192 +DA:85,8192 +DA:91,24576 +DA:92,24576 +DA:93,24576 +DA:94,24576 +DA:100,8192 +DA:101,8192 +DA:102,8192 +DA:103,8192 +DA:108,209 +DA:109,209 +DA:112,334250 +DA:113,0 +DA:115,334250 +DA:116,334250 +DA:118,334250 +DA:120,0 +DA:122,149504 +DA:123,149504 +DA:124,149504 +DA:125,149504 +DA:127,49612 +DA:128,49612 +DA:129,49612 +DA:130,49612 +DA:132,2968 +DA:133,2968 +DA:134,2968 +DA:135,2968 +DA:136,2968 +DA:137,2968 +DA:139,132166 +DA:140,132166 +DA:141,132166 +DA:142,132166 +DA:143,132166 +DA:144,132166 +DA:145,132166 +DA:146,132166 +DA:147,132166 +DA:148,132166 +DA:152,209 +DA:154,1234340 +DA:155,334250 +DA:157,1234340 +DA:158,1234340 +DA:159,1234340 +DA:162,8106 +DA:165,209 +DA:166,0 +DA:174,210 +DA:175,210 +DA:176,210 +DA:177,210 +DA:178,7288 +DA:179,1822624 +DA:180,1822624 +DA:181,1822624 +DA:184,210 +DA:189,529 +DA:190,529 +DA:191,529 +DA:192,529 +DA:193,8106 +DA:194,1234340 +DA:195,1234340 +DA:196,1234340 +DA:198,8106 +DA:202,1 +DA:203,335 +DA:204,335 +DA:205,335 +DA:206,335 +DA:207,335 +DA:210,335 +DA:211,209 +DA:214,335 +DA:215,269 +DA:217,66 +DA:219,335 +DA:220,335 +DA:224,335 +DA:225,72 +DA:226,72 +DA:228,263 +DA:229,263 +DA:230,2732114 +DA:231,2732114 +DA:232,2732114 +DA:234,263 +DA:237,335 +DA:238,739 +DA:239,210 +DA:248,529 +DA:258,335 +DA:259,126 +DA:260,0 +DA:263,209 +DA:266,335 +LF:137 +LH:129 +BRDA:12,0,0,0 +BRDA:12,0,1,313632 +BRDA:26,1,0,0 +BRDA:26,1,1,8192 +BRDA:40,2,0,0 +BRDA:40,2,1,1228160 +BRDA:53,3,0,0 +BRDA:53,3,1,272640 +BRDA:112,4,0,0 +BRDA:112,4,1,334250 +BRDA:118,5,0,0 +BRDA:118,5,1,149504 +BRDA:118,5,2,49612 +BRDA:118,5,3,2968 +BRDA:118,5,4,132166 +BRDA:165,6,0,0 +BRDA:165,6,1,209 +BRDA:210,7,0,209 +BRDA:210,7,1,126 +BRDA:214,8,0,269 +BRDA:214,8,1,66 +BRDA:224,9,0,72 +BRDA:224,9,1,263 +BRDA:238,10,0,210 +BRDA:238,10,1,529 +BRDA:258,11,0,126 +BRDA:258,11,1,209 +BRDA:259,12,0,0 +BRDA:259,12,1,126 +BRF:29 +BRH:21 +end_of_record +TN: +SF:lib\bitpacker.js +FN:5,(anonymous_0) +FN:11,(anonymous_1) +FN:52,getRGBA +FNF:3 +FNH:2 +FNDA:325,(anonymous_0) +FNDA:325,(anonymous_1) +FNDA:0,getRGBA +DA:3,1 +DA:5,1 +DA:7,325 +DA:10,325 +DA:11,325 +DA:12,325 +DA:13,325 +DA:15,325 +DA:18,325 +DA:19,325 +DA:24,0 +DA:26,0 +DA:27,0 +DA:28,0 +DA:29,0 +DA:31,0 +DA:32,0 +DA:33,0 +DA:34,0 +DA:36,0 +DA:38,0 +DA:39,0 +DA:41,0 +DA:42,0 +DA:43,0 +DA:45,0 +DA:46,0 +DA:48,0 +DA:49,0 +DA:56,0 +DA:57,0 +DA:59,0 +DA:60,0 +DA:61,0 +DA:62,0 +DA:63,0 +DA:65,0 +DA:66,0 +DA:67,0 +DA:68,0 +DA:70,0 +DA:71,0 +DA:72,0 +DA:73,0 +DA:74,0 +DA:76,0 +DA:77,0 +DA:78,0 +DA:79,0 +DA:81,0 +DA:88,0 +DA:89,0 +DA:90,0 +DA:91,0 +DA:95,0 +DA:99,0 +DA:105,0 +DA:108,0 +DA:109,0 +DA:110,0 +DA:112,0 +DA:115,0 +DA:116,0 +DA:117,0 +DA:118,0 +DA:119,0 +DA:120,0 +DA:123,0 +DA:124,0 +DA:125,0 +DA:126,0 +DA:127,0 +DA:130,0 +DA:134,0 +DA:135,0 +DA:136,0 +DA:137,0 +DA:138,0 +DA:141,0 +DA:142,0 +DA:143,0 +DA:146,0 +DA:149,0 +DA:152,0 +DA:153,0 +DA:157,0 +LF:86 +LH:10 +BRDA:10,0,0,325 +BRDA:10,0,1,0 +BRDA:18,1,0,325 +BRDA:18,1,1,0 +BRDA:18,2,0,325 +BRDA:18,2,1,0 +BRDA:18,2,2,0 +BRDA:24,3,0,0 +BRDA:24,3,1,0 +BRDA:28,4,0,0 +BRDA:28,4,1,0 +BRDA:28,5,0,0 +BRDA:28,5,1,0 +BRDA:32,6,0,0 +BRDA:32,6,1,0 +BRDA:41,7,0,0 +BRDA:41,7,1,0 +BRDA:42,8,0,0 +BRDA:42,8,1,0 +BRDA:45,9,0,0 +BRDA:45,9,1,0 +BRDA:48,10,0,0 +BRDA:48,10,1,0 +BRDA:57,11,0,0 +BRDA:57,11,1,0 +BRDA:57,11,2,0 +BRDA:57,11,3,0 +BRDA:57,11,4,0 +BRDA:88,12,0,0 +BRDA:88,12,1,0 +BRDA:89,13,0,0 +BRDA:89,13,1,0 +BRDA:112,14,0,0 +BRDA:112,14,1,0 +BRDA:112,14,2,0 +BRDA:112,14,3,0 +BRDA:112,14,4,0 +BRDA:115,15,0,0 +BRDA:115,15,1,0 +BRDA:119,16,0,0 +BRDA:119,16,1,0 +BRDA:126,17,0,0 +BRDA:126,17,1,0 +BRDA:135,18,0,0 +BRDA:135,18,1,0 +BRDA:137,19,0,0 +BRDA:137,19,1,0 +BRDA:142,20,0,0 +BRDA:142,20,1,0 +BRF:49 +BRH:3 +end_of_record +TN: +SF:lib\chunkstream.js +FN:6,(anonymous_0) +FN:20,(anonymous_1) +FN:28,(anonymous_2) +FN:41,(anonymous_3) +FN:67,(anonymous_4) +FN:90,(anonymous_5) +FN:98,(anonymous_6) +FN:110,(anonymous_7) +FN:132,(anonymous_8) +FN:163,(anonymous_9) +FNF:10 +FNH:10 +FNDA:529,(anonymous_0) +FNDA:13318,(anonymous_1) +FNDA:13318,(anonymous_2) +FNDA:943,(anonymous_3) +FNDA:311,(anonymous_4) +FNDA:311,(anonymous_5) +FNDA:327,(anonymous_6) +FNDA:741,(anonymous_7) +FNDA:12408,(anonymous_8) +FNDA:14263,(anonymous_9) +DA:3,1 +DA:4,1 +DA:6,1 +DA:7,529 +DA:9,529 +DA:10,529 +DA:12,529 +DA:13,529 +DA:15,529 +DA:16,529 +DA:18,1 +DA:20,1 +DA:21,13318 +DA:27,13318 +DA:29,13318 +DA:32,13318 +DA:33,0 +DA:35,0 +DA:41,1 +DA:42,943 +DA:43,0 +DA:44,0 +DA:48,943 +DA:49,943 +DA:51,0 +DA:54,943 +DA:55,943 +DA:57,943 +DA:60,943 +DA:61,346 +DA:64,943 +DA:67,1 +DA:68,311 +DA:69,0 +DA:72,311 +DA:75,311 +DA:76,0 +DA:80,311 +DA:81,309 +DA:83,2 +DA:84,2 +DA:88,1 +DA:90,1 +DA:91,311 +DA:92,3 +DA:95,311 +DA:98,1 +DA:99,327 +DA:100,0 +DA:103,327 +DA:104,327 +DA:105,327 +DA:107,327 +DA:110,1 +DA:112,741 +DA:115,741 +DA:118,741 +DA:119,568 +DA:120,568 +DA:122,568 +DA:125,173 +DA:126,173 +DA:128,173 +DA:132,1 +DA:133,12408 +DA:135,12408 +DA:136,12408 +DA:137,12408 +DA:140,12408 +DA:141,12617 +DA:142,12617 +DA:144,12617 +DA:145,12617 +DA:148,12617 +DA:149,11863 +DA:154,12408 +DA:155,532 +DA:158,12408 +DA:160,12408 +DA:163,1 +DA:164,14263 +DA:166,14263 +DA:167,15656 +DA:170,15656 +DA:171,741 +DA:172,14915 +DA:175,12408 +DA:179,2507 +DA:183,14263 +DA:184,2 +DA:187,0 +LF:91 +LH:82 +BRDA:32,0,0,0 +BRDA:32,0,1,13318 +BRDA:32,1,0,13318 +BRDA:32,1,1,10215 +BRDA:42,2,0,0 +BRDA:42,2,1,943 +BRDA:48,3,0,943 +BRDA:48,3,1,0 +BRDA:51,4,0,0 +BRDA:51,4,1,0 +BRDA:60,5,0,346 +BRDA:60,5,1,597 +BRDA:60,6,0,943 +BRDA:60,6,1,929 +BRDA:64,7,0,943 +BRDA:64,7,1,929 +BRDA:68,8,0,0 +BRDA:68,8,1,311 +BRDA:75,9,0,0 +BRDA:75,9,1,311 +BRDA:80,10,0,309 +BRDA:80,10,1,2 +BRDA:91,11,0,3 +BRDA:91,11,1,308 +BRDA:99,12,0,0 +BRDA:99,12,1,327 +BRDA:118,13,0,568 +BRDA:118,13,1,173 +BRDA:148,14,0,11863 +BRDA:148,14,1,754 +BRDA:154,15,0,532 +BRDA:154,15,1,11876 +BRDA:166,16,0,27412 +BRDA:166,16,1,15708 +BRDA:166,16,2,15671 +BRDA:170,17,0,741 +BRDA:170,17,1,14915 +BRDA:172,18,0,12408 +BRDA:172,18,1,2507 +BRDA:183,19,0,2 +BRDA:183,19,1,14261 +BRDA:183,20,0,14263 +BRDA:183,20,1,14213 +BRF:43 +BRH:35 +end_of_record +TN: +SF:lib\constants.js +FNF:0 +FNH:0 +DA:3,1 +LF:1 +LH:1 +BRF:0 +BRH:0 +end_of_record +TN: +SF:lib\crc.js +FN:5,(anonymous_0) +FN:19,(anonymous_1) +FN:23,(anonymous_2) +FN:30,(anonymous_3) +FN:34,(anonymous_4) +FNF:5 +FNH:5 +FNDA:1,(anonymous_0) +FNDA:2461,(anonymous_1) +FNDA:4839,(anonymous_2) +FNDA:2195,(anonymous_3) +FNDA:1592,(anonymous_4) +DA:3,1 +DA:5,1 +DA:6,1 +DA:7,256 +DA:8,256 +DA:9,2048 +DA:10,1024 +DA:12,1024 +DA:15,256 +DA:19,1 +DA:20,2461 +DA:23,1 +DA:24,4839 +DA:25,823519 +DA:27,4839 +DA:30,1 +DA:31,2195 +DA:34,1 +DA:35,1592 +DA:36,1592 +DA:37,305287 +DA:39,1592 +LF:22 +LH:22 +BRDA:9,0,0,1024 +BRDA:9,0,1,1024 +BRF:2 +BRH:2 +end_of_record +TN: +SF:lib\filter-pack.js +FN:5,filterNone +FN:11,filterSumNone +FN:21,filterSub +FN:30,filterSumSub +FN:42,filterUp +FN:51,filterSumUp +FN:64,filterAvg +FN:74,filterSumAvg +FN:87,filterPaeth +FN:99,filterSumPaeth +FN:130,(anonymous_10) +FNF:11 +FNH:11 +FNDA:44,filterNone +FNDA:10490,filterSumNone +FNDA:637,filterSub +FNDA:10490,filterSumSub +FNDA:2670,filterUp +FNDA:10490,filterSumUp +FNDA:208,filterAvg +FNDA:10490,filterSumAvg +FNDA:6931,filterPaeth +FNDA:10490,filterSumPaeth +FNDA:325,(anonymous_10) +DA:3,1 +DA:6,44 +DA:7,5136 +DA:12,10490 +DA:13,10490 +DA:15,10490 +DA:16,2776736 +DA:18,10490 +DA:22,637 +DA:23,107032 +DA:24,107032 +DA:26,107032 +DA:31,10490 +DA:32,10490 +DA:33,2776736 +DA:34,2776736 +DA:36,2776736 +DA:39,10490 +DA:43,2670 +DA:44,581344 +DA:45,581344 +DA:47,581344 +DA:52,10490 +DA:53,10490 +DA:54,10490 +DA:55,2776736 +DA:56,2776736 +DA:58,2776736 +DA:61,10490 +DA:65,208 +DA:66,204096 +DA:67,204096 +DA:68,204096 +DA:70,204096 +DA:75,10490 +DA:76,10490 +DA:77,2776736 +DA:78,2776736 +DA:79,2776736 +DA:81,2776736 +DA:84,10490 +DA:88,6931 +DA:89,1879128 +DA:90,1879128 +DA:92,1879128 +DA:93,1879128 +DA:95,1879128 +DA:100,10490 +DA:101,10490 +DA:102,2776736 +DA:103,2776736 +DA:105,2776736 +DA:106,2776736 +DA:108,2776736 +DA:111,10490 +DA:114,1 +DA:122,1 +DA:130,1 +DA:132,325 +DA:133,325 +DA:134,0 +DA:135,0 +DA:137,0 +DA:140,325 +DA:141,0 +DA:143,325 +DA:144,325 +DA:145,325 +DA:146,325 +DA:148,325 +DA:150,325 +DA:151,10490 +DA:153,10490 +DA:155,10490 +DA:156,52450 +DA:157,52450 +DA:158,35370 +DA:159,35370 +DA:164,10490 +DA:165,10490 +DA:166,10490 +DA:167,10490 +DA:168,10490 +DA:170,325 +LF:84 +LH:80 +BRDA:23,0,0,104484 +BRDA:23,0,1,2548 +BRDA:33,1,0,2734776 +BRDA:33,1,1,41960 +BRDA:44,2,0,581344 +BRDA:44,2,1,0 +BRDA:55,3,0,2734120 +BRDA:55,3,1,42616 +BRDA:66,4,0,203264 +BRDA:66,4,1,832 +BRDA:67,5,0,204096 +BRDA:67,5,1,0 +BRDA:77,6,0,2734776 +BRDA:77,6,1,41960 +BRDA:78,7,0,2734120 +BRDA:78,7,1,42616 +BRDA:89,8,0,1851404 +BRDA:89,8,1,27724 +BRDA:90,9,0,1879128 +BRDA:90,9,1,0 +BRDA:92,10,0,1851404 +BRDA:92,10,1,27724 +BRDA:92,11,0,1879128 +BRDA:92,11,1,1879128 +BRDA:102,12,0,2734776 +BRDA:102,12,1,41960 +BRDA:103,13,0,2734120 +BRDA:103,13,1,42616 +BRDA:105,14,0,2693460 +BRDA:105,14,1,83276 +BRDA:105,15,0,2776736 +BRDA:105,15,1,2734120 +BRDA:132,16,0,325 +BRDA:132,16,1,0 +BRDA:132,17,0,325 +BRDA:132,17,1,1 +BRDA:134,18,0,0 +BRDA:134,18,1,0 +BRDA:140,19,0,0 +BRDA:140,19,1,325 +BRDA:151,20,0,10490 +BRDA:151,20,1,0 +BRDA:157,21,0,35370 +BRDA:157,21,1,17080 +BRF:44 +BRH:36 +end_of_record +TN: +SF:lib\filter-parse-async.js +FN:7,(anonymous_0) +FN:14,(anonymous_1) +FN:17,(anonymous_2) +FNF:3 +FNH:3 +FNDA:176,(anonymous_0) +FNDA:9057,(anonymous_1) +FNDA:173,(anonymous_2) +DA:3,1 +DA:4,1 +DA:5,1 +DA:7,1 +DA:8,176 +DA:10,176 +DA:11,176 +DA:12,176 +DA:15,9057 +DA:18,173 +DA:22,176 +DA:24,1 +LF:12 +LH:12 +BRF:0 +BRH:0 +end_of_record +TN: +SF:lib\filter-parse-sync.js +FN:6,(anonymous_0) +FN:11,(anonymous_1) +FN:14,(anonymous_2) +FNF:3 +FNH:3 +FNDA:162,(anonymous_0) +FNDA:6337,(anonymous_1) +FNDA:162,(anonymous_2) +DA:3,1 +DA:4,1 +DA:6,1 +DA:7,162 +DA:8,162 +DA:9,162 +DA:12,6337 +DA:17,162 +DA:18,162 +DA:20,162 +LF:10 +LH:10 +BRF:0 +BRH:0 +end_of_record +TN: +SF:lib\filter-parse.js +FN:6,getByteWidth +FN:14,(anonymous_1) +FN:57,(anonymous_2) +FN:64,(anonymous_3) +FN:79,(anonymous_4) +FN:93,(anonymous_5) +FN:111,(anonymous_6) +FN:130,(anonymous_7) +FNF:8 +FNH:8 +FNDA:742,getByteWidth +FNDA:338,(anonymous_1) +FNDA:338,(anonymous_2) +FNDA:1939,(anonymous_3) +FNDA:800,(anonymous_4) +FNDA:172,(anonymous_5) +FNDA:4165,(anonymous_6) +FNDA:15394,(anonymous_7) +DA:3,1 +DA:4,1 +DA:7,742 +DA:8,742 +DA:9,531 +DA:11,742 +DA:14,1 +DA:15,338 +DA:16,338 +DA:17,338 +DA:18,338 +DA:19,338 +DA:21,338 +DA:22,338 +DA:23,338 +DA:25,338 +DA:26,338 +DA:27,338 +DA:28,72 +DA:29,72 +DA:30,476 +DA:37,266 +DA:48,338 +DA:49,127 +DA:50,211 +DA:51,66 +DA:53,145 +DA:57,1 +DA:58,338 +DA:64,1 +DA:69,1939 +DA:70,1939 +DA:72,1939 +DA:73,3563504 +DA:74,3563504 +DA:75,3563504 +DA:79,1 +DA:84,800 +DA:86,800 +DA:87,330256 +DA:88,330256 +DA:89,330256 +DA:93,1 +DA:98,172 +DA:99,172 +DA:100,172 +DA:102,172 +DA:103,9952 +DA:104,9952 +DA:105,9952 +DA:106,9952 +DA:107,9952 +DA:111,1 +DA:116,4165 +DA:117,4165 +DA:118,4165 +DA:120,4165 +DA:121,1152544 +DA:122,1152544 +DA:123,1152544 +DA:124,1152544 +DA:125,1152544 +DA:126,1152544 +DA:130,1 +DA:131,15394 +DA:133,15394 +DA:134,15394 +DA:136,15394 +DA:137,8318 +DA:139,7076 +DA:141,7076 +DA:143,1939 +DA:144,1939 +DA:146,800 +DA:147,800 +DA:149,172 +DA:150,172 +DA:152,4165 +DA:153,4165 +DA:155,0 +DA:159,15394 +DA:161,15394 +DA:162,15394 +DA:163,739 +DA:164,739 +DA:165,739 +DA:167,14655 +DA:170,15394 +DA:172,15059 +DA:174,335 +DA:175,335 +LF:91 +LH:90 +BRDA:8,0,0,531 +BRDA:8,0,1,211 +BRDA:27,1,0,72 +BRDA:27,1,1,266 +BRDA:48,2,0,127 +BRDA:48,2,1,211 +BRDA:50,3,0,66 +BRDA:50,3,1,145 +BRDA:74,4,0,3557696 +BRDA:74,4,1,5808 +BRDA:88,5,0,330000 +BRDA:88,5,1,256 +BRDA:104,6,0,9536 +BRDA:104,6,1,416 +BRDA:105,7,0,9554 +BRDA:105,7,1,398 +BRDA:122,8,0,1152288 +BRDA:122,8,1,256 +BRDA:123,9,0,1137296 +BRDA:123,9,1,15248 +BRDA:124,10,0,1137048 +BRDA:124,10,1,15496 +BRDA:124,11,0,1152544 +BRDA:124,11,1,1137296 +BRDA:136,12,0,8318 +BRDA:136,12,1,7076 +BRDA:141,13,0,1939 +BRDA:141,13,1,800 +BRDA:141,13,2,172 +BRDA:141,13,3,4165 +BRDA:141,13,4,0 +BRDA:162,14,0,739 +BRDA:162,14,1,14655 +BRDA:170,15,0,15059 +BRDA:170,15,1,335 +BRF:35 +BRH:34 +end_of_record +TN: +SF:lib\format-normaliser.js +FN:3,dePalette +FN:22,replaceTransparentColor +FN:49,scaleDepth +FN:66,(anonymous_3) +FNF:4 +FNH:4 +FNDA:131,dePalette +FNDA:12,replaceTransparentColor +FNDA:106,scaleDepth +FNDA:335,(anonymous_3) +DA:4,131 +DA:6,131 +DA:7,4912 +DA:8,1418436 +DA:10,1418436 +DA:11,0 +DA:14,1418436 +DA:15,5673744 +DA:17,1418436 +DA:23,12 +DA:24,12 +DA:25,384 +DA:26,12288 +DA:28,12288 +DA:29,6144 +DA:30,2762 +DA:32,6144 +DA:37,2718 +DA:39,12288 +DA:40,5480 +DA:41,21920 +DA:44,12288 +DA:50,106 +DA:51,106 +DA:52,106 +DA:54,106 +DA:55,3392 +DA:56,108544 +DA:57,434176 +DA:61,108544 +DA:66,1 +DA:67,335 +DA:68,335 +DA:69,335 +DA:70,335 +DA:71,335 +DA:72,335 +DA:74,335 +DA:76,335 +DA:78,131 +DA:80,204 +DA:81,12 +DA:84,204 +DA:86,106 +DA:87,66 +DA:89,106 +DA:92,335 +LF:47 +LH:46 +BRDA:10,0,0,0 +BRDA:10,0,1,1418436 +BRDA:28,1,0,6144 +BRDA:28,1,1,6144 +BRDA:29,2,0,2762 +BRDA:29,2,1,3382 +BRDA:32,3,0,2718 +BRDA:32,3,1,3426 +BRDA:33,4,0,6144 +BRDA:33,4,1,2718 +BRDA:33,4,2,2718 +BRDA:39,5,0,5480 +BRDA:39,5,1,6808 +BRDA:76,6,0,131 +BRDA:76,6,1,204 +BRDA:80,7,0,12 +BRDA:80,7,1,192 +BRDA:84,8,0,106 +BRDA:84,8,1,98 +BRDA:86,9,0,66 +BRDA:86,9,1,40 +BRF:21 +BRH:20 +end_of_record +TN: +SF:lib\interlace.js +FN:52,(anonymous_0) +FN:83,(anonymous_1) +FN:84,(anonymous_2) +FNF:3 +FNH:3 +FNDA:144,(anonymous_0) +FNDA:72,(anonymous_1) +FNDA:324850,(anonymous_2) +DA:14,1 +DA:52,1 +DA:53,144 +DA:54,144 +DA:55,144 +DA:56,144 +DA:57,144 +DA:58,144 +DA:59,1008 +DA:60,1008 +DA:61,1008 +DA:62,1008 +DA:63,1556 +DA:64,672 +DA:66,884 +DA:69,1008 +DA:70,1360 +DA:71,552 +DA:73,808 +DA:76,1008 +DA:77,952 +DA:80,144 +DA:83,1 +DA:84,72 +DA:85,324850 +DA:87,324850 +DA:89,324850 +DA:91,324850 +DA:93,324850 +LF:29 +LH:29 +BRDA:63,0,0,672 +BRDA:63,0,1,884 +BRDA:70,1,0,552 +BRDA:70,1,1,808 +BRDA:76,2,0,952 +BRDA:76,2,1,56 +BRDA:76,3,0,1008 +BRDA:76,3,1,980 +BRF:8 +BRH:8 +end_of_record +TN: +SF:lib\packer-async.js +FN:8,(anonymous_0) +FN:20,(anonymous_1) +FN:36,(anonymous_2) +FN:43,(anonymous_3) +FNF:4 +FNH:4 +FNDA:353,(anonymous_0) +FNDA:325,(anonymous_1) +FNDA:652,(anonymous_2) +FNDA:325,(anonymous_3) +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:8,1 +DA:9,353 +DA:11,353 +DA:13,353 +DA:14,353 +DA:16,353 +DA:18,1 +DA:20,1 +DA:22,325 +DA:23,325 +DA:25,325 +DA:26,290 +DA:29,325 +DA:32,325 +DA:34,325 +DA:37,652 +DA:41,325 +DA:44,325 +DA:45,325 +DA:49,325 +LF:24 +LH:24 +BRDA:11,0,0,353 +BRDA:11,0,1,0 +BRDA:25,1,0,290 +BRDA:25,1,1,35 +BRF:4 +BRH:3 +end_of_record +TN: +SF:lib\packer-sync.js +FN:11,(anonymous_0) +FNF:1 +FNH:0 +FNDA:0,(anonymous_0) +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,0 +DA:8,1 +DA:9,1 +DA:11,1 +DA:12,0 +DA:13,0 +DA:18,0 +DA:20,0 +DA:22,0 +DA:25,0 +DA:28,0 +DA:30,0 +DA:31,0 +DA:34,0 +DA:41,0 +DA:45,0 +DA:47,0 +DA:48,0 +DA:50,0 +DA:53,0 +DA:55,0 +LF:24 +LH:6 +BRDA:5,0,0,0 +BRDA:5,0,1,1 +BRDA:12,1,0,0 +BRDA:12,1,1,0 +BRDA:18,2,0,0 +BRDA:18,2,1,0 +BRDA:30,3,0,0 +BRDA:30,3,1,0 +BRDA:47,4,0,0 +BRDA:47,4,1,0 +BRDA:47,5,0,0 +BRDA:47,5,1,0 +BRF:12 +BRH:1 +end_of_record +TN: +SF:lib\packer.js +FN:9,(anonymous_0) +FN:64,(anonymous_1) +FN:72,(anonymous_2) +FN:76,(anonymous_3) +FN:86,(anonymous_4) +FN:104,(anonymous_5) +FN:110,(anonymous_6) +FN:123,(anonymous_7) +FN:127,(anonymous_8) +FNF:9 +FNH:9 +FNDA:353,(anonymous_0) +FNDA:353,(anonymous_1) +FNDA:353,(anonymous_2) +FNDA:325,(anonymous_3) +FNDA:1592,(anonymous_4) +FNDA:290,(anonymous_5) +FNDA:325,(anonymous_6) +FNDA:652,(anonymous_7) +FNDA:325,(anonymous_8) +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:9,1 +DA:10,353 +DA:12,353 +DA:13,353 +DA:15,353 +DA:17,353 +DA:19,353 +DA:20,353 +DA:22,353 +DA:26,353 +DA:31,353 +DA:39,0 +DA:43,353 +DA:51,0 +DA:57,353 +DA:58,0 +DA:64,1 +DA:65,353 +DA:72,1 +DA:73,353 +DA:76,1 +DA:78,325 +DA:81,325 +DA:82,325 +DA:83,325 +DA:86,1 +DA:87,1592 +DA:88,1592 +DA:90,1592 +DA:91,1592 +DA:93,1592 +DA:94,1267 +DA:97,1592 +DA:101,1592 +DA:104,1 +DA:105,290 +DA:106,290 +DA:107,290 +DA:110,1 +DA:111,325 +DA:112,325 +DA:113,325 +DA:114,325 +DA:115,325 +DA:116,325 +DA:117,325 +DA:118,325 +DA:120,325 +DA:123,1 +DA:124,652 +DA:127,1 +DA:128,325 +LF:57 +LH:54 +BRDA:12,0,0,353 +BRDA:12,0,1,353 +BRDA:14,1,0,0 +BRDA:14,1,1,353 +BRDA:16,2,0,0 +BRDA:16,2,1,353 +BRDA:18,3,0,0 +BRDA:18,3,1,353 +BRDA:19,4,0,353 +BRDA:19,4,1,353 +BRDA:20,5,0,353 +BRDA:20,5,1,353 +BRDA:23,6,0,0 +BRDA:23,6,1,353 +BRDA:27,7,0,0 +BRDA:27,7,1,353 +BRDA:31,8,0,0 +BRDA:31,8,1,353 +BRDA:43,9,0,0 +BRDA:43,9,1,353 +BRDA:57,10,0,0 +BRDA:57,10,1,353 +BRDA:57,11,0,353 +BRDA:57,11,1,0 +BRDA:87,12,0,1267 +BRDA:87,12,1,325 +BRDA:93,13,0,1267 +BRDA:93,13,1,325 +BRF:28 +BRH:19 +end_of_record +TN: +SF:lib\paeth-predictor.js +FN:3,paethPredictor +FNF:1 +FNH:1 +FNDA:5808408,paethPredictor +DA:3,1 +DA:4,5808408 +DA:5,5808408 +DA:6,5808408 +DA:7,5808408 +DA:9,5808408 +DA:10,5156742 +DA:12,651666 +DA:13,539893 +DA:15,111773 +LF:10 +LH:10 +BRDA:9,0,0,5156742 +BRDA:9,0,1,651666 +BRDA:9,1,0,5808408 +BRDA:9,1,1,5231305 +BRDA:12,2,0,539893 +BRDA:12,2,1,111773 +BRF:6 +BRH:6 +end_of_record +TN: +SF:lib\parser-async.js +FN:11,(anonymous_0) +FN:33,(anonymous_1) +FN:49,(anonymous_2) +FN:55,(anonymous_3) +FN:79,(anonymous_4) +FN:89,(anonymous_5) +FN:109,(anonymous_6) +FN:116,(anonymous_7) +FN:120,(anonymous_8) +FN:124,(anonymous_9) +FN:128,(anonymous_10) +FN:134,(anonymous_11) +FN:147,(anonymous_12) +FNF:13 +FNH:11 +FNDA:353,(anonymous_0) +FNDA:14,(anonymous_1) +FNDA:0,(anonymous_2) +FNDA:741,(anonymous_3) +FNDA:0,(anonymous_4) +FNDA:487,(anonymous_5) +FNDA:176,(anonymous_6) +FNDA:7,(anonymous_7) +FNDA:77,(anonymous_8) +FNDA:15,(anonymous_9) +FNDA:174,(anonymous_10) +FNDA:173,(anonymous_11) +FNDA:173,(anonymous_12) +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:8,1 +DA:9,1 +DA:11,1 +DA:12,353 +DA:14,353 +DA:26,353 +DA:27,353 +DA:29,353 +DA:31,1 +DA:33,1 +DA:34,14 +DA:36,14 +DA:38,14 +DA:40,14 +DA:41,1 +DA:44,14 +DA:45,2 +DA:49,2 +DA:52,14 +DA:55,1 +DA:56,741 +DA:57,174 +DA:58,36 +DA:60,36 +DA:61,36 +DA:63,36 +DA:66,138 +DA:72,138 +DA:73,138 +DA:75,138 +DA:76,138 +DA:78,138 +DA:79,138 +DA:80,0 +DA:81,0 +DA:84,0 +DA:86,138 +DA:88,138 +DA:89,138 +DA:90,487 +DA:91,0 +DA:94,487 +DA:95,0 +DA:98,487 +DA:100,487 +DA:103,138 +DA:106,741 +DA:109,1 +DA:110,176 +DA:111,176 +DA:113,176 +DA:116,1 +DA:117,7 +DA:120,1 +DA:121,77 +DA:124,1 +DA:125,15 +DA:128,1 +DA:131,174 +DA:134,1 +DA:135,173 +DA:136,0 +DA:139,173 +DA:140,1 +DA:143,172 +DA:147,1 +DA:148,173 +DA:149,0 +DA:154,173 +DA:155,173 +DA:157,173 +DA:158,173 +DA:160,0 +DA:161,0 +DA:164,173 +LF:80 +LH:71 +BRDA:40,0,0,1 +BRDA:40,0,1,13 +BRDA:40,1,0,14 +BRDA:40,1,1,1 +BRDA:44,2,0,2 +BRDA:44,2,1,12 +BRDA:56,3,0,174 +BRDA:56,3,1,567 +BRDA:57,4,0,36 +BRDA:57,4,1,138 +BRDA:80,5,0,0 +BRDA:80,5,1,0 +BRDA:90,6,0,0 +BRDA:90,6,1,487 +BRDA:94,7,0,0 +BRDA:94,7,1,487 +BRDA:135,8,0,0 +BRDA:135,8,1,173 +BRDA:139,9,0,1 +BRDA:139,9,1,172 +BRDA:148,10,0,0 +BRDA:148,10,1,173 +BRF:22 +BRH:16 +end_of_record +TN: +SF:lib\parser-sync.js +FN:15,(anonymous_0) +FN:23,handleError +FN:28,handleMetaData +FN:32,handleTransColor +FN:36,handlePalette +FN:40,handleSimpleTransparency +FN:45,handleGamma +FN:50,handleInflateData +FNF:8 +FNH:8 +FNDA:176,(anonymous_0) +FNDA:13,handleError +FNDA:165,handleMetaData +FNDA:5,handleTransColor +FNDA:73,handlePalette +FNDA:12,handleSimpleTransparency +FNDA:147,handleGamma +FNDA:492,handleInflateData +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,0 +DA:9,1 +DA:10,1 +DA:11,1 +DA:12,1 +DA:13,1 +DA:15,1 +DA:16,176 +DA:17,0 +DA:24,13 +DA:29,165 +DA:33,5 +DA:37,73 +DA:41,12 +DA:46,147 +DA:49,176 +DA:51,492 +DA:54,176 +DA:56,176 +DA:67,176 +DA:68,176 +DA:70,176 +DA:71,13 +DA:75,163 +DA:76,163 +DA:79,163 +DA:80,36 +DA:83,127 +DA:84,127 +DA:85,127 +DA:90,162 +DA:92,162 +DA:93,0 +DA:96,162 +DA:97,162 +DA:99,162 +DA:100,162 +DA:102,162 +DA:104,162 +DA:105,162 +DA:107,162 +LF:45 +LH:42 +BRDA:6,0,0,0 +BRDA:6,0,1,1 +BRDA:16,1,0,0 +BRDA:16,1,1,176 +BRDA:70,2,0,13 +BRDA:70,2,1,163 +BRDA:79,3,0,36 +BRDA:79,3,1,127 +BRDA:92,4,0,0 +BRDA:92,4,1,162 +BRDA:92,5,0,162 +BRDA:92,5,1,162 +BRDA:105,6,0,162 +BRDA:105,6,1,17 +BRF:14 +BRH:11 +end_of_record +TN: +SF:lib\parser.js +FN:6,(anonymous_0) +FN:36,(anonymous_1) +FN:39,(anonymous_2) +FN:43,(anonymous_3) +FN:55,(anonymous_4) +FN:93,(anonymous_5) +FN:97,(anonymous_6) +FN:101,(anonymous_7) +FN:116,(anonymous_8) +FN:119,(anonymous_9) +FN:183,(anonymous_10) +FN:186,(anonymous_11) +FN:201,(anonymous_12) +FN:205,(anonymous_13) +FN:241,(anonymous_14) +FN:244,(anonymous_15) +FN:251,(anonymous_16) +FN:258,(anonymous_17) +FN:278,(anonymous_18) +FN:281,(anonymous_19) +FNF:20 +FNH:20 +FNDA:529,(anonymous_0) +FNDA:163,(anonymous_1) +FNDA:529,(anonymous_2) +FNDA:365,(anonymous_3) +FNDA:2461,(anonymous_4) +FNDA:256,(anonymous_5) +FNDA:2195,(anonymous_6) +FNDA:2195,(anonymous_7) +FNDA:351,(anonymous_8) +FNDA:351,(anonymous_9) +FNDA:135,(anonymous_10) +FNDA:135,(anonymous_11) +FNDA:27,(anonymous_12) +FNDA:27,(anonymous_13) +FNDA:296,(anonymous_14) +FNDA:296,(anonymous_15) +FNDA:1233,(anonymous_16) +FNDA:1233,(anonymous_17) +FNDA:336,(anonymous_18) +FNDA:336,(anonymous_19) +DA:3,1 +DA:4,1 +DA:6,1 +DA:7,529 +DA:8,529 +DA:10,529 +DA:11,529 +DA:12,529 +DA:15,529 +DA:16,529 +DA:18,529 +DA:19,529 +DA:20,529 +DA:21,529 +DA:22,529 +DA:23,529 +DA:24,529 +DA:26,529 +DA:27,529 +DA:28,529 +DA:29,529 +DA:30,529 +DA:31,529 +DA:32,529 +DA:33,529 +DA:34,529 +DA:35,529 +DA:36,529 +DA:39,1 +DA:40,529 +DA:43,1 +DA:44,365 +DA:46,365 +DA:47,2867 +DA:48,13 +DA:49,13 +DA:52,352 +DA:55,1 +DA:57,2461 +DA:60,2461 +DA:61,2461 +DA:62,2461 +DA:63,9844 +DA:69,2461 +DA:73,2461 +DA:74,0 +DA:75,0 +DA:78,2461 +DA:79,2461 +DA:81,2461 +DA:82,2205 +DA:85,256 +DA:86,0 +DA:87,0 +DA:90,256 +DA:93,1 +DA:94,256 +DA:97,1 +DA:98,2195 +DA:101,1 +DA:102,2195 +DA:103,2195 +DA:106,2195 +DA:107,4 +DA:108,4 +DA:111,2191 +DA:112,1855 +DA:116,1 +DA:117,351 +DA:119,1 +DA:120,351 +DA:122,351 +DA:123,351 +DA:124,351 +DA:125,351 +DA:126,351 +DA:127,351 +DA:128,351 +DA:135,351 +DA:142,6 +DA:143,6 +DA:145,345 +DA:146,4 +DA:147,4 +DA:149,341 +DA:150,0 +DA:151,0 +DA:153,341 +DA:154,0 +DA:155,0 +DA:157,341 +DA:158,0 +DA:159,0 +DA:162,341 +DA:164,341 +DA:166,341 +DA:168,341 +DA:180,341 +DA:183,1 +DA:184,135 +DA:186,1 +DA:187,135 +DA:189,135 +DA:192,135 +DA:193,7350 +DA:196,135 +DA:198,135 +DA:201,1 +DA:202,27 +DA:203,27 +DA:205,1 +DA:206,27 +DA:209,27 +DA:210,15 +DA:211,0 +DA:212,0 +DA:214,15 +DA:215,0 +DA:216,0 +DA:218,15 +DA:219,529 +DA:221,15 +DA:226,27 +DA:228,6 +DA:230,27 +DA:231,6 +DA:238,27 +DA:241,1 +DA:242,296 +DA:244,1 +DA:245,296 +DA:246,296 +DA:248,296 +DA:251,1 +DA:252,1233 +DA:253,337 +DA:254,337 +DA:256,1233 +DA:258,1 +DA:259,1233 +DA:261,1233 +DA:265,0 +DA:268,1233 +DA:269,1233 +DA:271,1233 +DA:272,173 +DA:274,1060 +DA:278,1 +DA:279,336 +DA:281,1 +DA:282,336 +DA:284,336 +DA:285,336 +DA:287,336 +DA:288,173 +LF:155 +LH:140 +BRDA:36,0,0,529 +BRDA:36,0,1,176 +BRDA:47,1,0,13 +BRDA:47,1,1,2854 +BRDA:73,2,0,0 +BRDA:73,2,1,2461 +BRDA:73,3,0,2461 +BRDA:73,3,1,351 +BRDA:81,4,0,2205 +BRDA:81,4,1,256 +BRDA:85,5,0,0 +BRDA:85,5,1,256 +BRDA:106,6,0,4 +BRDA:106,6,1,2191 +BRDA:106,7,0,2195 +BRDA:106,7,1,2195 +BRDA:111,8,0,1855 +BRDA:111,8,1,336 +BRDA:135,9,0,6 +BRDA:135,9,1,345 +BRDA:136,10,0,351 +BRDA:136,10,1,219 +BRDA:136,10,2,132 +BRDA:136,10,3,101 +BRDA:136,10,4,72 +BRDA:145,11,0,4 +BRDA:145,11,1,341 +BRDA:149,12,0,0 +BRDA:149,12,1,341 +BRDA:153,13,0,0 +BRDA:153,13,1,341 +BRDA:157,14,0,0 +BRDA:157,14,1,341 +BRDA:157,15,0,341 +BRDA:157,15,1,72 +BRDA:209,16,0,15 +BRDA:209,16,1,12 +BRDA:210,17,0,0 +BRDA:210,17,1,15 +BRDA:214,18,0,0 +BRDA:214,18,1,15 +BRDA:226,19,0,6 +BRDA:226,19,1,21 +BRDA:230,20,0,6 +BRDA:230,20,1,21 +BRDA:252,21,0,337 +BRDA:252,21,1,896 +BRDA:261,22,0,0 +BRDA:261,22,1,1233 +BRDA:262,23,0,1233 +BRDA:262,23,1,131 +BRDA:271,24,0,173 +BRDA:271,24,1,1060 +BRDA:287,25,0,173 +BRDA:287,25,1,163 +BRF:55 +BRH:47 +end_of_record +TN: +SF:lib\png-sync.js +FN:6,(anonymous_0) +FN:10,(anonymous_1) +FNF:2 +FNH:1 +FNDA:176,(anonymous_0) +FNDA:0,(anonymous_1) +DA:3,1 +DA:4,1 +DA:6,1 +DA:7,176 +DA:10,1 +DA:11,0 +LF:6 +LH:5 +BRDA:7,0,0,176 +BRDA:7,0,1,176 +BRF:2 +BRH:2 +end_of_record +TN: +SF:lib\png.js +FN:9,(anonymous_0) +FN:38,(anonymous_1) +FN:54,(anonymous_2) +FN:61,(anonymous_3) +FN:69,(anonymous_4) +FN:73,(anonymous_5) +FN:80,(anonymous_6) +FN:94,(anonymous_7) +FN:99,(anonymous_8) +FN:103,(anonymous_9) +FN:110,(anonymous_10) +FN:114,(anonymous_11) +FN:120,(anonymous_12) +FN:160,(anonymous_13) +FN:175,(anonymous_14) +FN:192,(anonymous_15) +FNF:16 +FNH:9 +FNDA:353,(anonymous_0) +FNDA:173,(anonymous_1) +FNDA:325,(anonymous_2) +FNDA:325,(anonymous_3) +FNDA:0,(anonymous_4) +FNDA:0,(anonymous_5) +FNDA:0,(anonymous_6) +FNDA:412,(anonymous_7) +FNDA:175,(anonymous_8) +FNDA:174,(anonymous_9) +FNDA:149,(anonymous_10) +FNDA:378,(anonymous_11) +FNDA:0,(anonymous_12) +FNDA:0,(anonymous_13) +FNDA:0,(anonymous_14) +FNDA:0,(anonymous_15) +DA:3,1 +DA:4,1 +DA:5,1 +DA:6,1 +DA:7,1 +DA:9,1 +DA:10,353 +DA:12,353 +DA:15,353 +DA:16,353 +DA:18,353 +DA:23,353 +DA:24,0 +DA:27,353 +DA:28,353 +DA:30,353 +DA:32,353 +DA:33,353 +DA:34,353 +DA:35,353 +DA:36,353 +DA:39,173 +DA:40,173 +DA:44,353 +DA:45,353 +DA:46,353 +DA:47,353 +DA:48,353 +DA:50,1 +DA:52,1 +DA:54,1 +DA:55,325 +DA:56,0 +DA:57,0 +DA:60,325 +DA:62,325 +DA:66,325 +DA:69,1 +DA:70,0 +DA:73,0 +DA:74,0 +DA:76,0 +DA:77,0 +DA:80,0 +DA:81,0 +DA:83,0 +DA:86,0 +DA:87,0 +DA:90,0 +DA:91,0 +DA:94,1 +DA:95,412 +DA:96,412 +DA:99,1 +DA:100,175 +DA:103,1 +DA:104,174 +DA:105,174 +DA:107,174 +DA:110,1 +DA:111,149 +DA:114,1 +DA:115,378 +DA:116,0 +DA:120,1 +DA:124,0 +DA:125,0 +DA:126,0 +DA:127,0 +DA:128,0 +DA:129,0 +DA:132,0 +DA:138,0 +DA:141,0 +DA:147,0 +DA:150,0 +DA:151,0 +DA:160,1 +DA:171,0 +DA:172,0 +DA:175,1 +DA:176,0 +DA:177,0 +DA:178,0 +DA:179,0 +DA:181,0 +DA:182,0 +DA:183,0 +DA:184,0 +DA:188,0 +DA:192,1 +DA:193,0 +LF:92 +LH:52 +BRDA:12,0,0,353 +BRDA:12,0,1,348 +BRDA:19,1,0,1 +BRDA:19,1,1,352 +BRDA:19,2,0,353 +BRDA:19,2,1,1 +BRDA:23,3,0,0 +BRDA:23,3,1,353 +BRDA:23,4,0,353 +BRDA:23,4,1,0 +BRDA:55,5,0,0 +BRDA:55,5,1,325 +BRDA:55,6,0,325 +BRDA:55,6,1,325 +BRDA:70,7,0,0 +BRDA:70,7,1,0 +BRDA:115,8,0,0 +BRDA:115,8,1,378 +BRDA:115,9,0,378 +BRDA:115,9,1,378 +BRDA:132,10,0,0 +BRDA:132,10,1,0 +BRDA:133,11,0,0 +BRDA:133,11,1,0 +BRDA:133,11,2,0 +BRDA:133,11,3,0 +BRDA:141,12,0,0 +BRDA:141,12,1,0 +BRDA:142,13,0,0 +BRDA:142,13,1,0 +BRDA:142,13,2,0 +BRDA:142,13,3,0 +BRDA:176,14,0,0 +BRDA:176,14,1,0 +BRF:34 +BRH:14 +end_of_record +TN: +SF:lib\sync-inflate.js +FN:9,Inflate +FN:29,createInflate +FN:33,_close +FN:47,(anonymous_3) +FN:63,(anonymous_4) +FN:67,handleChunk +FN:145,zlibBufferSync +FN:161,inflateSync +FNF:8 +FNH:7 +FNDA:127,Inflate +FNDA:0,createInflate +FNDA:126,_close +FNDA:127,(anonymous_3) +FNDA:1,(anonymous_4) +FNDA:126,handleChunk +FNDA:127,zlibBufferSync +FNDA:127,inflateSync +DA:3,1 +DA:4,1 +DA:5,1 +DA:7,1 +DA:10,127 +DA:11,0 +DA:14,127 +DA:15,9 +DA:18,127 +DA:21,127 +DA:22,127 +DA:24,127 +DA:25,127 +DA:30,0 +DA:34,126 +DA:35,0 +DA:39,126 +DA:40,0 +DA:43,126 +DA:44,126 +DA:47,1 +DA:48,127 +DA:49,0 +DA:52,127 +DA:54,127 +DA:55,127 +DA:56,127 +DA:57,127 +DA:59,127 +DA:60,127 +DA:63,127 +DA:64,1 +DA:68,126 +DA:69,0 +DA:72,126 +DA:73,126 +DA:75,126 +DA:76,126 +DA:77,126 +DA:79,126 +DA:80,9 +DA:83,126 +DA:84,126 +DA:85,126 +DA:87,126 +DA:88,126 +DA:92,0 +DA:93,0 +DA:94,0 +DA:95,0 +DA:98,0 +DA:99,0 +DA:100,0 +DA:102,0 +DA:105,0 +DA:108,127 +DA:110,127 +DA:111,127 +DA:121,127 +DA:124,127 +DA:125,1 +DA:128,126 +DA:129,0 +DA:130,0 +DA:137,126 +DA:138,126 +DA:140,126 +DA:143,1 +DA:146,127 +DA:147,0 +DA:149,127 +DA:150,0 +DA:153,127 +DA:154,127 +DA:155,0 +DA:158,127 +DA:162,127 +DA:165,1 +DA:166,1 +DA:167,1 +DA:168,1 +LF:81 +LH:61 +BRDA:10,0,0,0 +BRDA:10,0,1,127 +BRDA:14,1,0,9 +BRDA:14,1,1,118 +BRDA:14,2,0,127 +BRDA:14,2,1,127 +BRDA:21,3,0,127 +BRDA:21,3,1,0 +BRDA:22,4,0,127 +BRDA:22,4,1,127 +BRDA:24,5,0,127 +BRDA:24,5,1,0 +BRDA:24,6,0,127 +BRDA:24,6,1,127 +BRDA:34,7,0,0 +BRDA:34,7,1,126 +BRDA:39,8,0,0 +BRDA:39,8,1,126 +BRDA:48,9,0,0 +BRDA:48,9,1,127 +BRDA:54,10,0,127 +BRDA:54,10,1,127 +BRDA:68,11,0,0 +BRDA:68,11,1,126 +BRDA:75,12,0,126 +BRDA:75,12,1,0 +BRDA:79,13,0,9 +BRDA:79,13,1,117 +BRDA:87,14,0,126 +BRDA:87,14,1,0 +BRDA:92,15,0,0 +BRDA:92,15,1,0 +BRDA:92,16,0,0 +BRDA:92,16,1,0 +BRDA:98,17,0,0 +BRDA:98,17,1,0 +BRDA:122,18,0,127 +BRDA:122,18,1,126 +BRDA:121,19,0,127 +BRDA:121,19,1,127 +BRDA:124,20,0,1 +BRDA:124,20,1,126 +BRDA:128,21,0,0 +BRDA:128,21,1,126 +BRDA:146,22,0,0 +BRDA:146,22,1,127 +BRDA:149,23,0,0 +BRDA:149,23,1,127 +BRDA:154,24,0,0 +BRDA:154,24,1,127 +BRF:50 +BRH:31 +end_of_record +TN: +SF:lib\sync-reader.js +FN:3,(anonymous_0) +FN:8,(anonymous_1) +FN:16,(anonymous_2) +FNF:3 +FNH:3 +FNDA:338,(anonymous_0) +FNDA:9900,(anonymous_1) +FNDA:338,(anonymous_2) +DA:3,1 +DA:4,338 +DA:5,338 +DA:8,1 +DA:9,9900 +DA:16,1 +DA:18,338 +DA:19,9900 +DA:21,9900 +DA:26,9900 +DA:28,9900 +DA:30,9900 +DA:32,9900 +DA:34,0 +DA:38,338 +DA:39,0 +DA:42,338 +DA:43,13 +LF:18 +LH:16 +BRDA:18,0,0,10238 +BRDA:18,0,1,9900 +BRDA:21,1,0,9900 +BRDA:21,1,1,0 +BRDA:22,2,0,9900 +BRDA:22,2,1,9900 +BRDA:22,2,2,0 +BRDA:38,3,0,0 +BRDA:38,3,1,338 +BRDA:42,4,0,13 +BRDA:42,4,1,325 +BRF:11 +BRH:8 +end_of_record diff --git a/node_modules/pngjs/lib/bitmapper.js b/node_modules/pngjs/lib/bitmapper.js new file mode 100644 index 0000000..18378a0 --- /dev/null +++ b/node_modules/pngjs/lib/bitmapper.js @@ -0,0 +1,267 @@ +"use strict"; + +let interlaceUtils = require("./interlace"); + +let pixelBppMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, data, pxPos, rawPos) { + if (rawPos === data.length) { + throw new Error("Ran out of data"); + } + + let pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = 0xff; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function (pxData, data, pxPos, rawPos) { + if (rawPos + 1 >= data.length) { + throw new Error("Ran out of data"); + } + + let pixel = data[rawPos]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = data[rawPos + 1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, data, pxPos, rawPos) { + if (rawPos + 2 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = 0xff; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, data, pxPos, rawPos) { + if (rawPos + 3 >= data.length) { + throw new Error("Ran out of data"); + } + + pxData[pxPos] = data[rawPos]; + pxData[pxPos + 1] = data[rawPos + 1]; + pxData[pxPos + 2] = data[rawPos + 2]; + pxData[pxPos + 3] = data[rawPos + 3]; + }, +]; + +let pixelBppCustomMapper = [ + // 0 - dummy entry + function () {}, + + // 1 - L + // 0: 0, 1: 0, 2: 0, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = maxBit; + }, + + // 2 - LA + // 0: 0, 1: 0, 2: 0, 3: 1 + function (pxData, pixelData, pxPos) { + let pixel = pixelData[0]; + pxData[pxPos] = pixel; + pxData[pxPos + 1] = pixel; + pxData[pxPos + 2] = pixel; + pxData[pxPos + 3] = pixelData[1]; + }, + + // 3 - RGB + // 0: 0, 1: 1, 2: 2, 3: 0xff + function (pxData, pixelData, pxPos, maxBit) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = maxBit; + }, + + // 4 - RGBA + // 0: 0, 1: 1, 2: 2, 3: 3 + function (pxData, pixelData, pxPos) { + pxData[pxPos] = pixelData[0]; + pxData[pxPos + 1] = pixelData[1]; + pxData[pxPos + 2] = pixelData[2]; + pxData[pxPos + 3] = pixelData[3]; + }, +]; + +function bitRetriever(data, depth) { + let leftOver = []; + let i = 0; + + function split() { + if (i === data.length) { + throw new Error("Ran out of data"); + } + let byte = data[i]; + i++; + let byte8, byte7, byte6, byte5, byte4, byte3, byte2, byte1; + switch (depth) { + default: + throw new Error("unrecognised depth"); + case 16: + byte2 = data[i]; + i++; + leftOver.push((byte << 8) + byte2); + break; + case 4: + byte2 = byte & 0x0f; + byte1 = byte >> 4; + leftOver.push(byte1, byte2); + break; + case 2: + byte4 = byte & 3; + byte3 = (byte >> 2) & 3; + byte2 = (byte >> 4) & 3; + byte1 = (byte >> 6) & 3; + leftOver.push(byte1, byte2, byte3, byte4); + break; + case 1: + byte8 = byte & 1; + byte7 = (byte >> 1) & 1; + byte6 = (byte >> 2) & 1; + byte5 = (byte >> 3) & 1; + byte4 = (byte >> 4) & 1; + byte3 = (byte >> 5) & 1; + byte2 = (byte >> 6) & 1; + byte1 = (byte >> 7) & 1; + leftOver.push(byte1, byte2, byte3, byte4, byte5, byte6, byte7, byte8); + break; + } + } + + return { + get: function (count) { + while (leftOver.length < count) { + split(); + } + let returner = leftOver.slice(0, count); + leftOver = leftOver.slice(count); + return returner; + }, + resetAfterLine: function () { + leftOver.length = 0; + }, + end: function () { + if (i !== data.length) { + throw new Error("extra data found"); + } + }, + }; +} + +function mapImage8Bit(image, pxData, getPxPos, bpp, data, rawPos) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pxPos = getPxPos(x, y, imagePass); + pixelBppMapper[bpp](pxData, data, pxPos, rawPos); + rawPos += bpp; //eslint-disable-line no-param-reassign + } + } + return rawPos; +} + +function mapImageCustomBit(image, pxData, getPxPos, bpp, bits, maxBit) { + // eslint-disable-line max-params + let imageWidth = image.width; + let imageHeight = image.height; + let imagePass = image.index; + for (let y = 0; y < imageHeight; y++) { + for (let x = 0; x < imageWidth; x++) { + let pixelData = bits.get(bpp); + let pxPos = getPxPos(x, y, imagePass); + pixelBppCustomMapper[bpp](pxData, pixelData, pxPos, maxBit); + } + bits.resetAfterLine(); + } +} + +exports.dataToBitMap = function (data, bitmapInfo) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let depth = bitmapInfo.depth; + let bpp = bitmapInfo.bpp; + let interlace = bitmapInfo.interlace; + let bits; + + if (depth !== 8) { + bits = bitRetriever(data, depth); + } + let pxData; + if (depth <= 8) { + pxData = Buffer.alloc(width * height * 4); + } else { + pxData = new Uint16Array(width * height * 4); + } + let maxBit = Math.pow(2, depth) - 1; + let rawPos = 0; + let images; + let getPxPos; + + if (interlace) { + images = interlaceUtils.getImagePasses(width, height); + getPxPos = interlaceUtils.getInterlaceIterator(width, height); + } else { + let nonInterlacedPxPos = 0; + getPxPos = function () { + let returner = nonInterlacedPxPos; + nonInterlacedPxPos += 4; + return returner; + }; + images = [{ width: width, height: height }]; + } + + for (let imageIndex = 0; imageIndex < images.length; imageIndex++) { + if (depth === 8) { + rawPos = mapImage8Bit( + images[imageIndex], + pxData, + getPxPos, + bpp, + data, + rawPos + ); + } else { + mapImageCustomBit( + images[imageIndex], + pxData, + getPxPos, + bpp, + bits, + maxBit + ); + } + } + if (depth === 8) { + if (rawPos !== data.length) { + throw new Error("extra data found"); + } + } else { + bits.end(); + } + + return pxData; +}; diff --git a/node_modules/pngjs/lib/bitpacker.js b/node_modules/pngjs/lib/bitpacker.js new file mode 100644 index 0000000..d7a4e65 --- /dev/null +++ b/node_modules/pngjs/lib/bitpacker.js @@ -0,0 +1,158 @@ +"use strict"; + +let constants = require("./constants"); + +module.exports = function (dataIn, width, height, options) { + let outHasAlpha = + [constants.COLORTYPE_COLOR_ALPHA, constants.COLORTYPE_ALPHA].indexOf( + options.colorType + ) !== -1; + if (options.colorType === options.inputColorType) { + let bigEndian = (function () { + let buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true /* littleEndian */); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] !== 256; + })(); + // If no need to convert to grayscale and alpha is present/absent in both, take a fast route + if (options.bitDepth === 8 || (options.bitDepth === 16 && bigEndian)) { + return dataIn; + } + } + + // map to a UInt16 array if data is 16bit, fix endianness below + let data = options.bitDepth !== 16 ? dataIn : new Uint16Array(dataIn.buffer); + + let maxValue = 255; + let inBpp = constants.COLORTYPE_TO_BPP_MAP[options.inputColorType]; + if (inBpp === 4 && !options.inputHasAlpha) { + inBpp = 3; + } + let outBpp = constants.COLORTYPE_TO_BPP_MAP[options.colorType]; + if (options.bitDepth === 16) { + maxValue = 65535; + outBpp *= 2; + } + let outData = Buffer.alloc(width * height * outBpp); + + let inIndex = 0; + let outIndex = 0; + + let bgColor = options.bgColor || {}; + if (bgColor.red === undefined) { + bgColor.red = maxValue; + } + if (bgColor.green === undefined) { + bgColor.green = maxValue; + } + if (bgColor.blue === undefined) { + bgColor.blue = maxValue; + } + + function getRGBA() { + let red; + let green; + let blue; + let alpha = maxValue; + switch (options.inputColorType) { + case constants.COLORTYPE_COLOR_ALPHA: + alpha = data[inIndex + 3]; + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_COLOR: + red = data[inIndex]; + green = data[inIndex + 1]; + blue = data[inIndex + 2]; + break; + case constants.COLORTYPE_ALPHA: + alpha = data[inIndex + 1]; + red = data[inIndex]; + green = red; + blue = red; + break; + case constants.COLORTYPE_GRAYSCALE: + red = data[inIndex]; + green = red; + blue = red; + break; + default: + throw new Error( + "input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + + if (options.inputHasAlpha) { + if (!outHasAlpha) { + alpha /= maxValue; + red = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.red + alpha * red), 0), + maxValue + ); + green = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.green + alpha * green), 0), + maxValue + ); + blue = Math.min( + Math.max(Math.round((1 - alpha) * bgColor.blue + alpha * blue), 0), + maxValue + ); + } + } + return { red: red, green: green, blue: blue, alpha: alpha }; + } + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let rgba = getRGBA(data, inIndex); + + switch (options.colorType) { + case constants.COLORTYPE_COLOR_ALPHA: + case constants.COLORTYPE_COLOR: + if (options.bitDepth === 8) { + outData[outIndex] = rgba.red; + outData[outIndex + 1] = rgba.green; + outData[outIndex + 2] = rgba.blue; + if (outHasAlpha) { + outData[outIndex + 3] = rgba.alpha; + } + } else { + outData.writeUInt16BE(rgba.red, outIndex); + outData.writeUInt16BE(rgba.green, outIndex + 2); + outData.writeUInt16BE(rgba.blue, outIndex + 4); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 6); + } + } + break; + case constants.COLORTYPE_ALPHA: + case constants.COLORTYPE_GRAYSCALE: { + // Convert to grayscale and alpha + let grayscale = (rgba.red + rgba.green + rgba.blue) / 3; + if (options.bitDepth === 8) { + outData[outIndex] = grayscale; + if (outHasAlpha) { + outData[outIndex + 1] = rgba.alpha; + } + } else { + outData.writeUInt16BE(grayscale, outIndex); + if (outHasAlpha) { + outData.writeUInt16BE(rgba.alpha, outIndex + 2); + } + } + break; + } + default: + throw new Error("unrecognised color Type " + options.colorType); + } + + inIndex += inBpp; + outIndex += outBpp; + } + } + + return outData; +}; diff --git a/node_modules/pngjs/lib/chunkstream.js b/node_modules/pngjs/lib/chunkstream.js new file mode 100644 index 0000000..95b46d4 --- /dev/null +++ b/node_modules/pngjs/lib/chunkstream.js @@ -0,0 +1,189 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); + +let ChunkStream = (module.exports = function () { + Stream.call(this); + + this._buffers = []; + this._buffered = 0; + + this._reads = []; + this._paused = false; + + this._encoding = "utf8"; + this.writable = true; +}); +util.inherits(ChunkStream, Stream); + +ChunkStream.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); + + process.nextTick( + function () { + this._process(); + + // its paused and there is not enought data then ask for more + if (this._paused && this._reads && this._reads.length > 0) { + this._paused = false; + + this.emit("drain"); + } + }.bind(this) + ); +}; + +ChunkStream.prototype.write = function (data, encoding) { + if (!this.writable) { + this.emit("error", new Error("Stream not writable")); + return false; + } + + let dataBuffer; + if (Buffer.isBuffer(data)) { + dataBuffer = data; + } else { + dataBuffer = Buffer.from(data, encoding || this._encoding); + } + + this._buffers.push(dataBuffer); + this._buffered += dataBuffer.length; + + this._process(); + + // ok if there are no more read requests + if (this._reads && this._reads.length === 0) { + this._paused = true; + } + + return this.writable && !this._paused; +}; + +ChunkStream.prototype.end = function (data, encoding) { + if (data) { + this.write(data, encoding); + } + + this.writable = false; + + // already destroyed + if (!this._buffers) { + return; + } + + // enqueue or handle end + if (this._buffers.length === 0) { + this._end(); + } else { + this._buffers.push(null); + this._process(); + } +}; + +ChunkStream.prototype.destroySoon = ChunkStream.prototype.end; + +ChunkStream.prototype._end = function () { + if (this._reads.length > 0) { + this.emit("error", new Error("Unexpected end of input")); + } + + this.destroy(); +}; + +ChunkStream.prototype.destroy = function () { + if (!this._buffers) { + return; + } + + this.writable = false; + this._reads = null; + this._buffers = null; + + this.emit("close"); +}; + +ChunkStream.prototype._processReadAllowingLess = function (read) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + // first we need to peek into first buffer + let smallerBuf = this._buffers[0]; + + // ok there is more data than we need + if (smallerBuf.length > read.length) { + this._buffered -= read.length; + this._buffers[0] = smallerBuf.slice(read.length); + + read.func.call(this, smallerBuf.slice(0, read.length)); + } else { + // ok this is less than maximum length so use it all + this._buffered -= smallerBuf.length; + this._buffers.shift(); // == smallerBuf + + read.func.call(this, smallerBuf); + } +}; + +ChunkStream.prototype._processRead = function (read) { + this._reads.shift(); // == read + + let pos = 0; + let count = 0; + let data = Buffer.alloc(read.length); + + // create buffer for all data + while (pos < read.length) { + let buf = this._buffers[count++]; + let len = Math.min(buf.length, read.length - pos); + + buf.copy(data, pos, 0, len); + pos += len; + + // last buffer wasn't used all so just slice it and leave + if (len !== buf.length) { + this._buffers[--count] = buf.slice(len); + } + } + + // remove all used buffers + if (count > 0) { + this._buffers.splice(0, count); + } + + this._buffered -= read.length; + + read.func.call(this, data); +}; + +ChunkStream.prototype._process = function () { + try { + // as long as there is any data and read requests + while (this._buffered > 0 && this._reads && this._reads.length > 0) { + let read = this._reads[0]; + + // read any data (but no more than length) + if (read.allowLess) { + this._processReadAllowingLess(read); + } else if (this._buffered >= read.length) { + // ok we can meet some expectations + + this._processRead(read); + } else { + // not enought data to satisfy first request in queue + // so we need to wait for more + break; + } + } + + if (this._buffers && !this.writable) { + this._end(); + } + } catch (ex) { + this.emit("error", ex); + } +}; diff --git a/node_modules/pngjs/lib/constants.js b/node_modules/pngjs/lib/constants.js new file mode 100644 index 0000000..21fdad6 --- /dev/null +++ b/node_modules/pngjs/lib/constants.js @@ -0,0 +1,32 @@ +"use strict"; + +module.exports = { + PNG_SIGNATURE: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], + + TYPE_IHDR: 0x49484452, + TYPE_IEND: 0x49454e44, + TYPE_IDAT: 0x49444154, + TYPE_PLTE: 0x504c5445, + TYPE_tRNS: 0x74524e53, // eslint-disable-line camelcase + TYPE_gAMA: 0x67414d41, // eslint-disable-line camelcase + + // color-type bits + COLORTYPE_GRAYSCALE: 0, + COLORTYPE_PALETTE: 1, + COLORTYPE_COLOR: 2, + COLORTYPE_ALPHA: 4, // e.g. grayscale and alpha + + // color-type combinations + COLORTYPE_PALETTE_COLOR: 3, + COLORTYPE_COLOR_ALPHA: 6, + + COLORTYPE_TO_BPP_MAP: { + 0: 1, + 2: 3, + 3: 1, + 4: 2, + 6: 4, + }, + + GAMMA_DIVISION: 100000, +}; diff --git a/node_modules/pngjs/lib/crc.js b/node_modules/pngjs/lib/crc.js new file mode 100644 index 0000000..950ec8a --- /dev/null +++ b/node_modules/pngjs/lib/crc.js @@ -0,0 +1,40 @@ +"use strict"; + +let crcTable = []; + +(function () { + for (let i = 0; i < 256; i++) { + let currentCrc = i; + for (let j = 0; j < 8; j++) { + if (currentCrc & 1) { + currentCrc = 0xedb88320 ^ (currentCrc >>> 1); + } else { + currentCrc = currentCrc >>> 1; + } + } + crcTable[i] = currentCrc; + } +})(); + +let CrcCalculator = (module.exports = function () { + this._crc = -1; +}); + +CrcCalculator.prototype.write = function (data) { + for (let i = 0; i < data.length; i++) { + this._crc = crcTable[(this._crc ^ data[i]) & 0xff] ^ (this._crc >>> 8); + } + return true; +}; + +CrcCalculator.prototype.crc32 = function () { + return this._crc ^ -1; +}; + +CrcCalculator.crc32 = function (buf) { + let crc = -1; + for (let i = 0; i < buf.length; i++) { + crc = crcTable[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8); + } + return crc ^ -1; +}; diff --git a/node_modules/pngjs/lib/filter-pack.js b/node_modules/pngjs/lib/filter-pack.js new file mode 100644 index 0000000..32c85c4 --- /dev/null +++ b/node_modules/pngjs/lib/filter-pack.js @@ -0,0 +1,171 @@ +"use strict"; + +let paethPredictor = require("./paeth-predictor"); + +function filterNone(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + rawData[rawPos + x] = pxData[pxPos + x]; + } +} + +function filterSumNone(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + + for (let i = pxPos; i < length; i++) { + sum += Math.abs(pxData[i]); + } + return sum; +} + +function filterSub(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + rawData[rawPos + x] = val; + } +} + +function filterSumSub(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let val = pxData[pxPos + x] - left; + + sum += Math.abs(val); + } + + return sum; +} + +function filterUp(pxData, pxPos, byteWidth, rawData, rawPos) { + for (let x = 0; x < byteWidth; x++) { + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - up; + + rawData[rawPos + x] = val; + } +} + +function filterSumUp(pxData, pxPos, byteWidth) { + let sum = 0; + let length = pxPos + byteWidth; + for (let x = pxPos; x < length; x++) { + let up = pxPos > 0 ? pxData[x - byteWidth] : 0; + let val = pxData[x] - up; + + sum += Math.abs(val); + } + + return sum; +} + +function filterAvg(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + rawData[rawPos + x] = val; + } +} + +function filterSumAvg(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let val = pxData[pxPos + x] - ((left + up) >> 1); + + sum += Math.abs(val); + } + + return sum; +} + +function filterPaeth(pxData, pxPos, byteWidth, rawData, rawPos, bpp) { + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + rawData[rawPos + x] = val; + } +} + +function filterSumPaeth(pxData, pxPos, byteWidth, bpp) { + let sum = 0; + for (let x = 0; x < byteWidth; x++) { + let left = x >= bpp ? pxData[pxPos + x - bpp] : 0; + let up = pxPos > 0 ? pxData[pxPos + x - byteWidth] : 0; + let upleft = + pxPos > 0 && x >= bpp ? pxData[pxPos + x - (byteWidth + bpp)] : 0; + let val = pxData[pxPos + x] - paethPredictor(left, up, upleft); + + sum += Math.abs(val); + } + + return sum; +} + +let filters = { + 0: filterNone, + 1: filterSub, + 2: filterUp, + 3: filterAvg, + 4: filterPaeth, +}; + +let filterSums = { + 0: filterSumNone, + 1: filterSumSub, + 2: filterSumUp, + 3: filterSumAvg, + 4: filterSumPaeth, +}; + +module.exports = function (pxData, width, height, options, bpp) { + let filterTypes; + if (!("filterType" in options) || options.filterType === -1) { + filterTypes = [0, 1, 2, 3, 4]; + } else if (typeof options.filterType === "number") { + filterTypes = [options.filterType]; + } else { + throw new Error("unrecognised filter types"); + } + + if (options.bitDepth === 16) { + bpp *= 2; + } + let byteWidth = width * bpp; + let rawPos = 0; + let pxPos = 0; + let rawData = Buffer.alloc((byteWidth + 1) * height); + + let sel = filterTypes[0]; + + for (let y = 0; y < height; y++) { + if (filterTypes.length > 1) { + // find best filter for this line (with lowest sum of values) + let min = Infinity; + + for (let i = 0; i < filterTypes.length; i++) { + let sum = filterSums[filterTypes[i]](pxData, pxPos, byteWidth, bpp); + if (sum < min) { + sel = filterTypes[i]; + min = sum; + } + } + } + + rawData[rawPos] = sel; + rawPos++; + filters[sel](pxData, pxPos, byteWidth, rawData, rawPos, bpp); + rawPos += byteWidth; + pxPos += byteWidth; + } + return rawData; +}; diff --git a/node_modules/pngjs/lib/filter-parse-async.js b/node_modules/pngjs/lib/filter-parse-async.js new file mode 100644 index 0000000..832b86c --- /dev/null +++ b/node_modules/pngjs/lib/filter-parse-async.js @@ -0,0 +1,24 @@ +"use strict"; + +let util = require("util"); +let ChunkStream = require("./chunkstream"); +let Filter = require("./filter-parse"); + +let FilterAsync = (module.exports = function (bitmapInfo) { + ChunkStream.call(this); + + let buffers = []; + let that = this; + this._filter = new Filter(bitmapInfo, { + read: this.read.bind(this), + write: function (buffer) { + buffers.push(buffer); + }, + complete: function () { + that.emit("complete", Buffer.concat(buffers)); + }, + }); + + this._filter.start(); +}); +util.inherits(FilterAsync, ChunkStream); diff --git a/node_modules/pngjs/lib/filter-parse-sync.js b/node_modules/pngjs/lib/filter-parse-sync.js new file mode 100644 index 0000000..6924d16 --- /dev/null +++ b/node_modules/pngjs/lib/filter-parse-sync.js @@ -0,0 +1,21 @@ +"use strict"; + +let SyncReader = require("./sync-reader"); +let Filter = require("./filter-parse"); + +exports.process = function (inBuffer, bitmapInfo) { + let outBuffers = []; + let reader = new SyncReader(inBuffer); + let filter = new Filter(bitmapInfo, { + read: reader.read.bind(reader), + write: function (bufferPart) { + outBuffers.push(bufferPart); + }, + complete: function () {}, + }); + + filter.start(); + reader.process(); + + return Buffer.concat(outBuffers); +}; diff --git a/node_modules/pngjs/lib/filter-parse.js b/node_modules/pngjs/lib/filter-parse.js new file mode 100644 index 0000000..3a32e5e --- /dev/null +++ b/node_modules/pngjs/lib/filter-parse.js @@ -0,0 +1,177 @@ +"use strict"; + +let interlaceUtils = require("./interlace"); +let paethPredictor = require("./paeth-predictor"); + +function getByteWidth(width, bpp, depth) { + let byteWidth = width * bpp; + if (depth !== 8) { + byteWidth = Math.ceil(byteWidth / (8 / depth)); + } + return byteWidth; +} + +let Filter = (module.exports = function (bitmapInfo, dependencies) { + let width = bitmapInfo.width; + let height = bitmapInfo.height; + let interlace = bitmapInfo.interlace; + let bpp = bitmapInfo.bpp; + let depth = bitmapInfo.depth; + + this.read = dependencies.read; + this.write = dependencies.write; + this.complete = dependencies.complete; + + this._imageIndex = 0; + this._images = []; + if (interlace) { + let passes = interlaceUtils.getImagePasses(width, height); + for (let i = 0; i < passes.length; i++) { + this._images.push({ + byteWidth: getByteWidth(passes[i].width, bpp, depth), + height: passes[i].height, + lineIndex: 0, + }); + } + } else { + this._images.push({ + byteWidth: getByteWidth(width, bpp, depth), + height: height, + lineIndex: 0, + }); + } + + // when filtering the line we look at the pixel to the left + // the spec also says it is done on a byte level regardless of the number of pixels + // so if the depth is byte compatible (8 or 16) we subtract the bpp in order to compare back + // a pixel rather than just a different byte part. However if we are sub byte, we ignore. + if (depth === 8) { + this._xComparison = bpp; + } else if (depth === 16) { + this._xComparison = bpp * 2; + } else { + this._xComparison = 1; + } +}); + +Filter.prototype.start = function () { + this.read( + this._images[this._imageIndex].byteWidth + 1, + this._reverseFilterLine.bind(this) + ); +}; + +Filter.prototype._unFilterType1 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f1Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + unfilteredLine[x] = rawByte + f1Left; + } +}; + +Filter.prototype._unFilterType2 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f2Up = lastLine ? lastLine[x] : 0; + unfilteredLine[x] = rawByte + f2Up; + } +}; + +Filter.prototype._unFilterType3 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f3Up = lastLine ? lastLine[x] : 0; + let f3Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f3Add = Math.floor((f3Left + f3Up) / 2); + unfilteredLine[x] = rawByte + f3Add; + } +}; + +Filter.prototype._unFilterType4 = function ( + rawData, + unfilteredLine, + byteWidth +) { + let xComparison = this._xComparison; + let xBiggerThan = xComparison - 1; + let lastLine = this._lastLine; + + for (let x = 0; x < byteWidth; x++) { + let rawByte = rawData[1 + x]; + let f4Up = lastLine ? lastLine[x] : 0; + let f4Left = x > xBiggerThan ? unfilteredLine[x - xComparison] : 0; + let f4UpLeft = x > xBiggerThan && lastLine ? lastLine[x - xComparison] : 0; + let f4Add = paethPredictor(f4Left, f4Up, f4UpLeft); + unfilteredLine[x] = rawByte + f4Add; + } +}; + +Filter.prototype._reverseFilterLine = function (rawData) { + let filter = rawData[0]; + let unfilteredLine; + let currentImage = this._images[this._imageIndex]; + let byteWidth = currentImage.byteWidth; + + if (filter === 0) { + unfilteredLine = rawData.slice(1, byteWidth + 1); + } else { + unfilteredLine = Buffer.alloc(byteWidth); + + switch (filter) { + case 1: + this._unFilterType1(rawData, unfilteredLine, byteWidth); + break; + case 2: + this._unFilterType2(rawData, unfilteredLine, byteWidth); + break; + case 3: + this._unFilterType3(rawData, unfilteredLine, byteWidth); + break; + case 4: + this._unFilterType4(rawData, unfilteredLine, byteWidth); + break; + default: + throw new Error("Unrecognised filter type - " + filter); + } + } + + this.write(unfilteredLine); + + currentImage.lineIndex++; + if (currentImage.lineIndex >= currentImage.height) { + this._lastLine = null; + this._imageIndex++; + currentImage = this._images[this._imageIndex]; + } else { + this._lastLine = unfilteredLine; + } + + if (currentImage) { + // read, using the byte width that may be from the new current image + this.read(currentImage.byteWidth + 1, this._reverseFilterLine.bind(this)); + } else { + this._lastLine = null; + this.complete(); + } +}; diff --git a/node_modules/pngjs/lib/format-normaliser.js b/node_modules/pngjs/lib/format-normaliser.js new file mode 100644 index 0000000..634d566 --- /dev/null +++ b/node_modules/pngjs/lib/format-normaliser.js @@ -0,0 +1,93 @@ +"use strict"; + +function dePalette(indata, outdata, width, height, palette) { + let pxPos = 0; + // use values from palette + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let color = palette[indata[pxPos]]; + + if (!color) { + throw new Error("index " + indata[pxPos] + " not in palette"); + } + + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = color[i]; + } + pxPos += 4; + } + } +} + +function replaceTransparentColor(indata, outdata, width, height, transColor) { + let pxPos = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + let makeTrans = false; + + if (transColor.length === 1) { + if (transColor[0] === indata[pxPos]) { + makeTrans = true; + } + } else if ( + transColor[0] === indata[pxPos] && + transColor[1] === indata[pxPos + 1] && + transColor[2] === indata[pxPos + 2] + ) { + makeTrans = true; + } + if (makeTrans) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = 0; + } + } + pxPos += 4; + } + } +} + +function scaleDepth(indata, outdata, width, height, depth) { + let maxOutSample = 255; + let maxInSample = Math.pow(2, depth) - 1; + let pxPos = 0; + + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + for (let i = 0; i < 4; i++) { + outdata[pxPos + i] = Math.floor( + (indata[pxPos + i] * maxOutSample) / maxInSample + 0.5 + ); + } + pxPos += 4; + } + } +} + +module.exports = function (indata, imageData) { + let depth = imageData.depth; + let width = imageData.width; + let height = imageData.height; + let colorType = imageData.colorType; + let transColor = imageData.transColor; + let palette = imageData.palette; + + let outdata = indata; // only different for 16 bits + + if (colorType === 3) { + // paletted + dePalette(indata, outdata, width, height, palette); + } else { + if (transColor) { + replaceTransparentColor(indata, outdata, width, height, transColor); + } + // if it needs scaling + if (depth !== 8) { + // if we need to change the buffer size + if (depth === 16) { + outdata = Buffer.alloc(width * height * 4); + } + scaleDepth(indata, outdata, width, height, depth); + } + } + return outdata; +}; diff --git a/node_modules/pngjs/lib/interlace.js b/node_modules/pngjs/lib/interlace.js new file mode 100644 index 0000000..a035cb1 --- /dev/null +++ b/node_modules/pngjs/lib/interlace.js @@ -0,0 +1,95 @@ +"use strict"; + +// Adam 7 +// 0 1 2 3 4 5 6 7 +// 0 x 6 4 6 x 6 4 6 +// 1 7 7 7 7 7 7 7 7 +// 2 5 6 5 6 5 6 5 6 +// 3 7 7 7 7 7 7 7 7 +// 4 3 6 4 6 3 6 4 6 +// 5 7 7 7 7 7 7 7 7 +// 6 5 6 5 6 5 6 5 6 +// 7 7 7 7 7 7 7 7 7 + +let imagePasses = [ + { + // pass 1 - 1px + x: [0], + y: [0], + }, + { + // pass 2 - 1px + x: [4], + y: [0], + }, + { + // pass 3 - 2px + x: [0, 4], + y: [4], + }, + { + // pass 4 - 4px + x: [2, 6], + y: [0, 4], + }, + { + // pass 5 - 8px + x: [0, 2, 4, 6], + y: [2, 6], + }, + { + // pass 6 - 16px + x: [1, 3, 5, 7], + y: [0, 2, 4, 6], + }, + { + // pass 7 - 32px + x: [0, 1, 2, 3, 4, 5, 6, 7], + y: [1, 3, 5, 7], + }, +]; + +exports.getImagePasses = function (width, height) { + let images = []; + let xLeftOver = width % 8; + let yLeftOver = height % 8; + let xRepeats = (width - xLeftOver) / 8; + let yRepeats = (height - yLeftOver) / 8; + for (let i = 0; i < imagePasses.length; i++) { + let pass = imagePasses[i]; + let passWidth = xRepeats * pass.x.length; + let passHeight = yRepeats * pass.y.length; + for (let j = 0; j < pass.x.length; j++) { + if (pass.x[j] < xLeftOver) { + passWidth++; + } else { + break; + } + } + for (let j = 0; j < pass.y.length; j++) { + if (pass.y[j] < yLeftOver) { + passHeight++; + } else { + break; + } + } + if (passWidth > 0 && passHeight > 0) { + images.push({ width: passWidth, height: passHeight, index: i }); + } + } + return images; +}; + +exports.getInterlaceIterator = function (width) { + return function (x, y, pass) { + let outerXLeftOver = x % imagePasses[pass].x.length; + let outerX = + ((x - outerXLeftOver) / imagePasses[pass].x.length) * 8 + + imagePasses[pass].x[outerXLeftOver]; + let outerYLeftOver = y % imagePasses[pass].y.length; + let outerY = + ((y - outerYLeftOver) / imagePasses[pass].y.length) * 8 + + imagePasses[pass].y[outerYLeftOver]; + return outerX * 4 + outerY * width * 4; + }; +}; diff --git a/node_modules/pngjs/lib/packer-async.js b/node_modules/pngjs/lib/packer-async.js new file mode 100644 index 0000000..f3df73a --- /dev/null +++ b/node_modules/pngjs/lib/packer-async.js @@ -0,0 +1,50 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let constants = require("./constants"); +let Packer = require("./packer"); + +let PackerAsync = (module.exports = function (opt) { + Stream.call(this); + + let options = opt || {}; + + this._packer = new Packer(options); + this._deflate = this._packer.createDeflate(); + + this.readable = true; +}); +util.inherits(PackerAsync, Stream); + +PackerAsync.prototype.pack = function (data, width, height, gamma) { + // Signature + this.emit("data", Buffer.from(constants.PNG_SIGNATURE)); + this.emit("data", this._packer.packIHDR(width, height)); + + if (gamma) { + this.emit("data", this._packer.packGAMA(gamma)); + } + + let filteredData = this._packer.filterData(data, width, height); + + // compress it + this._deflate.on("error", this.emit.bind(this, "error")); + + this._deflate.on( + "data", + function (compressedData) { + this.emit("data", this._packer.packIDAT(compressedData)); + }.bind(this) + ); + + this._deflate.on( + "end", + function () { + this.emit("data", this._packer.packIEND()); + this.emit("end"); + }.bind(this) + ); + + this._deflate.end(filteredData); +}; diff --git a/node_modules/pngjs/lib/packer-sync.js b/node_modules/pngjs/lib/packer-sync.js new file mode 100644 index 0000000..f5ab0b3 --- /dev/null +++ b/node_modules/pngjs/lib/packer-sync.js @@ -0,0 +1,56 @@ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let constants = require("./constants"); +let Packer = require("./packer"); + +module.exports = function (metaData, opt) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let options = opt || {}; + + let packer = new Packer(options); + + let chunks = []; + + // Signature + chunks.push(Buffer.from(constants.PNG_SIGNATURE)); + + // Header + chunks.push(packer.packIHDR(metaData.width, metaData.height)); + + if (metaData.gamma) { + chunks.push(packer.packGAMA(metaData.gamma)); + } + + let filteredData = packer.filterData( + metaData.data, + metaData.width, + metaData.height + ); + + // compress it + let compressedData = zlib.deflateSync( + filteredData, + packer.getDeflateOptions() + ); + filteredData = null; + + if (!compressedData || !compressedData.length) { + throw new Error("bad png - invalid compressed data response"); + } + chunks.push(packer.packIDAT(compressedData)); + + // End + chunks.push(packer.packIEND()); + + return Buffer.concat(chunks); +}; diff --git a/node_modules/pngjs/lib/packer.js b/node_modules/pngjs/lib/packer.js new file mode 100644 index 0000000..4aba12c --- /dev/null +++ b/node_modules/pngjs/lib/packer.js @@ -0,0 +1,129 @@ +"use strict"; + +let constants = require("./constants"); +let CrcStream = require("./crc"); +let bitPacker = require("./bitpacker"); +let filter = require("./filter-pack"); +let zlib = require("zlib"); + +let Packer = (module.exports = function (options) { + this._options = options; + + options.deflateChunkSize = options.deflateChunkSize || 32 * 1024; + options.deflateLevel = + options.deflateLevel != null ? options.deflateLevel : 9; + options.deflateStrategy = + options.deflateStrategy != null ? options.deflateStrategy : 3; + options.inputHasAlpha = + options.inputHasAlpha != null ? options.inputHasAlpha : true; + options.deflateFactory = options.deflateFactory || zlib.createDeflate; + options.bitDepth = options.bitDepth || 8; + // This is outputColorType + options.colorType = + typeof options.colorType === "number" + ? options.colorType + : constants.COLORTYPE_COLOR_ALPHA; + options.inputColorType = + typeof options.inputColorType === "number" + ? options.inputColorType + : constants.COLORTYPE_COLOR_ALPHA; + + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.colorType) === -1 + ) { + throw new Error( + "option color type:" + options.colorType + " is not supported at present" + ); + } + if ( + [ + constants.COLORTYPE_GRAYSCALE, + constants.COLORTYPE_COLOR, + constants.COLORTYPE_COLOR_ALPHA, + constants.COLORTYPE_ALPHA, + ].indexOf(options.inputColorType) === -1 + ) { + throw new Error( + "option input color type:" + + options.inputColorType + + " is not supported at present" + ); + } + if (options.bitDepth !== 8 && options.bitDepth !== 16) { + throw new Error( + "option bit depth:" + options.bitDepth + " is not supported at present" + ); + } +}); + +Packer.prototype.getDeflateOptions = function () { + return { + chunkSize: this._options.deflateChunkSize, + level: this._options.deflateLevel, + strategy: this._options.deflateStrategy, + }; +}; + +Packer.prototype.createDeflate = function () { + return this._options.deflateFactory(this.getDeflateOptions()); +}; + +Packer.prototype.filterData = function (data, width, height) { + // convert to correct format for filtering (e.g. right bpp and bit depth) + let packedData = bitPacker(data, width, height, this._options); + + // filter pixel data + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._options.colorType]; + let filteredData = filter(packedData, width, height, this._options, bpp); + return filteredData; +}; + +Packer.prototype._packChunk = function (type, data) { + let len = data ? data.length : 0; + let buf = Buffer.alloc(len + 12); + + buf.writeUInt32BE(len, 0); + buf.writeUInt32BE(type, 4); + + if (data) { + data.copy(buf, 8); + } + + buf.writeInt32BE( + CrcStream.crc32(buf.slice(4, buf.length - 4)), + buf.length - 4 + ); + return buf; +}; + +Packer.prototype.packGAMA = function (gamma) { + let buf = Buffer.alloc(4); + buf.writeUInt32BE(Math.floor(gamma * constants.GAMMA_DIVISION), 0); + return this._packChunk(constants.TYPE_gAMA, buf); +}; + +Packer.prototype.packIHDR = function (width, height) { + let buf = Buffer.alloc(13); + buf.writeUInt32BE(width, 0); + buf.writeUInt32BE(height, 4); + buf[8] = this._options.bitDepth; // Bit depth + buf[9] = this._options.colorType; // colorType + buf[10] = 0; // compression + buf[11] = 0; // filter + buf[12] = 0; // interlace + + return this._packChunk(constants.TYPE_IHDR, buf); +}; + +Packer.prototype.packIDAT = function (data) { + return this._packChunk(constants.TYPE_IDAT, data); +}; + +Packer.prototype.packIEND = function () { + return this._packChunk(constants.TYPE_IEND, null); +}; diff --git a/node_modules/pngjs/lib/paeth-predictor.js b/node_modules/pngjs/lib/paeth-predictor.js new file mode 100644 index 0000000..9634497 --- /dev/null +++ b/node_modules/pngjs/lib/paeth-predictor.js @@ -0,0 +1,16 @@ +"use strict"; + +module.exports = function paethPredictor(left, above, upLeft) { + let paeth = left + above - upLeft; + let pLeft = Math.abs(paeth - left); + let pAbove = Math.abs(paeth - above); + let pUpLeft = Math.abs(paeth - upLeft); + + if (pLeft <= pAbove && pLeft <= pUpLeft) { + return left; + } + if (pAbove <= pUpLeft) { + return above; + } + return upLeft; +}; diff --git a/node_modules/pngjs/lib/parser-async.js b/node_modules/pngjs/lib/parser-async.js new file mode 100644 index 0000000..a69d153 --- /dev/null +++ b/node_modules/pngjs/lib/parser-async.js @@ -0,0 +1,165 @@ +"use strict"; + +let util = require("util"); +let zlib = require("zlib"); +let ChunkStream = require("./chunkstream"); +let FilterAsync = require("./filter-parse-async"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +let ParserAsync = (module.exports = function (options) { + ChunkStream.call(this); + + this._parser = new Parser(options, { + read: this.read.bind(this), + error: this._handleError.bind(this), + metadata: this._handleMetaData.bind(this), + gamma: this.emit.bind(this, "gamma"), + palette: this._handlePalette.bind(this), + transColor: this._handleTransColor.bind(this), + finished: this._finished.bind(this), + inflateData: this._inflateData.bind(this), + simpleTransparency: this._simpleTransparency.bind(this), + headersFinished: this._headersFinished.bind(this), + }); + this._options = options; + this.writable = true; + + this._parser.start(); +}); +util.inherits(ParserAsync, ChunkStream); + +ParserAsync.prototype._handleError = function (err) { + this.emit("error", err); + + this.writable = false; + + this.destroy(); + + if (this._inflate && this._inflate.destroy) { + this._inflate.destroy(); + } + + if (this._filter) { + this._filter.destroy(); + // For backward compatibility with Node 7 and below. + // Suppress errors due to _inflate calling write() even after + // it's destroy()'ed. + this._filter.on("error", function () {}); + } + + this.errord = true; +}; + +ParserAsync.prototype._inflateData = function (data) { + if (!this._inflate) { + if (this._bitmapInfo.interlace) { + this._inflate = zlib.createInflate(); + + this._inflate.on("error", this.emit.bind(this, "error")); + this._filter.on("complete", this._complete.bind(this)); + + this._inflate.pipe(this._filter); + } else { + let rowSize = + ((this._bitmapInfo.width * + this._bitmapInfo.bpp * + this._bitmapInfo.depth + + 7) >> + 3) + + 1; + let imageSize = rowSize * this._bitmapInfo.height; + let chunkSize = Math.max(imageSize, zlib.Z_MIN_CHUNK); + + this._inflate = zlib.createInflate({ chunkSize: chunkSize }); + let leftToInflate = imageSize; + + let emitError = this.emit.bind(this, "error"); + this._inflate.on("error", function (err) { + if (!leftToInflate) { + return; + } + + emitError(err); + }); + this._filter.on("complete", this._complete.bind(this)); + + let filterWrite = this._filter.write.bind(this._filter); + this._inflate.on("data", function (chunk) { + if (!leftToInflate) { + return; + } + + if (chunk.length > leftToInflate) { + chunk = chunk.slice(0, leftToInflate); + } + + leftToInflate -= chunk.length; + + filterWrite(chunk); + }); + + this._inflate.on("end", this._filter.end.bind(this._filter)); + } + } + this._inflate.write(data); +}; + +ParserAsync.prototype._handleMetaData = function (metaData) { + this._metaData = metaData; + this._bitmapInfo = Object.create(metaData); + + this._filter = new FilterAsync(this._bitmapInfo); +}; + +ParserAsync.prototype._handleTransColor = function (transColor) { + this._bitmapInfo.transColor = transColor; +}; + +ParserAsync.prototype._handlePalette = function (palette) { + this._bitmapInfo.palette = palette; +}; + +ParserAsync.prototype._simpleTransparency = function () { + this._metaData.alpha = true; +}; + +ParserAsync.prototype._headersFinished = function () { + // Up until this point, we don't know if we have a tRNS chunk (alpha) + // so we can't emit metadata any earlier + this.emit("metadata", this._metaData); +}; + +ParserAsync.prototype._finished = function () { + if (this.errord) { + return; + } + + if (!this._inflate) { + this.emit("error", "No Inflate block"); + } else { + // no more data to inflate + this._inflate.end(); + } +}; + +ParserAsync.prototype._complete = function (filteredData) { + if (this.errord) { + return; + } + + let normalisedBitmapData; + + try { + let bitmapData = bitmapper.dataToBitMap(filteredData, this._bitmapInfo); + + normalisedBitmapData = formatNormaliser(bitmapData, this._bitmapInfo); + bitmapData = null; + } catch (ex) { + this._handleError(ex); + return; + } + + this.emit("parsed", normalisedBitmapData); +}; diff --git a/node_modules/pngjs/lib/parser-sync.js b/node_modules/pngjs/lib/parser-sync.js new file mode 100644 index 0000000..e79796b --- /dev/null +++ b/node_modules/pngjs/lib/parser-sync.js @@ -0,0 +1,108 @@ +"use strict"; + +let hasSyncZlib = true; +let zlib = require("zlib"); +let inflateSync = require("./sync-inflate"); +if (!zlib.deflateSync) { + hasSyncZlib = false; +} +let SyncReader = require("./sync-reader"); +let FilterSync = require("./filter-parse-sync"); +let Parser = require("./parser"); +let bitmapper = require("./bitmapper"); +let formatNormaliser = require("./format-normaliser"); + +module.exports = function (buffer, options) { + if (!hasSyncZlib) { + throw new Error( + "To use the sync capability of this library in old node versions, please pin pngjs to v2.3.0" + ); + } + + let err; + function handleError(_err_) { + err = _err_; + } + + let metaData; + function handleMetaData(_metaData_) { + metaData = _metaData_; + } + + function handleTransColor(transColor) { + metaData.transColor = transColor; + } + + function handlePalette(palette) { + metaData.palette = palette; + } + + function handleSimpleTransparency() { + metaData.alpha = true; + } + + let gamma; + function handleGamma(_gamma_) { + gamma = _gamma_; + } + + let inflateDataList = []; + function handleInflateData(inflatedData) { + inflateDataList.push(inflatedData); + } + + let reader = new SyncReader(buffer); + + let parser = new Parser(options, { + read: reader.read.bind(reader), + error: handleError, + metadata: handleMetaData, + gamma: handleGamma, + palette: handlePalette, + transColor: handleTransColor, + inflateData: handleInflateData, + simpleTransparency: handleSimpleTransparency, + }); + + parser.start(); + reader.process(); + + if (err) { + throw err; + } + + //join together the inflate datas + let inflateData = Buffer.concat(inflateDataList); + inflateDataList.length = 0; + + let inflatedData; + if (metaData.interlace) { + inflatedData = zlib.inflateSync(inflateData); + } else { + let rowSize = + ((metaData.width * metaData.bpp * metaData.depth + 7) >> 3) + 1; + let imageSize = rowSize * metaData.height; + inflatedData = inflateSync(inflateData, { + chunkSize: imageSize, + maxLength: imageSize, + }); + } + inflateData = null; + + if (!inflatedData || !inflatedData.length) { + throw new Error("bad png - invalid inflate data response"); + } + + let unfilteredData = FilterSync.process(inflatedData, metaData); + inflateData = null; + + let bitmapData = bitmapper.dataToBitMap(unfilteredData, metaData); + unfilteredData = null; + + let normalisedBitmapData = formatNormaliser(bitmapData, metaData); + + metaData.data = normalisedBitmapData; + metaData.gamma = gamma || 0; + + return metaData; +}; diff --git a/node_modules/pngjs/lib/parser.js b/node_modules/pngjs/lib/parser.js new file mode 100644 index 0000000..51a8f2a --- /dev/null +++ b/node_modules/pngjs/lib/parser.js @@ -0,0 +1,290 @@ +"use strict"; + +let constants = require("./constants"); +let CrcCalculator = require("./crc"); + +let Parser = (module.exports = function (options, dependencies) { + this._options = options; + options.checkCRC = options.checkCRC !== false; + + this._hasIHDR = false; + this._hasIEND = false; + this._emittedHeadersFinished = false; + + // input flags/metadata + this._palette = []; + this._colorType = 0; + + this._chunks = {}; + this._chunks[constants.TYPE_IHDR] = this._handleIHDR.bind(this); + this._chunks[constants.TYPE_IEND] = this._handleIEND.bind(this); + this._chunks[constants.TYPE_IDAT] = this._handleIDAT.bind(this); + this._chunks[constants.TYPE_PLTE] = this._handlePLTE.bind(this); + this._chunks[constants.TYPE_tRNS] = this._handleTRNS.bind(this); + this._chunks[constants.TYPE_gAMA] = this._handleGAMA.bind(this); + + this.read = dependencies.read; + this.error = dependencies.error; + this.metadata = dependencies.metadata; + this.gamma = dependencies.gamma; + this.transColor = dependencies.transColor; + this.palette = dependencies.palette; + this.parsed = dependencies.parsed; + this.inflateData = dependencies.inflateData; + this.finished = dependencies.finished; + this.simpleTransparency = dependencies.simpleTransparency; + this.headersFinished = dependencies.headersFinished || function () {}; +}); + +Parser.prototype.start = function () { + this.read(constants.PNG_SIGNATURE.length, this._parseSignature.bind(this)); +}; + +Parser.prototype._parseSignature = function (data) { + let signature = constants.PNG_SIGNATURE; + + for (let i = 0; i < signature.length; i++) { + if (data[i] !== signature[i]) { + this.error(new Error("Invalid file signature")); + return; + } + } + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._parseChunkBegin = function (data) { + // chunk content length + let length = data.readUInt32BE(0); + + // chunk type + let type = data.readUInt32BE(4); + let name = ""; + for (let i = 4; i < 8; i++) { + name += String.fromCharCode(data[i]); + } + + //console.log('chunk ', name, length); + + // chunk flags + let ancillary = Boolean(data[4] & 0x20); // or critical + // priv = Boolean(data[5] & 0x20), // or public + // safeToCopy = Boolean(data[7] & 0x20); // or unsafe + + if (!this._hasIHDR && type !== constants.TYPE_IHDR) { + this.error(new Error("Expected IHDR on beggining")); + return; + } + + this._crc = new CrcCalculator(); + this._crc.write(Buffer.from(name)); + + if (this._chunks[type]) { + return this._chunks[type](length); + } + + if (!ancillary) { + this.error(new Error("Unsupported critical chunk type " + name)); + return; + } + + this.read(length + 4, this._skipChunk.bind(this)); +}; + +Parser.prototype._skipChunk = function (/*data*/) { + this.read(8, this._parseChunkBegin.bind(this)); +}; + +Parser.prototype._handleChunkEnd = function () { + this.read(4, this._parseChunkEnd.bind(this)); +}; + +Parser.prototype._parseChunkEnd = function (data) { + let fileCrc = data.readInt32BE(0); + let calcCrc = this._crc.crc32(); + + // check CRC + if (this._options.checkCRC && calcCrc !== fileCrc) { + this.error(new Error("Crc error - " + fileCrc + " - " + calcCrc)); + return; + } + + if (!this._hasIEND) { + this.read(8, this._parseChunkBegin.bind(this)); + } +}; + +Parser.prototype._handleIHDR = function (length) { + this.read(length, this._parseIHDR.bind(this)); +}; +Parser.prototype._parseIHDR = function (data) { + this._crc.write(data); + + let width = data.readUInt32BE(0); + let height = data.readUInt32BE(4); + let depth = data[8]; + let colorType = data[9]; // bits: 1 palette, 2 color, 4 alpha + let compr = data[10]; + let filter = data[11]; + let interlace = data[12]; + + // console.log(' width', width, 'height', height, + // 'depth', depth, 'colorType', colorType, + // 'compr', compr, 'filter', filter, 'interlace', interlace + // ); + + if ( + depth !== 8 && + depth !== 4 && + depth !== 2 && + depth !== 1 && + depth !== 16 + ) { + this.error(new Error("Unsupported bit depth " + depth)); + return; + } + if (!(colorType in constants.COLORTYPE_TO_BPP_MAP)) { + this.error(new Error("Unsupported color type")); + return; + } + if (compr !== 0) { + this.error(new Error("Unsupported compression method")); + return; + } + if (filter !== 0) { + this.error(new Error("Unsupported filter method")); + return; + } + if (interlace !== 0 && interlace !== 1) { + this.error(new Error("Unsupported interlace method")); + return; + } + + this._colorType = colorType; + + let bpp = constants.COLORTYPE_TO_BPP_MAP[this._colorType]; + + this._hasIHDR = true; + + this.metadata({ + width: width, + height: height, + depth: depth, + interlace: Boolean(interlace), + palette: Boolean(colorType & constants.COLORTYPE_PALETTE), + color: Boolean(colorType & constants.COLORTYPE_COLOR), + alpha: Boolean(colorType & constants.COLORTYPE_ALPHA), + bpp: bpp, + colorType: colorType, + }); + + this._handleChunkEnd(); +}; + +Parser.prototype._handlePLTE = function (length) { + this.read(length, this._parsePLTE.bind(this)); +}; +Parser.prototype._parsePLTE = function (data) { + this._crc.write(data); + + let entries = Math.floor(data.length / 3); + // console.log('Palette:', entries); + + for (let i = 0; i < entries; i++) { + this._palette.push([data[i * 3], data[i * 3 + 1], data[i * 3 + 2], 0xff]); + } + + this.palette(this._palette); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleTRNS = function (length) { + this.simpleTransparency(); + this.read(length, this._parseTRNS.bind(this)); +}; +Parser.prototype._parseTRNS = function (data) { + this._crc.write(data); + + // palette + if (this._colorType === constants.COLORTYPE_PALETTE_COLOR) { + if (this._palette.length === 0) { + this.error(new Error("Transparency chunk must be after palette")); + return; + } + if (data.length > this._palette.length) { + this.error(new Error("More transparent colors than palette size")); + return; + } + for (let i = 0; i < data.length; i++) { + this._palette[i][3] = data[i]; + } + this.palette(this._palette); + } + + // for colorType 0 (grayscale) and 2 (rgb) + // there might be one gray/color defined as transparent + if (this._colorType === constants.COLORTYPE_GRAYSCALE) { + // grey, 2 bytes + this.transColor([data.readUInt16BE(0)]); + } + if (this._colorType === constants.COLORTYPE_COLOR) { + this.transColor([ + data.readUInt16BE(0), + data.readUInt16BE(2), + data.readUInt16BE(4), + ]); + } + + this._handleChunkEnd(); +}; + +Parser.prototype._handleGAMA = function (length) { + this.read(length, this._parseGAMA.bind(this)); +}; +Parser.prototype._parseGAMA = function (data) { + this._crc.write(data); + this.gamma(data.readUInt32BE(0) / constants.GAMMA_DIVISION); + + this._handleChunkEnd(); +}; + +Parser.prototype._handleIDAT = function (length) { + if (!this._emittedHeadersFinished) { + this._emittedHeadersFinished = true; + this.headersFinished(); + } + this.read(-length, this._parseIDAT.bind(this, length)); +}; +Parser.prototype._parseIDAT = function (length, data) { + this._crc.write(data); + + if ( + this._colorType === constants.COLORTYPE_PALETTE_COLOR && + this._palette.length === 0 + ) { + throw new Error("Expected palette not found"); + } + + this.inflateData(data); + let leftOverLength = length - data.length; + + if (leftOverLength > 0) { + this._handleIDAT(leftOverLength); + } else { + this._handleChunkEnd(); + } +}; + +Parser.prototype._handleIEND = function (length) { + this.read(length, this._parseIEND.bind(this)); +}; +Parser.prototype._parseIEND = function (data) { + this._crc.write(data); + + this._hasIEND = true; + this._handleChunkEnd(); + + if (this.finished) { + this.finished(); + } +}; diff --git a/node_modules/pngjs/lib/png-sync.js b/node_modules/pngjs/lib/png-sync.js new file mode 100644 index 0000000..68cac9b --- /dev/null +++ b/node_modules/pngjs/lib/png-sync.js @@ -0,0 +1,12 @@ +"use strict"; + +let parse = require("./parser-sync"); +let pack = require("./packer-sync"); + +exports.read = function (buffer, options) { + return parse(buffer, options || {}); +}; + +exports.write = function (png, options) { + return pack(png, options); +}; diff --git a/node_modules/pngjs/lib/png.js b/node_modules/pngjs/lib/png.js new file mode 100644 index 0000000..0b8af3f --- /dev/null +++ b/node_modules/pngjs/lib/png.js @@ -0,0 +1,194 @@ +"use strict"; + +let util = require("util"); +let Stream = require("stream"); +let Parser = require("./parser-async"); +let Packer = require("./packer-async"); +let PNGSync = require("./png-sync"); + +let PNG = (exports.PNG = function (options) { + Stream.call(this); + + options = options || {}; // eslint-disable-line no-param-reassign + + // coerce pixel dimensions to integers (also coerces undefined -> 0): + this.width = options.width | 0; + this.height = options.height | 0; + + this.data = + this.width > 0 && this.height > 0 + ? Buffer.alloc(4 * this.width * this.height) + : null; + + if (options.fill && this.data) { + this.data.fill(0); + } + + this.gamma = 0; + this.readable = this.writable = true; + + this._parser = new Parser(options); + + this._parser.on("error", this.emit.bind(this, "error")); + this._parser.on("close", this._handleClose.bind(this)); + this._parser.on("metadata", this._metadata.bind(this)); + this._parser.on("gamma", this._gamma.bind(this)); + this._parser.on( + "parsed", + function (data) { + this.data = data; + this.emit("parsed", data); + }.bind(this) + ); + + this._packer = new Packer(options); + this._packer.on("data", this.emit.bind(this, "data")); + this._packer.on("end", this.emit.bind(this, "end")); + this._parser.on("close", this._handleClose.bind(this)); + this._packer.on("error", this.emit.bind(this, "error")); +}); +util.inherits(PNG, Stream); + +PNG.sync = PNGSync; + +PNG.prototype.pack = function () { + if (!this.data || !this.data.length) { + this.emit("error", "No data provided"); + return this; + } + + process.nextTick( + function () { + this._packer.pack(this.data, this.width, this.height, this.gamma); + }.bind(this) + ); + + return this; +}; + +PNG.prototype.parse = function (data, callback) { + if (callback) { + let onParsed, onError; + + onParsed = function (parsedData) { + this.removeListener("error", onError); + + this.data = parsedData; + callback(null, this); + }.bind(this); + + onError = function (err) { + this.removeListener("parsed", onParsed); + + callback(err, null); + }.bind(this); + + this.once("parsed", onParsed); + this.once("error", onError); + } + + this.end(data); + return this; +}; + +PNG.prototype.write = function (data) { + this._parser.write(data); + return true; +}; + +PNG.prototype.end = function (data) { + this._parser.end(data); +}; + +PNG.prototype._metadata = function (metadata) { + this.width = metadata.width; + this.height = metadata.height; + + this.emit("metadata", metadata); +}; + +PNG.prototype._gamma = function (gamma) { + this.gamma = gamma; +}; + +PNG.prototype._handleClose = function () { + if (!this._parser.writable && !this._packer.readable) { + this.emit("close"); + } +}; + +PNG.bitblt = function (src, dst, srcX, srcY, width, height, deltaX, deltaY) { + // eslint-disable-line max-params + // coerce pixel dimensions to integers (also coerces undefined -> 0): + /* eslint-disable no-param-reassign */ + srcX |= 0; + srcY |= 0; + width |= 0; + height |= 0; + deltaX |= 0; + deltaY |= 0; + /* eslint-enable no-param-reassign */ + + if ( + srcX > src.width || + srcY > src.height || + srcX + width > src.width || + srcY + height > src.height + ) { + throw new Error("bitblt reading outside image"); + } + + if ( + deltaX > dst.width || + deltaY > dst.height || + deltaX + width > dst.width || + deltaY + height > dst.height + ) { + throw new Error("bitblt writing outside image"); + } + + for (let y = 0; y < height; y++) { + src.data.copy( + dst.data, + ((deltaY + y) * dst.width + deltaX) << 2, + ((srcY + y) * src.width + srcX) << 2, + ((srcY + y) * src.width + srcX + width) << 2 + ); + } +}; + +PNG.prototype.bitblt = function ( + dst, + srcX, + srcY, + width, + height, + deltaX, + deltaY +) { + // eslint-disable-line max-params + + PNG.bitblt(this, dst, srcX, srcY, width, height, deltaX, deltaY); + return this; +}; + +PNG.adjustGamma = function (src) { + if (src.gamma) { + for (let y = 0; y < src.height; y++) { + for (let x = 0; x < src.width; x++) { + let idx = (src.width * y + x) << 2; + + for (let i = 0; i < 3; i++) { + let sample = src.data[idx + i] / 255; + sample = Math.pow(sample, 1 / 2.2 / src.gamma); + src.data[idx + i] = Math.round(sample * 255); + } + } + } + src.gamma = 0; + } +}; + +PNG.prototype.adjustGamma = function () { + PNG.adjustGamma(this); +}; diff --git a/node_modules/pngjs/lib/sync-inflate.js b/node_modules/pngjs/lib/sync-inflate.js new file mode 100644 index 0000000..4da0d5f --- /dev/null +++ b/node_modules/pngjs/lib/sync-inflate.js @@ -0,0 +1,168 @@ +"use strict"; + +let assert = require("assert").ok; +let zlib = require("zlib"); +let util = require("util"); + +let kMaxLength = require("buffer").kMaxLength; + +function Inflate(opts) { + if (!(this instanceof Inflate)) { + return new Inflate(opts); + } + + if (opts && opts.chunkSize < zlib.Z_MIN_CHUNK) { + opts.chunkSize = zlib.Z_MIN_CHUNK; + } + + zlib.Inflate.call(this, opts); + + // Node 8 --> 9 compatibility check + this._offset = this._offset === undefined ? this._outOffset : this._offset; + this._buffer = this._buffer || this._outBuffer; + + if (opts && opts.maxLength != null) { + this._maxLength = opts.maxLength; + } +} + +function createInflate(opts) { + return new Inflate(opts); +} + +function _close(engine, callback) { + if (callback) { + process.nextTick(callback); + } + + // Caller may invoke .close after a zlib error (which will null _handle). + if (!engine._handle) { + return; + } + + engine._handle.close(); + engine._handle = null; +} + +Inflate.prototype._processChunk = function (chunk, flushFlag, asyncCb) { + if (typeof asyncCb === "function") { + return zlib.Inflate._processChunk.call(this, chunk, flushFlag, asyncCb); + } + + let self = this; + + let availInBefore = chunk && chunk.length; + let availOutBefore = this._chunkSize - this._offset; + let leftToInflate = this._maxLength; + let inOff = 0; + + let buffers = []; + let nread = 0; + + let error; + this.on("error", function (err) { + error = err; + }); + + function handleChunk(availInAfter, availOutAfter) { + if (self._hadError) { + return; + } + + let have = availOutBefore - availOutAfter; + assert(have >= 0, "have should not go down"); + + if (have > 0) { + let out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + + if (out.length > leftToInflate) { + out = out.slice(0, leftToInflate); + } + + buffers.push(out); + nread += out.length; + leftToInflate -= out.length; + + if (leftToInflate === 0) { + return false; + } + } + + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = Buffer.allocUnsafe(self._chunkSize); + } + + if (availOutAfter === 0) { + inOff += availInBefore - availInAfter; + availInBefore = availInAfter; + + return true; + } + + return false; + } + + assert(this._handle, "zlib binding closed"); + let res; + do { + res = this._handle.writeSync( + flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore + ); // out_len + // Node 8 --> 9 compatibility check + res = res || this._writeState; + } while (!this._hadError && handleChunk(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + if (nread >= kMaxLength) { + _close(this); + throw new RangeError( + "Cannot create final Buffer. It would be larger than 0x" + + kMaxLength.toString(16) + + " bytes" + ); + } + + let buf = Buffer.concat(buffers, nread); + _close(this); + + return buf; +}; + +util.inherits(Inflate, zlib.Inflate); + +function zlibBufferSync(engine, buffer) { + if (typeof buffer === "string") { + buffer = Buffer.from(buffer); + } + if (!(buffer instanceof Buffer)) { + throw new TypeError("Not a string or buffer"); + } + + let flushFlag = engine._finishFlushFlag; + if (flushFlag == null) { + flushFlag = zlib.Z_FINISH; + } + + return engine._processChunk(buffer, flushFlag); +} + +function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); +} + +module.exports = exports = inflateSync; +exports.Inflate = Inflate; +exports.createInflate = createInflate; +exports.inflateSync = inflateSync; diff --git a/node_modules/pngjs/lib/sync-reader.js b/node_modules/pngjs/lib/sync-reader.js new file mode 100644 index 0000000..15cbd4c --- /dev/null +++ b/node_modules/pngjs/lib/sync-reader.js @@ -0,0 +1,45 @@ +"use strict"; + +let SyncReader = (module.exports = function (buffer) { + this._buffer = buffer; + this._reads = []; +}); + +SyncReader.prototype.read = function (length, callback) { + this._reads.push({ + length: Math.abs(length), // if length < 0 then at most this length + allowLess: length < 0, + func: callback, + }); +}; + +SyncReader.prototype.process = function () { + // as long as there is any data and read requests + while (this._reads.length > 0 && this._buffer.length) { + let read = this._reads[0]; + + if ( + this._buffer.length && + (this._buffer.length >= read.length || read.allowLess) + ) { + // ok there is any data so that we can satisfy this request + this._reads.shift(); // == read + + let buf = this._buffer; + + this._buffer = buf.slice(read.length); + + read.func.call(this, buf.slice(0, read.length)); + } else { + break; + } + } + + if (this._reads.length > 0) { + return new Error("There are some read requests waitng on finished stream"); + } + + if (this._buffer.length > 0) { + return new Error("unrecognised content at end of stream"); + } +}; diff --git a/node_modules/pngjs/package.json b/node_modules/pngjs/package.json new file mode 100644 index 0000000..12a9871 --- /dev/null +++ b/node_modules/pngjs/package.json @@ -0,0 +1,73 @@ +{ + "name": "pngjs", + "version": "5.0.0", + "description": "PNG encoder/decoder in pure JS, supporting any bit size & interlace, async & sync with full test suite.", + "contributors": [ + "Alexandre Paré", + "Gaurav Mali", + "Gusts Kaksis", + "Kuba Niegowski", + "Luke Page", + "Pietajan De Potter", + "Steven Sojka", + "liangzeng", + "Michael Vogt", + "Xin-Xin Wang", + "toriningen", + "Eugene Kulabuhov" + ], + "homepage": "https://github.com/lukeapage/pngjs", + "keywords": [ + "PNG", + "decoder", + "encoder", + "js-png", + "node-png", + "parser", + "png", + "png-js", + "png-parse", + "pngjs" + ], + "engines": { + "node": ">=10.13.0" + }, + "main": "./lib/png.js", + "directories": { + "lib": "lib", + "example": "examples", + "test": "test" + }, + "scripts": { + "build": "yarn prepublish", + "prepublish": "yarn browserify", + "browserify": "browserify lib/png.js --standalone png > browser.js", + "coverage": "nyc --reporter=lcov --reporter=text-summary tape test/*-spec.js nolarge", + "test": "yarn lint && yarn prettier:check && tape test/*-spec.js | tap-dot && node test/run-compare", + "lint": "eslint .", + "prettier:write": "prettier --write .", + "prettier:check": "prettier --check ." + }, + "repository": { + "type": "git", + "url": "git://github.com/lukeapage/pngjs.git" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/lukeapage/pngjs/issues" + }, + "devDependencies": { + "browserify": "16.5.1", + "buffer-equal": "1.0.0", + "codecov": "3.6.5", + "connect": "3.7.0", + "eslint": "6.8.0", + "eslint-config-prettier": "6.10.1", + "nyc": "15.0.1", + "prettier": "2.0.4", + "puppeteer": "2.1.1", + "serve-static": "1.14.1", + "tap-dot": "2.0.0", + "tape": "4.13.2" + } +} diff --git a/node_modules/postgres-array/index.d.ts b/node_modules/postgres-array/index.d.ts new file mode 100644 index 0000000..88665bd --- /dev/null +++ b/node_modules/postgres-array/index.d.ts @@ -0,0 +1,4 @@ + +export function parse(source: string): string[]; +export function parse(source: string, transform: (value: string) => T): T[]; + diff --git a/node_modules/postgres-array/index.js b/node_modules/postgres-array/index.js new file mode 100644 index 0000000..18bfd16 --- /dev/null +++ b/node_modules/postgres-array/index.js @@ -0,0 +1,97 @@ +'use strict' + +exports.parse = function (source, transform) { + return new ArrayParser(source, transform).parse() +} + +class ArrayParser { + constructor (source, transform) { + this.source = source + this.transform = transform || identity + this.position = 0 + this.entries = [] + this.recorded = [] + this.dimension = 0 + } + + isEof () { + return this.position >= this.source.length + } + + nextCharacter () { + var character = this.source[this.position++] + if (character === '\\') { + return { + value: this.source[this.position++], + escaped: true + } + } + return { + value: character, + escaped: false + } + } + + record (character) { + this.recorded.push(character) + } + + newEntry (includeEmpty) { + var entry + if (this.recorded.length > 0 || includeEmpty) { + entry = this.recorded.join('') + if (entry === 'NULL' && !includeEmpty) { + entry = null + } + if (entry !== null) entry = this.transform(entry) + this.entries.push(entry) + this.recorded = [] + } + } + + consumeDimensions () { + if (this.source[0] === '[') { + while (!this.isEof()) { + var char = this.nextCharacter() + if (char.value === '=') break + } + } + } + + parse (nested) { + var character, parser, quote + this.consumeDimensions() + while (!this.isEof()) { + character = this.nextCharacter() + if (character.value === '{' && !quote) { + this.dimension++ + if (this.dimension > 1) { + parser = new ArrayParser(this.source.substr(this.position - 1), this.transform) + this.entries.push(parser.parse(true)) + this.position += parser.position - 2 + } + } else if (character.value === '}' && !quote) { + this.dimension-- + if (!this.dimension) { + this.newEntry() + if (nested) return this.entries + } + } else if (character.value === '"' && !character.escaped) { + if (quote) this.newEntry(true) + quote = !quote + } else if (character.value === ',' && !quote) { + this.newEntry() + } else { + this.record(character.value) + } + } + if (this.dimension !== 0) { + throw new Error('array dimension not balanced') + } + return this.entries + } +} + +function identity (value) { + return value +} diff --git a/node_modules/postgres-array/license b/node_modules/postgres-array/license new file mode 100644 index 0000000..25c6247 --- /dev/null +++ b/node_modules/postgres-array/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Ben Drucker (bendrucker.me) + +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/node_modules/postgres-array/package.json b/node_modules/postgres-array/package.json new file mode 100644 index 0000000..d6aa94e --- /dev/null +++ b/node_modules/postgres-array/package.json @@ -0,0 +1,35 @@ +{ + "name": "postgres-array", + "main": "index.js", + "version": "2.0.0", + "description": "Parse postgres array columns", + "license": "MIT", + "repository": "bendrucker/postgres-array", + "author": { + "name": "Ben Drucker", + "email": "bvdrucker@gmail.com", + "url": "bendrucker.me" + }, + "engines": { + "node": ">=4" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "types": "index.d.ts", + "keywords": [ + "postgres", + "array", + "parser" + ], + "dependencies": {}, + "devDependencies": { + "standard": "^12.0.1", + "tape": "^4.0.0" + }, + "files": [ + "index.js", + "index.d.ts", + "readme.md" + ] +} diff --git a/node_modules/postgres-array/readme.md b/node_modules/postgres-array/readme.md new file mode 100644 index 0000000..b74b369 --- /dev/null +++ b/node_modules/postgres-array/readme.md @@ -0,0 +1,43 @@ +# postgres-array [![Build Status](https://travis-ci.org/bendrucker/postgres-array.svg?branch=master)](https://travis-ci.org/bendrucker/postgres-array) + +> Parse postgres array columns + + +## Install + +``` +$ npm install --save postgres-array +``` + + +## Usage + +```js +var postgresArray = require('postgres-array') + +postgresArray.parse('{1,2,3}', (value) => parseInt(value, 10)) +//=> [1, 2, 3] +``` + +## API + +#### `parse(input, [transform])` -> `array` + +##### input + +*Required* +Type: `string` + +A Postgres array string. + +##### transform + +Type: `function` +Default: `identity` + +A function that transforms non-null values inserted into the array. + + +## License + +MIT © [Ben Drucker](http://bendrucker.me) diff --git a/node_modules/postgres-bytea/index.js b/node_modules/postgres-bytea/index.js new file mode 100644 index 0000000..b0dc4c7 --- /dev/null +++ b/node_modules/postgres-bytea/index.js @@ -0,0 +1,33 @@ +'use strict' + +var bufferFrom = Buffer.from || Buffer + +module.exports = function parseBytea (input) { + if (/^\\x/.test(input)) { + // new 'hex' style response (pg >9.0) + return bufferFrom(input.substr(2), 'hex') + } + var output = '' + var i = 0 + while (i < input.length) { + if (input[i] !== '\\') { + output += input[i] + ++i + } else { + if (/[0-7]{3}/.test(input.substr(i + 1, 3))) { + output += String.fromCharCode(parseInt(input.substr(i + 1, 3), 8)) + i += 4 + } else { + var backslashes = 1 + while (i + backslashes < input.length && input[i + backslashes] === '\\') { + backslashes++ + } + for (var k = 0; k < Math.floor(backslashes / 2); ++k) { + output += '\\' + } + i += Math.floor(backslashes / 2) * 2 + } + } + } + return bufferFrom(output, 'binary') +} diff --git a/node_modules/postgres-bytea/license b/node_modules/postgres-bytea/license new file mode 100644 index 0000000..25c6247 --- /dev/null +++ b/node_modules/postgres-bytea/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Ben Drucker (bendrucker.me) + +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/node_modules/postgres-bytea/package.json b/node_modules/postgres-bytea/package.json new file mode 100644 index 0000000..344b9a0 --- /dev/null +++ b/node_modules/postgres-bytea/package.json @@ -0,0 +1,34 @@ +{ + "name": "postgres-bytea", + "main": "index.js", + "version": "1.0.1", + "description": "Postgres bytea parser", + "license": "MIT", + "repository": "bendrucker/postgres-bytea", + "author": { + "name": "Ben Drucker", + "email": "bvdrucker@gmail.com", + "url": "bendrucker.me" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "keywords": [ + "bytea", + "postgres", + "binary", + "parser" + ], + "dependencies": {}, + "devDependencies": { + "tape": "^4.0.0", + "standard": "^4.0.0" + }, + "files": [ + "index.js", + "readme.md" + ] +} diff --git a/node_modules/postgres-bytea/readme.md b/node_modules/postgres-bytea/readme.md new file mode 100644 index 0000000..4939c3b --- /dev/null +++ b/node_modules/postgres-bytea/readme.md @@ -0,0 +1,34 @@ +# postgres-bytea [![Build Status](https://travis-ci.org/bendrucker/postgres-bytea.svg?branch=master)](https://travis-ci.org/bendrucker/postgres-bytea) + +> Postgres bytea parser + + +## Install + +``` +$ npm install --save postgres-bytea +``` + + +## Usage + +```js +var bytea = require('postgres-bytea'); +bytea('\\000\\100\\200') +//=> buffer +``` + +## API + +#### `bytea(input)` -> `buffer` + +##### input + +*Required* +Type: `string` + +A Postgres bytea binary string. + +## License + +MIT © [Ben Drucker](http://bendrucker.me) diff --git a/node_modules/postgres-date/index.js b/node_modules/postgres-date/index.js new file mode 100644 index 0000000..5dc73fb --- /dev/null +++ b/node_modules/postgres-date/index.js @@ -0,0 +1,116 @@ +'use strict' + +var DATE_TIME = /(\d{1,})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d{1,})?.*?( BC)?$/ +var DATE = /^(\d{1,})-(\d{2})-(\d{2})( BC)?$/ +var TIME_ZONE = /([Z+-])(\d{2})?:?(\d{2})?:?(\d{2})?/ +var INFINITY = /^-?infinity$/ + +module.exports = function parseDate (isoDate) { + if (INFINITY.test(isoDate)) { + // Capitalize to Infinity before passing to Number + return Number(isoDate.replace('i', 'I')) + } + var matches = DATE_TIME.exec(isoDate) + + if (!matches) { + // Force YYYY-MM-DD dates to be parsed as local time + return getDate(isoDate) || null + } + + var isBC = !!matches[8] + var year = parseInt(matches[1], 10) + if (isBC) { + year = bcYearToNegativeYear(year) + } + + var month = parseInt(matches[2], 10) - 1 + var day = matches[3] + var hour = parseInt(matches[4], 10) + var minute = parseInt(matches[5], 10) + var second = parseInt(matches[6], 10) + + var ms = matches[7] + ms = ms ? 1000 * parseFloat(ms) : 0 + + var date + var offset = timeZoneOffset(isoDate) + if (offset != null) { + date = new Date(Date.UTC(year, month, day, hour, minute, second, ms)) + + // Account for years from 0 to 99 being interpreted as 1900-1999 + // by Date.UTC / the multi-argument form of the Date constructor + if (is0To99(year)) { + date.setUTCFullYear(year) + } + + if (offset !== 0) { + date.setTime(date.getTime() - offset) + } + } else { + date = new Date(year, month, day, hour, minute, second, ms) + + if (is0To99(year)) { + date.setFullYear(year) + } + } + + return date +} + +function getDate (isoDate) { + var matches = DATE.exec(isoDate) + if (!matches) { + return + } + + var year = parseInt(matches[1], 10) + var isBC = !!matches[4] + if (isBC) { + year = bcYearToNegativeYear(year) + } + + var month = parseInt(matches[2], 10) - 1 + var day = matches[3] + // YYYY-MM-DD will be parsed as local time + var date = new Date(year, month, day) + + if (is0To99(year)) { + date.setFullYear(year) + } + + return date +} + +// match timezones: +// Z (UTC) +// -05 +// +06:30 +function timeZoneOffset (isoDate) { + if (isoDate.endsWith('+00')) { + return 0 + } + + var zone = TIME_ZONE.exec(isoDate.split(' ')[1]) + if (!zone) return + var type = zone[1] + + if (type === 'Z') { + return 0 + } + var sign = type === '-' ? -1 : 1 + var offset = parseInt(zone[2], 10) * 3600 + + parseInt(zone[3] || 0, 10) * 60 + + parseInt(zone[4] || 0, 10) + + return offset * sign * 1000 +} + +function bcYearToNegativeYear (year) { + // Account for numerical difference between representations of BC years + // See: https://github.com/bendrucker/postgres-date/issues/5 + return -(year - 1) +} + +function is0To99 (num) { + return num >= 0 && num < 100 +} diff --git a/node_modules/postgres-date/license b/node_modules/postgres-date/license new file mode 100644 index 0000000..25c6247 --- /dev/null +++ b/node_modules/postgres-date/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Ben Drucker (bendrucker.me) + +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/node_modules/postgres-date/package.json b/node_modules/postgres-date/package.json new file mode 100644 index 0000000..6fddec7 --- /dev/null +++ b/node_modules/postgres-date/package.json @@ -0,0 +1,33 @@ +{ + "name": "postgres-date", + "main": "index.js", + "version": "1.0.7", + "description": "Postgres date column parser", + "license": "MIT", + "repository": "bendrucker/postgres-date", + "author": { + "name": "Ben Drucker", + "email": "bvdrucker@gmail.com", + "url": "bendrucker.me" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "keywords": [ + "postgres", + "date", + "parser" + ], + "dependencies": {}, + "devDependencies": { + "standard": "^14.0.0", + "tape": "^5.0.0" + }, + "files": [ + "index.js", + "readme.md" + ] +} diff --git a/node_modules/postgres-date/readme.md b/node_modules/postgres-date/readme.md new file mode 100644 index 0000000..095431a --- /dev/null +++ b/node_modules/postgres-date/readme.md @@ -0,0 +1,49 @@ +# postgres-date [![Build Status](https://travis-ci.org/bendrucker/postgres-date.svg?branch=master)](https://travis-ci.org/bendrucker/postgres-date) [![Greenkeeper badge](https://badges.greenkeeper.io/bendrucker/postgres-date.svg)](https://greenkeeper.io/) + +> Postgres date output parser + +This package parses [date/time outputs](https://www.postgresql.org/docs/current/datatype-datetime.html#DATATYPE-DATETIME-OUTPUT) from Postgres into Javascript `Date` objects. Its goal is to match Postgres behavior and preserve data accuracy. + +If you find a case where a valid Postgres output results in incorrect parsing (including loss of precision), please [create a pull request](https://github.com/bendrucker/postgres-date/compare) and provide a failing test. + +**Supported Postgres Versions:** `>= 9.6` + +All prior versions of Postgres are likely compatible but not officially supported. + +## Install + +``` +$ npm install --save postgres-date +``` + + +## Usage + +```js +var parse = require('postgres-date') +parse('2011-01-23 22:15:51Z') +// => 2011-01-23T22:15:51.000Z +``` + +## API + +#### `parse(isoDate)` -> `date` + +##### isoDate + +*Required* +Type: `string` + +A date string from Postgres. + +## Releases + +The following semantic versioning increments will be used for changes: + +* **Major**: Removal of support for Node.js versions or Postgres versions (not expected) +* **Minor**: Unused, since Postgres returns dates in standard ISO 8601 format +* **Patch**: Any fix for parsing behavior + +## License + +MIT © [Ben Drucker](http://bendrucker.me) diff --git a/node_modules/postgres-interval/index.d.ts b/node_modules/postgres-interval/index.d.ts new file mode 100644 index 0000000..f82b4c3 --- /dev/null +++ b/node_modules/postgres-interval/index.d.ts @@ -0,0 +1,20 @@ +declare namespace PostgresInterval { + export interface IPostgresInterval { + years?: number; + months?: number; + days?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + + toPostgres(): string; + + toISO(): string; + toISOString(): string; + } +} + +declare function PostgresInterval(raw: string): PostgresInterval.IPostgresInterval; + +export = PostgresInterval; diff --git a/node_modules/postgres-interval/index.js b/node_modules/postgres-interval/index.js new file mode 100644 index 0000000..8ecca80 --- /dev/null +++ b/node_modules/postgres-interval/index.js @@ -0,0 +1,125 @@ +'use strict' + +var extend = require('xtend/mutable') + +module.exports = PostgresInterval + +function PostgresInterval (raw) { + if (!(this instanceof PostgresInterval)) { + return new PostgresInterval(raw) + } + extend(this, parse(raw)) +} +var properties = ['seconds', 'minutes', 'hours', 'days', 'months', 'years'] +PostgresInterval.prototype.toPostgres = function () { + var filtered = properties.filter(this.hasOwnProperty, this) + + // In addition to `properties`, we need to account for fractions of seconds. + if (this.milliseconds && filtered.indexOf('seconds') < 0) { + filtered.push('seconds') + } + + if (filtered.length === 0) return '0' + return filtered + .map(function (property) { + var value = this[property] || 0 + + // Account for fractional part of seconds, + // remove trailing zeroes. + if (property === 'seconds' && this.milliseconds) { + value = (value + this.milliseconds / 1000).toFixed(6).replace(/\.?0+$/, '') + } + + return value + ' ' + property + }, this) + .join(' ') +} + +var propertiesISOEquivalent = { + years: 'Y', + months: 'M', + days: 'D', + hours: 'H', + minutes: 'M', + seconds: 'S' +} +var dateProperties = ['years', 'months', 'days'] +var timeProperties = ['hours', 'minutes', 'seconds'] +// according to ISO 8601 +PostgresInterval.prototype.toISOString = PostgresInterval.prototype.toISO = function () { + var datePart = dateProperties + .map(buildProperty, this) + .join('') + + var timePart = timeProperties + .map(buildProperty, this) + .join('') + + return 'P' + datePart + 'T' + timePart + + function buildProperty (property) { + var value = this[property] || 0 + + // Account for fractional part of seconds, + // remove trailing zeroes. + if (property === 'seconds' && this.milliseconds) { + value = (value + this.milliseconds / 1000).toFixed(6).replace(/0+$/, '') + } + + return value + propertiesISOEquivalent[property] + } +} + +var NUMBER = '([+-]?\\d+)' +var YEAR = NUMBER + '\\s+years?' +var MONTH = NUMBER + '\\s+mons?' +var DAY = NUMBER + '\\s+days?' +var TIME = '([+-])?([\\d]*):(\\d\\d):(\\d\\d)\\.?(\\d{1,6})?' +var INTERVAL = new RegExp([YEAR, MONTH, DAY, TIME].map(function (regexString) { + return '(' + regexString + ')?' +}) + .join('\\s*')) + +// Positions of values in regex match +var positions = { + years: 2, + months: 4, + days: 6, + hours: 9, + minutes: 10, + seconds: 11, + milliseconds: 12 +} +// We can use negative time +var negatives = ['hours', 'minutes', 'seconds', 'milliseconds'] + +function parseMilliseconds (fraction) { + // add omitted zeroes + var microseconds = fraction + '000000'.slice(fraction.length) + return parseInt(microseconds, 10) / 1000 +} + +function parse (interval) { + if (!interval) return {} + var matches = INTERVAL.exec(interval) + var isNegative = matches[8] === '-' + return Object.keys(positions) + .reduce(function (parsed, property) { + var position = positions[property] + var value = matches[position] + // no empty string + if (!value) return parsed + // milliseconds are actually microseconds (up to 6 digits) + // with omitted trailing zeroes. + value = property === 'milliseconds' + ? parseMilliseconds(value) + : parseInt(value, 10) + // no zeros + if (!value) return parsed + if (isNegative && ~negatives.indexOf(property)) { + value *= -1 + } + parsed[property] = value + return parsed + }, {}) +} diff --git a/node_modules/postgres-interval/license b/node_modules/postgres-interval/license new file mode 100644 index 0000000..25c6247 --- /dev/null +++ b/node_modules/postgres-interval/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Ben Drucker (bendrucker.me) + +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/node_modules/postgres-interval/package.json b/node_modules/postgres-interval/package.json new file mode 100644 index 0000000..95520a0 --- /dev/null +++ b/node_modules/postgres-interval/package.json @@ -0,0 +1,36 @@ +{ + "name": "postgres-interval", + "main": "index.js", + "version": "1.2.0", + "description": "Parse Postgres interval columns", + "license": "MIT", + "repository": "bendrucker/postgres-interval", + "author": { + "name": "Ben Drucker", + "email": "bvdrucker@gmail.com", + "url": "bendrucker.me" + }, + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "standard && tape test.js" + }, + "keywords": [ + "postgres", + "interval", + "parser" + ], + "dependencies": { + "xtend": "^4.0.0" + }, + "devDependencies": { + "tape": "^4.0.0", + "standard": "^12.0.1" + }, + "files": [ + "index.js", + "index.d.ts", + "readme.md" + ] +} diff --git a/node_modules/postgres-interval/readme.md b/node_modules/postgres-interval/readme.md new file mode 100644 index 0000000..53cda4a --- /dev/null +++ b/node_modules/postgres-interval/readme.md @@ -0,0 +1,48 @@ +# postgres-interval [![Build Status](https://travis-ci.org/bendrucker/postgres-interval.svg?branch=master)](https://travis-ci.org/bendrucker/postgres-interval) [![Greenkeeper badge](https://badges.greenkeeper.io/bendrucker/postgres-interval.svg)](https://greenkeeper.io/) + +> Parse Postgres interval columns + + +## Install + +``` +$ npm install --save postgres-interval +``` + + +## Usage + +```js +var parse = require('postgres-interval') +var interval = parse('01:02:03') +//=> {hours: 1, minutes: 2, seconds: 3} +interval.toPostgres() +// 3 seconds 2 minutes 1 hours +interval.toISO() +// P0Y0M0DT1H2M3S +``` + +## API + +#### `parse(pgInterval)` -> `interval` + +##### pgInterval + +*Required* +Type: `string` + +A Postgres interval string. + +#### `interval.toPostgres()` -> `string` + +Returns an interval string. This allows the interval object to be passed into prepared statements. + +#### `interval.toISOString()` -> `string` + +Returns an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#Durations) compliant string. + +Also available as `interval.toISO()` for backwards compatibility. + +## License + +MIT © [Ben Drucker](http://bendrucker.me) diff --git a/node_modules/postgres/README.md b/node_modules/postgres/README.md new file mode 100644 index 0000000..ca1adcc --- /dev/null +++ b/node_modules/postgres/README.md @@ -0,0 +1,1970 @@ +Fastest full PostgreSQL nodejs client + +- 🚀 Fastest full-featured PostgreSQL client +- 🏷 ES6 Tagged Template Strings at the core +- 🏄‍♀️ Simple surface API +- 🖊️ Dynamic query support +- 🐦 Follow on [X](https://x.com/rporsager) + +
+ +## Getting started + +
+Good UX with Postgres.js +
+ +### Installation +```bash +$ npm install postgres +``` + +Postgres.js needs Node.js 20 or later, Bun, or Cloudflare Workers. Deno runs it through its Node.js compatibility. It is an ES module with no dependencies. + +> **Upgrading from v3?** The API is the same apart from a short list of changes. Read [Upgrading from v3](#upgrading-from-v3) first: parameter types are now decided by the server, which changes how a `Date` is written to `timestamp` and `date` columns outside UTC. + +### Usage +Create your `sql` database instance +```js +// db.js +import postgres from 'postgres' + +const sql = postgres({ /* options */ }) // will use psql environment variables + +export default sql +``` + +Simply import for use elsewhere +```js +// users.js +import sql from './db.js' + +async function getUsersOver(age) { + const users = await sql` + select + name, + age + from users + where age > ${ age } + ` + // users = Result [{ name: "Walter", age: 80 }, { name: 'Murray', age: 68 }, ...] + return users +} + + +async function insertUser({ name, age }) { + const users = await sql` + insert into users + (name, age) + values + (${ name }, ${ age }) + returning name, age + ` + // users = Result [{ name: "Murray", age: 68 }] + return users +} +``` + +#### Dynamic imports and CommonJS + +```js +const { default: postgres } = await import('postgres') +``` + +From CommonJS, on Node.js 20.19 or 22.12 and later, `require` loads it as well: + +```js +const postgres = require('postgres').default +``` + +## Table of Contents + +* [Upgrading from v3](#upgrading-from-v3) +* [Connection](#connection) +* [Queries](#queries) +* [Building queries](#building-queries) +* [Advanced query methods](#advanced-query-methods) +* [Transactions](#transactions) +* [Data Transformation](#data-transformation) +* [Listen & notify](#listen--notify) +* [Realtime subscribe](#realtime-subscribe) +* [Numbers, bigint, numeric](#numbers-bigint-numeric) +* [Result Array](#result-array) +* [Connection details](#connection-details) +* [Custom Types](#custom-types) +* [Teardown / Cleanup](#teardown--cleanup) +* [Tracing](#tracing) +* [Error handling](#error-handling) +* [TypeScript support](#typescript-support) +* [Reserving connections](#reserving-connections) +* [Changelog](./CHANGELOG.md) + + +## Connection + +### `postgres([url], [options])` + +You can use either a `postgres://` url connection string or the options to define your database connection properties. Options in the object will override any present in the url. Options will fall back to the same environment variables as psql. + +```js +const sql = postgres('postgres://username:password@host:port/database', { + host : '', // Postgres ip address[s] or domain name[s] + port : 5432, // Postgres server port[s] + database : '', // Name of database to connect to + username : '', // Username of database user + password : '', // Password of database user + ...and more +}) +``` + +More options can be found in the [Connection details section](#connection-details). + +## Queries + +### ```await sql`...` -> Result[]``` + +Postgres.js utilizes [Tagged template functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates) to process query parameters **before** interpolation. Using tagged template literals benefits developers by: + +1. **Enforcing** safe query generation +2. Giving the ` sql`` ` function powerful [utility](#dynamic-inserts) and [query building](#building-queries) features. + +Any generic value will be serialized according to an inferred type, and replaced by a PostgreSQL protocol placeholder `$1, $2, ...`. The parameters are then sent separately to the database which handles escaping & casting. + +All queries will return a `Result` array, with objects mapping column names to each row. + +```js +const xs = await sql` + insert into users ( + name, age + ) values ( + 'Murray', 68 + ) + + returning * +` + +// xs = [{ user_id: 1, name: 'Murray', age: 68 }] +``` + +> Please note that queries are first executed when `awaited` – or instantly by using [`.execute()`](#execute). + +### Query parameters + +Parameters are automatically extracted and handled by the database so that SQL injection isn't possible. No special handling is necessary, simply use tagged template literals as usual. + +```js +const name = 'Mur' + , age = 60 + +const users = await sql` + select + name, + age + from users + where + name like ${ name + '%' } + and age > ${ age } +` +// users = [{ name: 'Murray', age: 68 }] +``` + +> Be careful with quotation marks here. Because Postgres infers column types, you do not need to wrap your interpolated parameters in quotes like `'${name}'`. This will cause an error because the tagged template replaces `${name}` with `$1` in the query string, leaving Postgres to do the interpolation. If you wrap that in a string, Postgres will see `'$1'` and interpret it as a string as opposed to a parameter. + +### Parameter types + +The server decides the type of every parameter from the query, as with libpq and `psql`, and each value is written for the type the server asked for. A `Date` for a `timestamptz` or `timestamp` column is stored as the instant it is, a `timestamp` is read back as UTC, and a string such as `'true'` for a `boolean` is read by the server. + +Where the query doesn't decide the type, such as a value in the select list or an argument to an overloaded function like `date_trunc`, the server reads the value as text or asks for a cast. A cast always decides: + +```js +await sql`select date_trunc('day', ${ date }::timestamptz)` +await sql`select ${ flag }::bool as flag` +``` + +`infer: true` types values from JavaScript instead, as v3 did: a `Date` as `timestamptz`, a `Buffer` or `Uint8Array` as `bytea`, a boolean as `boolean`, a `bigint` as `int8`, and an array by its first element. See [Upgrading from v3](#upgrading-from-v3) for what that changes. + +### Dynamic column selection + +```js +const columns = ['name', 'age'] + +await sql` + select + ${ sql(columns) } + from users +` + +// Which results in: +select "name", "age" from users +``` + +### Dynamic inserts + +```js +const user = { + name: 'Murray', + age: 68 +} + +await sql` + insert into users ${ + sql(user, 'name', 'age') + } +` + +// Which results in: +insert into users ("name", "age") values ($1, $2) + +// The columns can also be given with an array +const columns = ['name', 'age'] + +await sql` + insert into users ${ + sql(user, columns) + } +` +``` + +**You can omit column names and simply execute `sql(user)` to get all the fields from the object as columns**. Be careful not to allow users to supply columns that you do not want to be inserted. + +#### Multiple inserts in one query +If you need to insert multiple rows at the same time it's also much faster to do it with a single `insert`. Simply pass an array of objects to `sql()`. + +```js +const users = [{ + name: 'Murray', + age: 68, + garbage: 'ignore' +}, +{ + name: 'Walter', + age: 80 +}] + +await sql`insert into users ${ sql(users, 'name', 'age') }` + +// Is translated to: +insert into users ("name", "age") values ($1, $2), ($3, $4) + +// Here you can also omit column names which will use object keys as columns +await sql`insert into users ${ sql(users) }` + +// Which results in: +insert into users ("name", "age") values ($1, $2), ($3, $4) +``` + +### Dynamic columns in updates +This is also useful for update queries +```js +const user = { + id: 1, + name: 'Murray', + age: 68 +} + +await sql` + update users set ${ + sql(user, 'name', 'age') + } + where user_id = ${ user.id } +` + +// Which results in: +update users set "name" = $1, "age" = $2 where user_id = $3 + +// The columns can also be given with an array +const columns = ['name', 'age'] + +await sql` + update users set ${ + sql(user, columns) + } + where user_id = ${ user.id } +` +``` + +### Multiple updates in one query +To create multiple updates in a single query, it is necessary to use arrays instead of objects to ensure that the order of the items correspond with the column names. +```js +const users = [ + [1, 'John', 34], + [2, 'Jane', 27], +] + +await sql` + update users set name = update_data.name, age = (update_data.age)::int + from (values ${sql(users)}) as update_data (id, name, age) + where users.id = (update_data.id)::int + returning users.id, users.name, users.age +` +``` + +### Dynamic values and `where in` +Value lists can also be created dynamically, making `where in` queries simple too. +```js +const users = await sql` + select + * + from users + where age in ${ sql([68, 75, 23]) } +` +``` + +or +```js +const [{ a, b, c }] = await sql` + select + * + from (values ${ sql(['a', 'b', 'c']) }) as x(a, b, c) +` +``` + +### Named arguments in function calls +An object in the parentheses of a function call becomes its named arguments. +```js +await sql` + select make_interval(${ sql({ days: 1, hours: 2 }) }) +` + +// Which results in: +select make_interval("days" => $1,"hours" => $2) +``` + +## Building queries + +Postgres.js features a simple dynamic query builder by conditionally appending/omitting query fragments. +It works by nesting ` sql`` ` fragments within other ` sql`` ` calls or fragments. This allows you to build dynamic queries safely without risking sql injections through usual string concatenation. + +### Partial queries +```js +const olderThan = x => sql`and age > ${ x }` + +const filterAge = true + +await sql` + select + * + from users + where name is not null ${ + filterAge + ? olderThan(50) + : sql`` + } +` +// Which results in: +select * from users where name is not null +// Or +select * from users where name is not null and age > 50 +``` + +### Dynamic filters +```js +await sql` + select + * + from users ${ + id + ? sql`where user_id = ${ id }` + : sql`` + } +` + +// Which results in: +select * from users +// Or +select * from users where user_id = $1 +``` + +Identifiers and values combine with operators, such as for a field of a `json` column: + +```js +const column = email ? 'notifications' : 'settings' + +await sql` + select * from users where ${ sql(column) }->>'email' = ${ 'true' } +` + +// Which results in: +select * from users where "notifications"->>'email' = $1 +``` + +### Joining fragments + +A fragment used as a separator joins a list of fragments and values. Values become parameters, and `false`, `null` and `undefined` are left out, so conditions can be written inline. A space is added on each side of the separator, and around the result, where there isn't one already. + +```js +const where = sql`and`.join([ + sql`age > ${ age }`, + name && sql`name = ${ name }` +]) + +await sql` + select * from users ${ where.length ? sql`where ${ where }` : sql`` } +` + +// Which results in: +select * from users where age > $1 and name = $2 +``` + +### Dynamic ordering + +```js +const id = 1 +const order = { + username: 'asc', + created_at: 'desc' +} +await sql` + select + * + from ticket + where account = ${ id } + order by ${ + Object.entries(order).flatMap(([column, order], i) => + [i ? sql`,` : sql``, sql`${ sql(column) } ${ order === 'desc' ? sql`desc` : sql`asc` }`] + ) + } +` +``` + +### SQL functions +Using keywords or calling functions dynamically is also possible by using ``` sql`` ``` fragments. +```js +const date = null + +await sql` + update users set updated_at = ${ date || sql`now()` } +` + +// Which results in: +update users set updated_at = now() +``` + +### Table names +Dynamic identifiers like table names and column names is also supported like so: +```js +const table = 'users' + , column = 'id' + +await sql` + select ${ sql(column) } from ${ sql(table) } +` + +// Which results in: +select "id" from "users" +``` + +### Quick primer on interpolation + +Here's a quick oversight over all the ways to do interpolation in a query template string: + +| Interpolation syntax | Usage | Example | +| ------------- | ------------- | ------------- | +| `${ sql`` }` | for keywords or sql fragments | ``await sql`SELECT * FROM users ${sql`order by age desc` }` `` | +| `${ sql(string) }` | for identifiers | ``await sql`SELECT * FROM ${sql('table_name')` `` | +| `${ sql([] or {}, ...) }` | for helpers | ``await sql`INSERT INTO users ${sql({ name: 'Peter'})}` `` | +| `${ 'somevalue' }` | for values | ``await sql`SELECT * FROM users WHERE age = ${42}` `` | + +## Advanced query methods + +### Cursors + +#### ```await sql``.cursor([rows = 1], [fn])``` + +Use cursors if you need to throttle the amount of rows being returned from a query. You can use a cursor either as an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of) or with a callback function. For a callback function new results won't be requested until the promise / async callback function has resolved. + +Inside `sql.begin` or on a reserved connection every cursor has a portal of its own, so several can be open at once and other queries can run between their batches. + +##### callback function +```js +await sql` + select + * + from generate_series(1,4) as x +`.cursor(async([row]) => { + // row = { x: 1 } + await http.request('https://example.com/wat', { row }) +}) +``` + +##### for await...of +```js +// for await...of +const cursor = sql`select * from generate_series(1,4) as x`.cursor() + +for await (const [row] of cursor) { + // row = { x: 1 } + await http.request('https://example.com/wat', { row }) +} +``` + +A single row will be returned by default, but you can also request batches by setting the number of rows desired in each batch as the first argument to `.cursor`: +```js +await sql` + select + * + from generate_series(1,1000) as x +`.cursor(10, async rows => { + // rows = [{ x: 1 }, { x: 2 }, ... ] + await Promise.all(rows.map(row => + http.request('https://example.com/wat', { row }) + )) +}) +``` + +If an error is thrown inside the callback function no more rows will be requested and the outer promise will reject with the thrown error. + +You can close the cursor early either by calling `break` in the `for await...of` loop, or by returning the token `sql.CLOSE` from the callback function. + +```js +await sql` + select * from generate_series(1,1000) as x +`.cursor(row => { + return Math.random() > 0.9 && sql.CLOSE // or sql.END +}) +``` + +### Instant iteration + +#### ```await sql``.forEach(fn)``` + +If you want to handle rows returned by a query one by one, you can use `.forEach` which returns a promise that resolves once there are no more rows. +```js +await sql` + select created_at, name from events +`.forEach(row => { + // row = { created_at: '2019-11-22T14:22:00Z', name: 'connected' } +}) + +// No more rows +``` + +### Query Descriptions +#### ```await sql``.describe() -> Result[]``` + +Rather than executing a given query, `.describe` will return information utilized in the query process. This information can include the query identifier, column types, etc. + +This is useful for debugging and analyzing your Postgres queries. Furthermore, **`.describe` will give you access to the final generated query string that would be executed.** + +### Rows as Array of Values +#### ```sql``.values()``` + +Using `.values` will return rows as an array of values for each column, instead of objects. + +This can be useful to receive identically named columns, or for specific performance/transformation reasons. The column definitions are still included on the result array, plus access to parsers for each column. + +### Rows as Raw Array of Buffers +#### ```sql``.raw()``` + +Using `.raw` will return rows as an array with `Buffer` values for each column, instead of objects. + +This can be useful for specific performance/transformation reasons. The column definitions are still included on the result array, plus access to parsers for each column. + +### Queries in Files +#### `await sql.file(path, [args], [options]) -> Result[]` + +Using a file for a query is also supported with optional parameters to use if the file includes `$1, $2, etc` + +```js +const result = await sql.file('query.sql', ['Murray', 68]) +``` + +### Multiple statements in one query +#### ```await sql``.simple()``` + +The postgres wire protocol supports ["simple"](https://www.postgresql.org/docs/current/protocol-flow.html#id-1.10.6.7.4) and ["extended"](https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-EXT-QUERY) queries. "simple" queries supports multiple statements, but does not support any dynamic parameters. "extended" queries support parameters but only one statement. To use "simple" queries you can use +```sql``.simple()```. That will create it as a simple query. + +```js +await sql`select 1; select 2;`.simple() +``` + +### Copy to/from as Streams + +Postgres.js supports [`COPY ...`](https://www.postgresql.org/docs/14/sql-copy.html) queries, which are exposed as [Node.js streams](https://nodejs.org/api/stream.html). + +#### ```await sql`copy ... from stdin`.writable() -> Writable``` + +```js +import { pipeline } from 'node:stream/promises' + +// Stream of users with the default tab delimitated cells and new-line delimitated rows +const userStream = Readable.from([ + 'Murray\t68\n', + 'Walter\t80\n' +]) + +const query = await sql`copy users (name, age) from stdin`.writable() +await pipeline(userStream, query); +query.count // 2, the number of rows copied, once the stream has finished +``` + +#### ```await sql`copy ... to stdout`.readable() -> Readable``` + +##### Using Stream Pipeline +```js +import { pipeline } from 'node:stream/promises' +import { createWriteStream } from 'node:fs' + +const readableStream = await sql`copy users (name, age) to stdout`.readable() +await pipeline(readableStream, createWriteStream('output.tsv')) +// output.tsv content: `Murray\t68\nWalter\t80\n` +``` + +##### Using `for await...of` +```js +const readableStream = await sql` + copy ( + select name, age + from users + where age = 68 + ) to stdout +`.readable() +for await (const chunk of readableStream) { + // chunk.toString() === `Murray\t68\n` +} +``` + +> **NOTE** This is a low-level API which does not provide any type safety. To make this work, you must match your [`copy query` parameters](https://www.postgresql.org/docs/14/sql-copy.html) correctly to your [Node.js stream read or write](https://nodejs.org/api/stream.html) code. Ensure [Node.js stream backpressure](https://nodejs.org/en/learn/modules/backpressuring-in-streams) is handled correctly to avoid memory exhaustion. + +### Canceling Queries in Progress + +Postgres.js supports, [canceling queries in progress](https://www.postgresql.org/docs/7.1/protocol-protocol.html#AEN39000). It works by opening a new connection with a protocol level startup message to cancel the current query running on a specific connection. That means there is no guarantee that the query will be canceled, and due to the possible race conditions it might even result in canceling another query. This is fine for long running queries, but in the case of high load and fast queries it might be better to simply ignore results instead of canceling. + +```js +const query = sql`select pg_sleep 100`.execute() +setTimeout(() => query.cancel(), 100) +const result = await query +``` + +`.signal()` cancels the query when an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) aborts: one still waiting for a connection is rejected without being sent, and a running one gets a cancel request. A cursor canceled while its callback runs, or while an async iterator over it is between batches, is stopped by the client instead: it fetches no more rows, closes its portal and rejects with `57014`, with no cancel request sent. + +```js +await sql`select * from report()`.signal(AbortSignal.timeout(5000)) +``` + +A query waits for a connection when every connection is reserved, in a transaction or has `max_pipeline` queries in flight. `queue_timeout` (in seconds) rejects it with `QUEUE_TIMEOUT` if it waits longer, without ever sending it, and the same goes for `sql.begin` and `sql.reserve`. Once a query is sent, PostgreSQL's own `statement_timeout` is the limit. + +### Execute + +#### ```await sql``.execute()``` + +The lazy Promise implementation in Postgres.js is what allows it to distinguish [Nested Fragments](#building-queries) from the main outer query. This also means that queries are always executed at the earliest in the following tick. If you have a specific need to execute the query in the same tick, you can call `.execute()` + +### Inspecting a query + +`query.text` is the text sent to the server, with `$1`, `$2` for the parameters, and `query.parameters` their values. Both work before the query is sent, without a connection: + +```js +const query = sql`select * from users where id = ${ 1 } and name = ${ 'Murray' }` +query.text // 'select * from users where id = $1 and name = $2' +query.parameters // [1, 'Murray'] +``` + +### Unsafe raw string queries + +
+Advanced unsafe use cases + +### `await sql.unsafe(query, [args], [options]) -> Result[]` + +If you know what you're doing, you can use `unsafe` to pass any string you'd like to postgres. Please note that this can lead to SQL injection if you're not careful. + +```js +sql.unsafe('select ' + danger + ' from users where id = ' + dragons) +``` + +Values go in `args` and are referred to as `$1`, `$2` and so on, so they are never part of the string itself: + +```js +sql.unsafe('select * from users where id = $1 and age > $2', [id, age]) +``` + +`options` takes: + +| Option | Default | | +| --- | --- | --- | +| `prepare` | `false` | Prepare the query as a named statement. Off by default because a string built at run time may be different every time, and each would stay prepared on the server. | +| `simple` | `true` without `args` | Send it with the simple protocol, which allows several statements in one string but no `args`. | + +You can also nest `sql.unsafe` within a safe `sql` expression. This is useful if only part of your fraction has unsafe elements. + +```js +const triggerName = 'friend_created' +const triggerFnName = 'on_friend_created' +const eventType = 'insert' +const schema_name = 'app' +const table_name = 'friends' + +await sql` + create or replace trigger ${sql(triggerName)} + after ${sql.unsafe(eventType)} on ${sql.unsafe(`${schema_name}.${table_name}`)} + for each row + execute function ${sql(triggerFnName)}() +` + +await sql` + create role friend_service with login password ${sql.unsafe(`'${password}'`)} +` +``` + +
+ +## Transactions + +#### BEGIN / COMMIT `await sql.begin([options = ''], fn) -> fn()` + +Use `sql.begin` to start a new transaction. Postgres.js will reserve a connection for the transaction and supply a scoped `sql` instance for all transaction uses in the callback function. `sql.begin` will resolve with the returned value from the callback function. + +`BEGIN` is automatically sent with the optional options, and if anything fails `ROLLBACK` will be called so the connection can be released and execution can continue. + +A query that fails in a transaction aborts it, whether the server rejected it or Postgres.js could not build it (an `undefined` value, say), as PostgreSQL does: catching the error does not let the rest commit, and a later `COMMIT` answers `ROLLBACK`. The transaction commits only once its cursors have finished, also those the callback did not await. + +```js +const [user, account] = await sql.begin(async sql => { + const [user] = await sql` + insert into users ( + name + ) values ( + 'Murray' + ) + returning * + ` + + const [account] = await sql` + insert into accounts ( + user_id + ) values ( + ${ user.user_id } + ) + returning * + ` + + return [user, account] +}) +``` + +Do note that you can often achieve the same result using [`WITH` queries (Common Table Expressions)](https://www.postgresql.org/docs/current/queries-with.html) instead of using transactions. + +It's also possible to pipeline the requests in a transaction if needed by returning an array with queries from the callback function like this: + +```js +const result = await sql.begin(sql => [ + sql`update ...`, + sql`update ...`, + sql`insert ...` +]) +``` + +Queries that are not awaited one by one are pipelined anywhere in the transaction, so `Promise.all` pipelines a group of them between other queries. They run in the order they were made, so a later query sees what an earlier one in the group did: + +```js +await sql.begin(async sql => { + const [movie] = await sql`select * from movie where name = 'Star Wars'` + + await Promise.all([ + sql`insert into movie_actor ...${ movie.id }`, + sql`insert into movie_release ...${ movie.id }` + ]) + + await sql`select ...` +}) +``` + +#### SAVEPOINT `await sql.savepoint([name], fn) -> fn()` + +```js +sql.begin('read write', async sql => { + const [user] = await sql` + insert into users ( + name + ) values ( + 'Murray' + ) + ` + + const [account] = (await sql.savepoint(sql => + sql` + insert into accounts ( + user_id + ) values ( + ${ user.user_id } + ) + ` + ).catch(err => { + // Account could not be created. ROLLBACK SAVEPOINT is called because we caught the rejection. + })) || [] + + return [user, account] +}) +.then(([user, account]) => { + // great success - COMMIT succeeded +}) +.catch(() => { + // not so good - ROLLBACK was called +}) +``` + + +#### Nested `sql.begin` + +Inside a transaction, `sql.begin(fn)` runs `fn` in a savepoint, so code that opens a transaction works the same whether it is given the pool or a transaction. Nothing it does is committed until the outer transaction commits. A mode other than the transaction's own, such as `'read only'` inside a `'read write'` transaction, throws `NESTED_TRANSACTION_MODE`, since a savepoint can't change it, and so does `sql.prepare()` inside a nested `begin`. A savepoint with a name is still `sql.savepoint(name, fn)`. + +```js +async function transfer(sql, from, to, amount) { + return sql.begin(async sql => { + await sql`update accounts set balance = balance - ${ amount } where id = ${ from }` + await sql`update accounts set balance = balance + ${ amount } where id = ${ to }` + }) +} + +await transfer(sql, 1, 2, 10) // its own transaction +await sql.begin(sql => transfer(sql, 1, 2, 10)) // a savepoint in this one +``` + +#### ROLLBACK `await sql.rollback()` + +Rolls back the transaction without throwing, and `sql.begin` resolves with what the callback returns (#500). Called in a savepoint or a nested `sql.begin`, it rolls back only that savepoint, and the outer transaction goes on. The rollback is sent at once, after any queries already made. Queries made after it in the same scope are not sent and reject with `TRANSACTION_ROLLED_BACK`, and so does the `sql.begin` they were made in. + +```js +const result = await sql.begin(async sql => { + const [order] = await sql`insert into orders ${ sql(input) } returning *` + if (!await inStock(sql, order)) + return (await sql.rollback(), { saved: false }) + return { saved: true, order } +}) +``` + +#### PREPARE TRANSACTION `await sql.prepare([name]) -> fn()` + +Indicates that the transactions should be prepared using the [`PREPARE TRANSACTION [NAME]`](https://www.postgresql.org/docs/current/sql-prepare-transaction.html) statement +instead of being committed. + +```js +sql.begin('read write', async sql => { + const [user] = await sql` + insert into users ( + name + ) values ( + 'Murray' + ) + ` + + await sql.prepare('tx1') +}) +``` + +## Data Transformation + +Postgres.js allows for transformation of the data passed to or returned from a query by using the `transform` option. + +Built in transformation functions are: + +* For camelCase - `postgres.camel`, `postgres.toCamel`, `postgres.fromCamel` +* For PascalCase - `postgres.pascal`, `postgres.toPascal`, `postgres.fromPascal` +* For Kebab-Case - `postgres.kebab`, `postgres.toKebab`, `postgres.fromKebab` + +These built in transformations will only convert to/from snake_case. For example, using `{ transform: postgres.toCamel }` will convert the column names to camelCase only if the column names are in snake_case to begin with. `{ transform: postgres.fromCamel }` will convert camelCase only to snake_case. + +By default, using `postgres.camel`, `postgres.pascal` and `postgres.kebab` will perform a two-way transformation - both the data passed to the query and the data returned by the query will be transformed: + +```js +// Transform the column names to and from camel case +const sql = postgres({ transform: postgres.camel }) + +await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER, b_test TEXT)` +await sql`INSERT INTO camel_case ${ sql([{ aTest: 1, bTest: 1 }]) }` +const data = await sql`SELECT ${ sql('aTest', 'bTest') } FROM camel_case` + +console.log(data) // [ { aTest: 1, bTest: '1' } ] +``` + +To only perform half of the transformation (eg. only the transformation **to** or **from** camel case), use the other transformation functions: + +```js +// Transform the column names only to camel case +// (for the results that are returned from the query) +postgres({ transform: postgres.toCamel }) + +await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER)` +await sql`INSERT INTO camel_case ${ sql([{ a_test: 1 }]) }` +const data = await sql`SELECT a_test FROM camel_case` + +console.log(data) // [ { aTest: 1 } ] +``` + +```js +// Transform the column names only from camel case +// (for interpolated inserts, updates, and selects) +const sql = postgres({ transform: postgres.fromCamel }) + +await sql`CREATE TABLE IF NOT EXISTS camel_case (a_test INTEGER)` +await sql`INSERT INTO camel_case ${ sql([{ aTest: 1 }]) }` +const data = await sql`SELECT ${ sql('aTest') } FROM camel_case` + +console.log(data) // [ { a_test: 1 } ] +``` + +> Note that Postgres.js does not rewrite the static parts of the tagged template strings. So to transform column names in your queries, the `sql()` helper must be used - eg. `${ sql('columnName') }` as in the examples above. + +### Transform `undefined` Values + +By default, Postgres.js will throw the error `UNDEFINED_VALUE: Undefined values are not allowed` when undefined values are passed + +```js +// Transform the column names to and from camel case +const sql = postgres({ + transform: { + undefined: null + } +}) + +await sql`CREATE TABLE IF NOT EXISTS transform_undefined (a_test INTEGER)` +await sql`INSERT INTO transform_undefined ${ sql([{ a_test: undefined }]) }` +const data = await sql`SELECT a_test FROM transform_undefined` + +console.log(data) // [ { a_test: null } ] +``` + +To combine with the built in transform functions, spread the transform in the `transform` object: + +```js +// Transform the column names to and from camel case +const sql = postgres({ + transform: { + ...postgres.camel, + undefined: null + } +}) + +await sql`CREATE TABLE IF NOT EXISTS transform_undefined (a_test INTEGER)` +await sql`INSERT INTO transform_undefined ${ sql([{ aTest: undefined }]) }` +const data = await sql`SELECT ${ sql('aTest') } FROM transform_undefined` + +console.log(data) // [ { aTest: null } ] +``` + +### Custom Transform Functions + +To specify your own transformation functions, you can use the `column`, `value` and `row` options inside of `transform`, each an object possibly including `to` and `from` keys: + +* `to`: The function to transform the outgoing query column name to, i.e `SELECT ${ sql('aName') }` to `SELECT a_name` when using `postgres.toCamel`. +* `from`: The function to transform the incoming query result column name to, see example below. + +> Both parameters are optional, if not provided, the default transformation function will be used. + +```js +// Implement your own functions, look at postgres.toCamel, etc +// as a reference: +// toCamel and the others in types.js +function transformColumnToDatabase() { /* ... */ } +function transformColumnFromDatabase() { /* ... */ } + +const sql = postgres({ + transform: { + column: { + to: transformColumnToDatabase, + from: transformColumnFromDatabase, + }, + value: { /* ... */ }, + row: { /* ... */ } + } +}) +``` + +## Listen & notify + +When you call `.listen`, a dedicated connection will be created to ensure that you receive notifications instantly. This connection will be used for any further calls to `.listen`. The connection will automatically reconnect according to a backoff reconnection pattern to not overload the database server. + +### Listen `await sql.listen(channel, onnotify, [onlisten]) -> { state }` +`.listen` takes the channel name, a function to handle each notify, and an optional function to run every time listen is registered and ready (happens on initial connect and reconnects). It returns a promise which resolves once the `LISTEN` query to Postgres completes, or if there is already a listener active. + +```js +await sql.listen('news', payload => { + const json = JSON.parse(payload) + console.log(json.this) // logs 'is' +}) +``` + +The optional `onlisten` method is great to use for a very simply queue mechanism: + +```js +await sql.listen( + 'jobs', + (x) => run(JSON.parse(x)), + ( ) => sql`select unfinished_jobs()`.forEach(run) +) + +function run(job) { + // And here you do the work you please +} +``` +### Notify `await sql.notify(channel, payload) -> Result[]` +Notify can be done as usual in SQL, or by using the `sql.notify` method. +```js +sql.notify('news', JSON.stringify({ no: 'this', is: 'news' })) +``` + +## Realtime subscribe + +Postgres.js implements the logical replication protocol of PostgreSQL to support subscription to real-time updates of `insert`, `update`, `delete` and `truncate` operations. + +> **NOTE** To make this work you must [create the proper publications in your database](https://www.postgresql.org/docs/current/sql-createpublication.html), enable logical replication by setting `wal_level = logical` in `postgresql.conf` and connect using either a replication or superuser. + +### Quick start + +#### Create a publication (eg. in migration) +```sql +CREATE PUBLICATION alltables FOR ALL TABLES +``` + +#### Subscribe to updates +```js +const sql = postgres({ publications: 'alltables' }) + +const { unsubscribe } = await sql.subscribe( + 'insert:events', + (row, { command, relation, key, old, lsn, time, xid }) => { + // Callback function for each row change + // tell about new event row over eg. websockets or do something else + }, + () => { + // Callback on initial connect and potential reconnects + }, + error => { + // A handler failed, or the stream had an error + } +) +``` + +Besides the row, each change comes with the transaction it was part of: its `lsn` (like `'0/1A2B3C4'`), its commit `time` and its `xid`. An `update` also has `old` when the table's replica identity sends it, and a `truncate` has no row but `cascade` and `restartIdentity`. + +### Handlers that return promises + +A handler may be async. Changes are then handled one after the other, in the order they were committed, and the stream waits while a handler is busy instead of piling changes up in memory: + +```js +await sql.subscribe('insert:orders', async row => { + await queue.publish('order', row) +}) +``` + +### Persistent slots + +By default a subscription uses a temporary replication slot, which the server drops when the connection closes, so changes made while the subscriber is away are not seen. + +Give the slot a name to keep it. It is created if it does not exist, and streaming starts where it was last confirmed, so nothing committed while the subscriber was down is missed: + +```js +const sql = postgres({ publications: 'alltables', slot: 'orders_worker' }) + +await sql.subscribe('*:orders', async(row, info) => { + await handle(row, info) +}) +``` + +With a slot, a transaction is confirmed to the server only after every handler for it has finished. If a handler throws or rejects, the transaction is not confirmed: `onerror` is called, the stream restarts and the transaction is delivered again. Delivery is at least once, so a handler should cope with seeing a transaction twice, for instance by remembering the `lsn` it handled last. + +While nothing is in flight, the slot is also confirmed as far as the server has got, so a quiet slot does not keep the server holding WAL. + +A persistent slot keeps WAL on the server until it is confirmed, so drop it when it is no longer used: + +```sql +select pg_drop_replication_slot('orders_worker') +``` + +### Subscribe pattern + +You can subscribe to specific operations, tables, or even rows with primary keys. + +#### `operation` `:` `schema` `.` `table` `=` `primary_key` + +**`operation`** is one of ``` * | insert | update | delete | truncate ``` and defaults to `*` + +**`schema`** defaults to `public` + +**`table`** is a specific table name and defaults to `*` + +**`primary_key`** can be used to only subscribe to specific rows + +### Examples + +```js +sql.subscribe('*', () => /* everything */ ) +sql.subscribe('insert', () => /* all inserts */ ) +sql.subscribe('*:users', () => /* all operations on the public.users table */ ) +sql.subscribe('delete:users', () => /* all deletes on the public.users table */ ) +sql.subscribe('update:users=1', () => /* all updates on the users row with a primary key = 1 */ ) +sql.subscribe('truncate:users', () => /* the public.users table was truncated */ ) +``` + +## Numbers, bigint, numeric + +`Number` in javascript is only able to represent 253-1 safely which means that types in PostgreSQLs like `bigint` and `numeric` won't fit into `Number`. + +Since Node.js v10.4 we can use [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) to match the PostgreSQL type `bigint` which is returned for eg. `count(*)`. Unfortunately, it doesn't work with `JSON.stringify` out of the box, so Postgres.js will return it as a string. + +If you want to use `BigInt` you can add this custom type: + +```js +const sql = postgres({ + types: { + bigint: postgres.BigInt + } +}) +``` + +There is currently no guaranteed way to handle `numeric` / `decimal` types in native Javascript. **These [and similar] types will be returned as a `string`**. The best way in this case is to use [custom types](#custom-types). + +## Result Array + +The `Result` Array returned from queries is a custom array allowing for easy destructuring or passing on directly to JSON.stringify or general Array usage. It includes the following properties. + +### .count + +The `count` property is the number of affected rows returned by the database. This is useful for insert, update and delete operations to know the number of rows since .length will be 0 in these cases if not using `RETURNING ...`. + +### .command + +The `command` run by the query - eg. one of `SELECT`, `UPDATE`, `INSERT`, `DELETE` + +### .columns + +The `columns` returned by the query useful to determine types, or map to the result values when using `.values()` + +```js +{ + name : String, // Column name, + type : oid, // PostgreSQL oid column type + parser: Function // The function used by Postgres.js for parsing +} +``` + +### .statement + +The `statement` contains information about the statement implicitly created by Postgres.js. + +```js +{ + name : String, // The auto generated statement name + string : String, // The actual query string executed + types : [oid], // An array of oid expected as input parameters + columns : [Column] // Array of columns - same as Result.columns +} +``` + +### .state + +This is the state `{ pid, secret }` of the connection that executed the query. + +## Connection details + +### All Postgres options + +```js +const sql = postgres('postgres://username:password@host:port/database', { + host : '', // Postgres ip address[es] or domain name[s] + port : 5432, // Postgres server port[s] + path : '', // unix socket path (usually '/tmp') + database : '', // Name of database to connect to + username : '', // Username of database user, or a function returning it + password : '', // Password of database user, or a function returning it + ssl : false, // true, prefer, require, verify-full, tls.connect options + sslnegotiation : null, // 'direct' for TLS from the first byte (PostgreSQL 17+) + channel_binding : 'prefer', // SCRAM-SHA-256-PLUS over TLS: 'disable', 'prefer' or 'require' + max : 10, // Max number of connections + min : 0, // Connections kept open once the pool is used + max_pipeline : 100, // Max number of queries pipelined on one connection + scheduler : true, // Pipeline where a query should be done soonest (more info below) + max_lifetime : null, // Max lifetime in seconds (more info below) + idle_timeout : 0, // Idle connection timeout in seconds + connect_timeout : 30, // Connect timeout in seconds + queue_timeout : 0, // Seconds a query may wait for a connection, 0 for no limit + keep_alive : 60, // TCP keep-alive in seconds, 0 or null for none + backoff : fn, // Seconds to wait before reconnecting, given the attempt + prepare : true, // Automatic creation of prepared statements + infer : false, // true types parameters from JS values, as v3 did + types : [], // Array of custom types, see more below + onnotice : fn, // Default console.log, set false to silence NOTICE + onnotify : fn, // (channel, payload, pid) for every notification + onparameter : fn, // (key, value) when server param change + onclose : fn, // (connection id) when a connection closes + debug : false, // true, or a function called with (connection, query, params, types) + socket : fn, // (options, host, port) returning a custom socket to use + transform : { + undefined : undefined, // Transforms undefined values (eg. to null) + column : fn, // Transforms incoming column names + value : fn, // Transforms incoming row values + row : fn // Transforms entire rows + }, + connection : { + application_name : 'postgres.js', // Default application_name + ... // Other connection parameters, see https://www.postgresql.org/docs/current/runtime-config-client.html + }, + target_session_attrs : null, // Use 'read-write' with multiple hosts to + // ensure only connecting to primary + fetch_types : true, // Fetches array types and other types it does not know + publications : 'alltables', // Publications for sql.subscribe + slot : null, // A permanent replication slot for sql.subscribe + onread : true, // Read into one shared buffer per connection (Node.js, Bun, Deno) + unref_sockets : false // Idle connections don't keep the process alive +}) +``` + +Note that `max_lifetime = 60 * (30 + Math.random() * 30)` by default. This resolves to an interval between 30 and 60 minutes to optimize for the benefits of prepared statements **and** working nicely with Linux's OOM killer. + +### Dynamic passwords + +When clients need to use alternative authentication schemes such as access tokens or connections to databases with rotating passwords, provide either a synchronous or asynchronous function that will resolve the dynamic password value at connection time. + +```js +const sql = postgres(url, { + // Other connection config + ... + // Password function for the database user + password : async () => await signer.getAuthToken(), +}) +``` + +The user can be a function as well, for credentials that rotate both, such as those from a secrets manager. It is called each time a connection opens, before the password. Give `database` too, since it can no longer default to the user name. + +```js +const sql = postgres({ + database: 'app', + username: async () => (await secrets.get()).username, + password: async () => (await secrets.get()).password +}) +``` + +### Password file + +With no password given, Postgres.js reads one from the file in `PGPASSFILE`, or `~/.pgpass` (`%APPDATA%\postgresql\pgpass.conf` on Windows), as libpq does: lines of `host:port:database:user:password`, where `*` matches anything and `\` escapes a `:` or `\`. On Unix the file is ignored unless only its owner can read it (`chmod 600`). + +### SSL + +Although [vulnerable to MITM attacks](https://security.stackexchange.com/a/229297/174913), a common configuration for the `ssl` option for some cloud providers is to set `rejectUnauthorized` to `false` (if `NODE_ENV` is `production`): + +```js +const sql = + process.env.NODE_ENV === 'production' + ? // "Unless you're using a Private or Shield Heroku Postgres database, Heroku Postgres does not currently support verifiable certificates" + // https://help.heroku.com/3DELT3RK/why-can-t-my-third-party-utility-connect-to-heroku-postgres-with-ssl + postgres({ ssl: { rejectUnauthorized: false } }) + : postgres() +``` + +For more information regarding `ssl` with `postgres`, check out the [Node.js documentation for tls](https://nodejs.org/api/tls.html#tlsconnectoptions-callback). + +The modes follow libpq's `sslmode`: `require`, `prefer` and `allow` encrypt without checking the certificate, and `verify-full` (or `sslrootcert=system` in the url) checks it against the system's certificate authorities. `prefer` and `allow` fall back to an unencrypted connection when the server has no TLS. Cloudflare Workers always check the certificate. + +#### Direct TLS + +PostgreSQL 17 and later can start TLS on the first byte instead of being asked first, which saves a round trip when connecting: + +```js +const sql = postgres('postgres://host/db?sslmode=require&sslnegotiation=direct') +// or +const sql = postgres({ ssl: 'require', sslnegotiation: 'direct' }) +``` + +On Node.js this is also the fastest encrypted connection, as it reads into the same shared buffer as a plain one. It needs a server that supports it, and is not available in Cloudflare Workers, whose sockets cannot send the ALPN it requires. + +#### Channel binding + +Over TLS, SCRAM authentication is bound to the server's certificate with SCRAM-SHA-256-PLUS (`tls-server-end-point`) when the server offers it, so a man in the middle holding some other certificate that looks valid can't relay the login. `channel_binding` works as in libpq, and can also be given in the url or as `PGCHANNELBINDING`: + +- `'prefer'` (the default) binds when the server offers it, and authenticates as before when it doesn't. +- `'require'` refuses any connection that isn't bound, so a server that isn't reached over TLS, doesn't offer it or authenticates without SCRAM is rejected with `CHANNEL_BINDING_REQUIRED`. +- `'disable'` never binds. + +```js +const sql = postgres('postgres://host/db?sslmode=verify-full&channel_binding=require') +``` + +Certificates signed with Ed25519, for which binding isn't defined, are not bound. Cloudflare Workers sockets don't expose the server certificate, so there `'prefer'` doesn't bind and `'require'` is rejected. + + +### Multi-host connections - High Availability (HA) + +Multiple connection strings can be passed to `postgres()` in the form of `postgres('postgres://localhost:5432,localhost:5433', ...)`. This works the same as native the `psql` command. Read more at [multiple host URIs](https://www.postgresql.org/docs/13/libpq-connect.html#LIBPQ-MULTIPLE-HOSTS). + +Connections will be attempted in order of the specified hosts/ports. On a successful connection, all retries will be reset. This ensures that hosts can come up and down seamlessly. + +If you specify `target_session_attrs: 'primary'` or `PGTARGETSESSIONATTRS=primary` Postgres.js will only connect to the primary host, allowing for zero downtime failovers. + +### The Connection Pool + +Connections are created lazily once a query is created. This means that simply doing const `sql = postgres(...)` won't have any effect other than instantiating a new `sql` instance. + +> No connection will be made until a query is made. + +For example: + +```js +const sql = postgres() // no connections are opened + +await sql`...` // one connection is now opened +await sql`...` // previous opened connection is reused + +// two connections are opened now +await Promise.all([ + sql`...`, + sql`...` +]) +``` + +> When there are high amount of concurrent queries, `postgres` will open as many connections as needed up until `max` number of connections is reached. By default `max` is 10. This can be changed by setting `max` in the `postgres()` call. Example - `postgres('connectionURL', { max: 20 })`. + +This means that we get a much simpler story for error handling and reconnections. Queries will be sent over the wire immediately on the next available connection in the pool. Connections are automatically taken out of the pool if you start a transaction using `sql.begin()`, and automatically returned to the pool once your transaction is done. + +Any query which was already sent over the wire will be rejected if the connection is lost. It'll automatically defer to the error handling you have for that query, and since connections are lazy it'll automatically try to reconnect the next time a query is made. The benefit of this is no weird generic "onerror" handler that tries to get things back to normal, and also simpler application code since you don't have to handle errors out of context. + +There are no guarantees about queries executing in order unless using a transaction with `sql.begin()` or setting `max: 1`. Of course doing a series of queries, one awaiting the other will work as expected, but that's just due to the nature of js async/promise handling, so it's not necessary for this library to be concerned with ordering. + +Since this library automatically creates prepared statements, it also has a default max lifetime for connections to prevent memory bloat on the database itself. This is a random interval for each connection between 30 and 60 minutes. This allows multiple connections to independently come up and down without affecting the service. + +What a statement takes and returns is learned once for the whole pool, not once per connection, so a new connection never has to ask about a query the pool already knows. Each connection still prepares a statement itself the first time it runs it. + +Up to `max_pipeline` queries (100 by default) are sent on one connection before the answers come back, which is what makes many small queries fast. A query that waits on a lock holds up those behind it on the same connection; lower `max_pipeline` if that matters more to you than throughput. + +#### Scheduling + +A query goes to an idle connection when there is one. When every connection is busy, the pool pipelines it on the connection where it should be done soonest, from how long each statement has taken before and how long what is in flight has been running, so a quick query doesn't wait behind a slow one when another connection is about to be free. Slow queries (around 100 ms or more) are kept together on the connections that already run slow work, within twice their own time, once the rest of the pool is needed for quick work; how many connections that is follows how much quick and slow work has come in over the last few seconds. Nothing has to be configured, and while nothing slow is in flight the pool places queries as before. `scheduler: false` turns it off: a busy pool then pipelines on the connection with the fewest queries in flight. With `max: 1` there is only one connection to choose, so the scheduler is off. + +#### Pool stats + +`sql.stats` tells what the pool is doing right now: + +```js +sql.stats +// { connections: 3, opening: 0, idle: 1, leased: 1, waiting: 0 } +``` + +### Connection timeout + +By default, connections will not close until `.end()` is called. However, it may be useful to have them close automatically when: + +- re-instantiating multiple ` sql`` ` instances +- using Postgres.js in a Serverless environment (Lambda, etc.) +- using Postgres.js with a database service that automatically closes connections after some time (see [`ECONNRESET` issue](https://github.com/porsager/postgres/issues/179)) + +This can be done using the `idle_timeout` or `max_lifetime` options. These configuration options specify the number of seconds to wait before automatically closing an idle connection and the maximum time a connection can exist, respectively. + +For example, to close a connection that has either been idle for 20 seconds or existed for more than 30 minutes: + +```js +const sql = postgres({ + idle_timeout: 20, + max_lifetime: 60 * 30 +}) +``` + +### Cloudflare Workers support + +Postgres.js runs in Cloudflare Workers on the [TCP socket API](https://developers.cloudflare.com/workers/runtime-apis/tcp-sockets/). Bundlers pick the Workers build through the `workerd` export condition, so the import is the same as anywhere else. + +You can use Postgres.js directly in a Worker, or to benefit from connection pooling and query caching, via the [Hyperdrive](https://developers.cloudflare.com/hyperdrive/learning/connect-to-postgres/#driver-examples) service available to Workers by passing the Hyperdrive `connectionString` when creating a new `postgres` client as follows: + +```ts +import postgres from 'postgres' + +interface Env { + HYPERDRIVE: Hyperdrive +} + +export default { + async fetch(req: Request, env: Env, ctx: ExecutionContext) { + const sql = postgres(env.HYPERDRIVE.connectionString) + const results = await sql`SELECT * FROM users LIMIT 10` + ctx.waitUntil(sql.end()) + return Response.json(results) + } +} +``` + +Postgres.js uses `Buffer`, `crypto` and `events` from the Node.js compatibility of Workers, which is on by default from the compatibility date 2026-08-04. For an earlier date, enable it in `wrangler.toml`: + +```toml +compatibility_flags = ["nodejs_compat"] +``` + +A few things differ in Workers: + +- The server certificate is always checked, whatever `ssl` is set to. +- `sslnegotiation: 'direct'` is refused with `SSL_NEGOTIATION_NOT_SUPPORTED`, as Workers sockets cannot send ALPN. +- Channel binding isn't available, as Workers sockets don't expose the server certificate, so `channel_binding: 'require'` is rejected with `CHANNEL_BINDING_REQUIRED`. +- A connection belongs to the request that opened it, so a client made outside `fetch` cannot be shared between requests. + +### Auto fetching of array types + +The built-in types and their arrays are known without asking the server. Before its first query a pool asks once for the array types and domains that the database has besides those, so an array of an enum or a domain over a built-in type is read and written like its base type. A type made after that, and any type that is neither, is read and written as text, as in v3. + +If you have revoked access to `pg_catalog` this feature will no longer work and will need to be disabled. + +You can disable this feature by setting `fetch_types` to `false`. + +### Environmental variables + +It is also possible to connect to the database without a connection string or any options. Postgres.js will fall back to the common environment variables used by `psql` as in the table below: + +```js +const sql = postgres() +``` + +| Option | Environment Variables | +| ------------------ | ------------------------ | +| `host` | `PGHOST` | +| `port` | `PGPORT` | +| `database` | `PGDATABASE` | +| `username` | `PGUSERNAME` or `PGUSER` | +| `password` | `PGPASSWORD` | +| `application_name` | `PGAPPNAME` | +| `idle_timeout` | `PGIDLE_TIMEOUT` | +| `connect_timeout` | `PGCONNECT_TIMEOUT` | + +### Prepared statements + +Prepared statements will automatically be created for any queries where it can be inferred that the query is static. This can be disabled by using the `prepare: false` option, which is what a pooler in transaction mode without support for prepared statements needs (see below). With `prepare: false` a query with parameters is described before it runs, as in v3, which costs a round trip, but always uses the types the server has now. A prepared statement keeps the parameter types it was prepared with, on the server and here, and each connection reads rows and writes values only by what its own server described. If a column changes type so that a query no longer fits them, the query fails before it runs; Postgres.js then runs the query once more with a fresh description and prepares the statement again with the new types, unless it was sent in a transaction or on a reserved connection, where the error is returned and the next query is prepared afresh. Once any connection sees a statement describe differently, the other connections prepare it again before they next use it. Where the server can still cast the old parameter type to the new one, such as `json` to `text`, on a connection that has not yet seen the change, there is no error to act on, and the value is stored as that cast gives it; use `prepare: false` if columns change type while the application runs. + +### Connection poolers + +Postgres.js is tested through PgBouncer in session mode and in transaction mode, with and without its support for prepared statements. + +| Pooler mode | Options | What does not work | +| ----------- | ------- | ------------------ | +| Session | none | Nothing, apart from what the pooler itself refuses | +| Transaction, with [`max_prepared_statements`](https://www.pgbouncer.org/config.html#max_prepared_statements) (PgBouncer 1.21+) | none | `LISTEN`, and `DEALLOCATE` sent as SQL | +| Transaction, without | `prepare: false` | `LISTEN`, and named prepared statements | + +In both transaction modes a session belongs to a client only for the length of a transaction, so anything that has to outlive one, like `SET`, `LISTEN` or a temporary table, only works inside `sql.begin` or not at all. Use a direct connection, or a pooler in session mode, for `sql.listen` and `sql.subscribe`. + +With `max_prepared_statements`, PgBouncer keeps one prepared statement on each server connection for every query text and set of parameter types, shared by all its clients. After a column changes type, a connection may be handed the statement prepared before the change, which still describes the old parameter types; where the server can cast the old type to the new one, there is no error to act on. Use `prepare: false` through PgBouncer if columns change type while the application runs. + +PgBouncer refuses startup parameters it does not know, so a `connection` option like `{ 'some.var': 1 }` needs [`ignore_startup_parameters`](https://www.pgbouncer.org/config.html#ignore_startup_parameters) or `SET` inside a transaction instead. The pid in `state` is the pooler's, not the server's, so `pg_terminate_backend(state.pid)` does not end the session. + +## Custom Types + +You can add ergonomic support for custom types, or simply use `sql.typed(value, type)` inline, where type is the PostgreSQL `oid` for the type and the correctly serialized string. _(`oid` values for types can be found in the `pg_catalog.pg_type` table.)_ + +Adding Query helpers is the cleanest approach which can be done like this: + +```js +const sql = postgres({ + types: { + rect: { + // The pg_types oid to pass to the db along with the serialized value. + to : 1337, + + // An array of pg_types oids to handle when parsing values coming from the db. + from : [1337], + + //Function that transform values before sending them to the db. + serialize : ({ x, y, width, height }) => [x, y, width, height], + + // Function that transforms values coming from the db. + parse : ([x, y, width, height]) => { x, y, width, height } + } + } +}) + +// Now you can use sql.typed.rect() as specified above +const [custom] = await sql` + insert into rectangles ( + name, + rect + ) values ( + 'wat', + ${ sql.typed.rect({ x: 13, y: 37, width: 42, height: 80 }) } + ) + returning * +` + +// custom = { name: 'wat', rect: { x: 13, y: 37, width: 42, height: 80 } } + +``` + +A type whose oid isn't fixed, such as one from an extension, can be given by name instead, with `schema.name` allowed. Names are looked up when the pool starts, along with the type's array type, and queries wait for that. A name that doesn't exist rejects queries with `TYPE_NOT_FOUND`, and the lookup is tried again a second later, so a type created afterwards is found. Types by name need `fetch_types`. + +```js +const sql = postgres({ + types: { + vector: { + to : 'vector', + from : ['vector'], + serialize : x => '[' + x.join(',') + ']', + parse : x => JSON.parse(x) + } + } +}) + +await sql`insert into items ${ sql({ embedding: sql.typed.vector([1, 2, 3]) }) }` +``` + +### Custom socket + +Easily do in-process ssh tunneling to your database by providing a custom socket for Postgres.js to use. The function (optionally async) is called with the options and the host and port to connect to, and must return a socket-like duplex stream. If the socket has done TLS itself, set `negotiated: true` on it so Postgres.js does not ask the server for TLS again. + +Here's a sample using [ssh2](https://github.com/mscdex/ssh2) + +```js +import ssh2 from 'ssh2' + +const sql = postgres({ + ...options, + socket: ({ host: [host], port: [port] }) => new Promise((resolve, reject) => { + const ssh = new ssh2.Client() + ssh + .on('error', reject) + .on('ready', () => + ssh.forwardOut('127.0.0.1', 12345, host, port, + (err, socket) => err ? reject(err) : resolve(socket) + ) + ) + .connect(sshOptions) + }) +}) +``` + +## Teardown / Cleanup + +To ensure proper teardown and cleanup on server restarts use `await sql.end()` before `process.exit()`. + +`await sql.close()` closes every connection once the queries on it have finished, but leaves the pool usable: the next query opens a connection again. + +Calling `sql.end()` will reject new queries and return a Promise which resolves when all queries are finished and the underlying connections are closed. If a `{ timeout }` option is provided any pending queries will be rejected once the timeout (in seconds) is reached and the connections will be destroyed. + +`await using` ends the pool when it goes out of scope: + +```js +{ + await using sql = postgres() + await sql`select 1` +} // sql.end() has been awaited here +``` + +For scripts that should exit when their work is done, without calling `sql.end()`, `unref_sockets: true` stops idle connections from keeping the process alive, like `allowExitOnIdle` in node-postgres. Connections with queries in flight still do. + +With `min`, the pool keeps that many connections open once it has been used, and `idle_timeout` closes connections only above that number. `sql.close()` lets them close; the next query opens them again. + +#### Sample shutdown using [Prexit](https://github.com/porsager/prexit) + +```js +import prexit from 'prexit' + +prexit(async () => { + await sql.end({ timeout: 5 }) + await new Promise(r => server.close(r)) +}) +``` + +## Reserving connections + +### `await sql.reserve()` + +The `reserve` method pulls out a connection from the pool, and returns a client that wraps the single connection. This can be used for running queries on an isolated connection. + +```ts +const reserved = await sql.reserve() +await reserved`select * from users` +await reserved.release() +``` + +### `reserved.release()` + +Once you have finished with the reserved connection, call `release` to add it back to the pool. `using reserved = await sql.reserve()` releases it when it goes out of scope. + +## Tracing + +Postgres.js publishes what it does on Node.js [diagnostics channels](https://nodejs.org/api/diagnostics_channel.html), so a tracer or a metrics library can follow every query without an option or a wrapper. Nothing is published while nobody subscribes, and a query costs nothing measurable then. Diagnostics channels are there on Node.js, Bun and Cloudflare Workers. + +| Channel | Kind | Published for | +| ------- | ---- | ------------- | +| `postgres:query` | [tracing channel](https://nodejs.org/api/diagnostics_channel.html#class-tracingchannel) | Every query, from when it is sent off until it settles | +| `postgres:connect` | tracing channel | Every attempt to connect to a host, up to a ready connection or an error | +| `postgres:transaction` | tracing channel | Every `sql.begin`, up to its commit or rollback | +| `postgres:pool` | channel | Connections opening, going idle, being leased and released, closing, and queries waiting | +| `postgres:notice` | channel | Every notice from the server | + +A tracing channel publishes `start` and `end` around the sending of the query, `error` if it fails, and `asyncStart` and `asyncEnd` when it settles, all with the same context object, which fills in as the query goes along. `start` runs in the async context of the code that made the query, so a span started there gets the right parent. + +#### `postgres:query` + +| Field | | +| ----- | - | +| `query` | The text sent, with `$1`, `$2` for the parameters | +| `parameters` | The values, only with `debug: true` | +| `statement` | The name it is prepared as, `''` if unnamed | +| `database`, `user` | As connected with | +| `connection`, `host`, `port` | The connection it ran on, once sent | +| `command`, `count` | The command tag and the number of rows, once done | +| `queued`, `sent`, `firstByte`, `complete` | Times in milliseconds from `performance.now()` | +| `result`, `error` | What it resolved or rejected with | + +#### `postgres:connect` + +`host`, `port`, `path`, `database`, `user`, `ssl` and `sslnegotiation`, then `result` with the backend `pid`, `status`, `readOnly` and `standby`, or `error`. + +#### `postgres:transaction` + +`mode`, `database`, `user`, `connection`, `host`, `port`, and `outcome`: `'commit'`, `'rollback'` or `'prepare'`. + +#### `postgres:pool` and `postgres:notice` + +Pool messages have an `event` (`open`, `idle`, `wait`, `lease`, `release` or `close`), the `connection`, `host`, `port` and `database`, and the pool's `stats` at that moment. `lease` and `release` also have the `kind` of lease and `lease` how many milliseconds it `waited`; `close` has the `error`. Notices come as `{ notice, connection, host, port, database }`. + +#### OpenTelemetry + +Spans following the [semantic conventions for PostgreSQL](https://opentelemetry.io/docs/specs/semconv/db/postgresql/) take a few lines: + +```js +import dc from 'node:diagnostics_channel' +import { trace, SpanKind, SpanStatusCode } from '@opentelemetry/api' + +const tracer = trace.getTracer('postgres.js') +const spans = new WeakMap() + +dc.tracingChannel('postgres:query').subscribe({ + start(x) { + spans.set(x, tracer.startSpan(x.database, { + kind: SpanKind.CLIENT, + attributes: { + 'db.system.name': 'postgresql', + 'db.namespace': x.database, + 'db.query.text': x.query ?? undefined + } + })) + }, + error(x) { + const span = spans.get(x) + span.recordException(x.error) + span.setStatus({ code: SpanStatusCode.ERROR, message: x.error.message }) + span.setAttribute('error.type', x.error.code || x.error.name) + x.error.severity && span.setAttribute('db.response.status_code', x.error.code) + }, + asyncEnd(x) { + const span = spans.get(x) + span.setAttributes({ + 'db.query.text': x.query ?? undefined, + 'db.operation.name': x.command ?? undefined, + 'db.response.returned_rows': x.count ?? undefined, + 'server.address': x.host ?? undefined, + 'server.port': x.port ?? undefined + }) + x.command && span.updateName(x.command + ' ' + x.database) + span.end() + }, + end() {}, + asyncStart() {} +}) +``` + +#### Metrics + +```js +import dc from 'node:diagnostics_channel' + +dc.subscribe('tracing:postgres:query:asyncEnd', x => { + histogram.record(x.complete - x.queued, { command: x.command, error: !!x.error }) +}) + +dc.subscribe('postgres:pool', x => { + gauge.record(x.stats.waiting) +}) +``` + +## Error handling + +Errors are all thrown to related queries and never globally. Errors coming from database itself are always in the [native Postgres format](https://www.postgresql.org/docs/current/errcodes-appendix.html), and the same goes for any [Node.js errors](https://nodejs.org/api/errors.html#errors_common_system_errors) eg. coming from the underlying connection. + +The stack of a query error leads to the line in your code that made the query, not into Postgres.js, even when the error comes back long after it was sent. + +Query errors will also contain the `query` string and the `parameters`. These are not enumerable to avoid accidentally leaking confidential information in logs. To log these it is required to specifically access `error.query` and `error.parameters`, or set `debug: true` in options. + +An error from the server is a `PostgresError`, with the fields of the server's [error message](https://www.postgresql.org/docs/current/protocol-error-fields.html) as properties: + +```js +import postgres, { PostgresError } from 'postgres' + +try { + await sql`insert into users ${ sql(user) }` +} catch (error) { + if (error instanceof PostgresError && error.code === '23505') + return { taken: error.constraint_name } + throw error +} +``` + +| Property | | +| --- | --- | +| `code` | The [SQLSTATE](https://www.postgresql.org/docs/current/errcodes-appendix.html), such as `'23505'` for a unique violation | +| `message`, `severity`, `severity_local` | Always there | +| `detail`, `hint`, `position`, `where` | When the server sends them | +| `schema_name`, `table_name`, `column_name`, `data_type_name`, `constraint_name` | For errors about a specific object | +| `file`, `line`, `routine` | Where in the server it happened | +| `query`, `parameters`, `types` | The query that failed; not enumerable unless `debug` is on | + +`JSON.stringify(error)` includes the message and every enumerable field. + +Errors from the connection are Node.js errors such as `ECONNREFUSED`, or one with a `code` from the list below. Every error Postgres.js throws has a `code`. + +There are also the following errors specifically for this library. + +##### UNSAFE_TRANSACTION +> Only use sql.begin, sql.reserved or max: 1 + +To ensure statements in a transaction runs on the same connection (which is required for them to run inside the transaction), you must use [`sql.begin(...)`](#transactions), a [reserved connection](#reserving-connections) or only allow a single connection in options (`max: 1`). A query on the pool that leaves its connection in a transaction is rolled back and rejected with this error. A query that looks like it may start a transaction runs alone on its connection, so no other query ends up in it, and one that opens and closes its own transaction, such as a migration file with `BEGIN` and `COMMIT`, runs as it is. + +##### UNDEFINED_VALUE +> Undefined values are not allowed + +Postgres.js won't accept `undefined` as values in tagged template queries since it becomes ambiguous what to do with the value. If you want to set something to null, use `null` explicitly. + +##### MESSAGE_NOT_SUPPORTED +> X (X) is not supported + +Whenever a message is received from Postgres which is not supported by this library. Feel free to file an issue if you think something is missing. + +##### PROTOCOL_ERROR +> The server sent a message with an invalid length (-1) + +The server, or something between it and Postgres.js, sent a message whose length is below 4 bytes or above 1 GiB. The connection is closed, and its queries reject with this error or with a connection error caused by it. + +##### NUL_CHARACTER +> The connection parameter database contains a NUL character + +A connection parameter such as `database`, `user` or `application_name` contains `\0`. The startup message separates parameters with NUL, so the rest would be read as more parameters; the connection is refused instead. + +##### MAX_PARAMETERS_EXCEEDED +> Max number of parameters (65534) exceeded + +The postgres protocol doesn't allow more than 65534 (16bit) parameters. If you run into this issue there are various workarounds such as using `sql([...])` to escape values instead of passing them as parameters. + +##### SASL_SIGNATURE_MISMATCH +> Message type X not supported + +When using SASL authentication the server responds with a signature at the end of the authentication flow which needs to match the one on the client. This is to avoid [man-in-the-middle attacks](https://en.wikipedia.org/wiki/Man-in-the-middle_attack). If you receive this error the connection was canceled because the server did not reply with the expected signature. + +##### NOT_TAGGED_CALL +> Query not called as a tagged template literal + +Making queries has to be done using the sql function as a [tagged template](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Tagged_templates). This is to ensure parameters are serialized and passed to Postgres as query parameters with correct types and to avoid SQL injection. + +##### AUTH_TYPE_NOT_IMPLEMENTED +> Authentication type X is not supported + +Postgres supports many different authentication types. This one is not supported. Cleartext, MD5, SCRAM-SHA-256 and SCRAM-SHA-256-PLUS are. + +##### SASL_MECHANISM_NOT_SUPPORTED / SASL_NONCE_MISMATCH +The server offered no SASL mechanism Postgres.js supports (SCRAM-SHA-256 or, over TLS, SCRAM-SHA-256-PLUS), or its answer did not continue the client's nonce, which means something between them interfered. + +##### CHANNEL_BINDING_REQUIRED +> channel_binding is require, but the server did not offer it + +`channel_binding` is `'require'`, and the connection could not be bound to the server's certificate: it is not over TLS, the server did not offer SCRAM-SHA-256-PLUS, asked for a cleartext or MD5 password (which is then not sent) or authenticated without SCRAM, or the certificate could not be hashed for it. + +##### SSL_NOT_SUPPORTED +> The server does not support SSL connections + +`ssl` was `require` or stricter and the server has no TLS. + +##### SSL_NEGOTIATION_NOT_SUPPORTED +`sslnegotiation: 'direct'` was asked for in Cloudflare Workers, which cannot do it. + +##### TRANSACTION_ROLLED_BACK +> The server rolled back the transaction instead of committing it + +`sql.begin` sent COMMIT and the server answered that it rolled back instead, so nothing in the transaction was saved. + +> The query was not sent, the transaction was rolled back with sql.rollback() + +A query, savepoint or nested `sql.begin` was made after `sql.rollback()` in the same transaction or savepoint. + +##### ARRAY_REMOVED +> sql.array() is removed in v4, pass the array as it is + +Arrays are typed from what they hold, so they need no helper. Add a cast where the server should treat it as something else, like `${ ids }::int[]`. + +##### CONNECTION_CLOSED +> write CONNECTION_CLOSED host:port + +This error is thrown if the connection was closed without an error. This should not happen during normal operations, so please create an issue if this was unexpected. + +##### CONNECTION_ENDED +> write CONNECTION_ENDED host:port + +This error is thrown if the user has called [`sql.end()`](#teardown--cleanup) and performed a query afterward. + +##### CONNECTION_DESTROYED +> write CONNECTION_DESTROYED host:port + +This error is thrown for any queries that were pending when the timeout to [`sql.end({ timeout: X })`](#teardown--cleanup) was reached. + +##### QUEUE_TIMEOUT +> Waited more than 5 seconds for a connection + +A query, transaction or reserve waited longer than `queue_timeout` for a connection. It was never sent. + +##### TYPE_NOT_FOUND +> The type vector does not exist + +A custom type given by name was not found when the pool looked it up. + +##### NESTED_TRANSACTION_MODE +> A nested transaction runs in a savepoint, which can not change the transaction mode + +A nested `sql.begin` was given a mode other than its transaction's, or called `sql.prepare()`. + +##### TLS_HANDSHAKE_FAILED +> The TLS connection to host:port was lost before the server answered + +On Cloudflare Workers: the TLS handshake could not be completed, most often because the server's certificate is not signed by a publicly trusted CA. Workers always verify the certificate; Hyperdrive connects to such servers for you. + +##### NO_COLUMNS +> The insert helper got no columns + +An insert or update helper was given an empty object or an empty list of columns, which would make invalid SQL. + +##### CONNECT_TIMEOUT +> write CONNECT_TIMEOUT host:port + +This error is thrown if the startup phase of the connection (tcp, protocol negotiation, and auth) took more than the default 30 seconds or what was specified using `connect_timeout` or `PGCONNECT_TIMEOUT`. + +##### COPY_IN_PROGRESS +> You cannot execute queries during copy + +This error is thrown if trying to run a query during a copy operation (writable / readable). + +## TypeScript support + +`postgres` has TypeScript support. You can pass a row list type for your queries in this way: +```ts +interface User { + id: number + name: string +} + +const users = await sql`SELECT * FROM users` +users[0].id // ok => number +users[1].name // ok => string +users[0].invalid // fails: `invalid` does not exists on `User` +``` + +However, be sure to check the array length to avoid accessing properties of `undefined` rows: +```ts +const users = await sql`SELECT * FROM users WHERE id = ${id}` +if (!users.length) + throw new Error('Not found') +return users[0] +``` + +You can also prefer destructuring when you only care about a fixed number of rows. +In this case, we recommend you to prefer using tuples to handle `undefined` properly: +```ts +const [user]: [User?] = await sql`SELECT * FROM users WHERE id = ${id}` +if (!user) // => User | undefined + throw new Error('Not found') +return user // => User + +// NOTE: +const [first, second]: [User?] = await sql`SELECT * FROM users WHERE id = ${id}` // fails: `second` does not exist on `[User?]` +const [first, second] = await sql<[User?]>`SELECT * FROM users WHERE id = ${id}` // don't fail : `second: User | undefined` +``` + +The types that matter are also exported by name: + +```ts +import postgres, { type Sql, type TransactionSql, type Row } from 'postgres' + +function users(sql: Sql) { + return sql`select * from users` +} +``` + +A function that should run on the pool, in a transaction or on a reserved connection alike takes `ISql`, which is what the three have in common: + +```ts +import postgres, { type ISql } from 'postgres' + +function users(sql: ISql) { + return sql`select * from users` +} + +await users(sql) +await sql.begin(sql => users(sql)) +``` + +`PostgresError` is exported by name too, so `import { PostgresError } from 'postgres'` works with `instanceof`. + +The types are checked against a test of their own with TypeScript 4.9 and later. Feel free to open an issue if you have trouble with types. + +## Upgrading from v3 + +The API is the same as v3's, and most code runs unchanged. Check these before upgrading. + +### Parameter types are decided by the server + +v3 typed a `Date` as `timestamptz`, a boolean as `boolean`, a `Buffer` as `bytea`, a `bigint` as `int8` and arrays of these by their first element. v4 sends them without a type and the server decides from the query (see [Parameter types](#parameter-types)). `infer: true` keeps v3's behaviour: + +```js +const sql = postgres({ infer: true }) +``` + +Nothing changes for `timestamptz` columns, for values written to a column of their own type, for strings and numbers, or for anything with a cast. What does change: + +**Dates and times outside UTC.** When the session's `TimeZone` or the Node.js process isn't UTC: + +- A `Date` written to a `timestamp` column, or compared with one, is taken as UTC instead of the session's local time. +- A `Date` written to a `date` column, compared with one or cast with `::date`, takes the day in UTC instead of in the session's time zone, so near midnight it can be a day off. +- A `timestamp` column is read as UTC instead of the process's local time, so rows v3 wrote as local time are read back shifted by the UTC offset. + +This query shows whether that concerns you: + +```sql +select current_setting('TimeZone') as session_time_zone, + table_schema, table_name, column_name, data_type +from information_schema.columns +where data_type in ('timestamp without time zone', 'date', 'time without time zone') + and table_schema not in ('pg_catalog', 'information_schema') +``` + +If it returns no columns, or the time zone is `UTC` and so is your Node.js process (`TZ=UTC`, the default in most containers), nothing changes. Otherwise use `infer: true`, or move those columns to `timestamptz`, or cast the parameters (`${ date }::timestamptz`). + +**Errors that need a cast.** A `Date` given where the query doesn't decide its type is now an error from the server, with the fix in the query: + +| Query | Error | With a cast | +| ----- | ----- | ----------- | +| ``date_trunc('day', ${ date })``, `extract`, `to_char`, `to_json`, `jsonb_build_object` | `42725` function is not unique, or `42P18` / `42804` could not determine the type | `${ date }::timestamptz` | +| ``${ date } + interval '1 day'`` | `22007` invalid input syntax for type interval | `${ date }::timestamptz + interval '1 day'` | +| A `Date` written to a `time` column | `22007` invalid input syntax for type time | `${ date }::timestamptz::time` | +| ``${ 2n ** 60n } + 1`` | `22003` out of range for type integer | `${ n }::int8 + 1` | + +**Values that come back as text.** A boolean, `Date`, `Buffer` or array that is only selected back, as in ``select ${ true } as x``, comes back as a string, since the server reads it as text; cast it to get the type back. A `Buffer` written to a `text` column is stored as its text instead of `\x` hex, a `Date` written to a `text` column as an ISO string ending in `Z`, and `${ 10n } + 1` gives the number `11` instead of the string `'11'`. A string such as `'yes'` or `'t'` for a `boolean` is now read by the server as `true`; v3 wrote any string for a `boolean` as `false`. + +**One more round trip.** A query whose parameters are all dates, booleans, `bigint`s, `Buffer`s or arrays of these is described before its first run on each connection, as queries with strings and numbers already were. + +### Everything else + +- **Runtimes.** Node.js 20 or later, Bun and Cloudflare Workers; Deno runs the npm package. Postgres.js is an ES module; `require('postgres').default` works on Node.js 20.19 and 22.12 and later. +- **`sql.array()` is removed.** Pass the array as it is, with a cast where the query doesn't decide its type: `${ ids }::int[]`. +- **Transactions are stricter.** A `COMMIT` the server answers with `ROLLBACK` rejects with `TRANSACTION_ROLLED_BACK`, a query on a transaction or reserved connection after it ended rejects, a query that can't be built inside a transaction aborts it, and a `begin` sent outside `sql.begin`, a reserved connection or `max: 1` rejects with `UNSAFE_TRANSACTION` and is rolled back. +- **Domains** are read and written as their base type, so a domain over `int[]` comes back as an array of numbers. +- **`infinity` timestamps** are `Infinity` and `-Infinity` instead of an invalid `Date`. +- **TypeScript.** The types are an ES module with a default export and named types: `import postgres, { type Sql } from 'postgres'`. + +The [changelog](./CHANGELOG.md) has every change, with the smaller ones about connections and errors. + +## Migration tools + +Postgres.js doesn't come with any migration solution since it's way out of scope, but here are some modules that support Postgres.js for migrations: + +- https://github.com/porsager/postgres-shift +- https://github.com/lukeed/ley +- https://github.com/JAForbes/pgmg + +## Thank you + +A really big thank you to [@JAForbes](https://twitter.com/jmsfbs) who introduced me to Postgres and still holds my hand navigating all the great opportunities we have. + +Thanks to [@ACXgit](https://twitter.com/andreacoiutti) for initial tests and dogfooding. + +Also thanks to [Ryan Dahl](https://github.com/ry) for letting me have the `postgres` npm package name. diff --git a/node_modules/postgres/package.json b/node_modules/postgres/package.json new file mode 100644 index 0000000..6a29faa --- /dev/null +++ b/node_modules/postgres/package.json @@ -0,0 +1,39 @@ +{ + "name": "postgres", + "version": "4.0.0", + "description": "Fastest full featured PostgreSQL client for Node.js, Bun and Cloudflare Workers", + "type": "module", + "main": "src/index.js", + "types": "types/index.d.ts", + "exports": { + ".": { + "types": "./types/index.d.ts", + "workerd": "./src/cf.js", + "default": "./src/index.js" + } + }, + "engines": { + "node": ">=20" + }, + "scripts": { + "test": "node tests/unit && node tests/index.js && node tests/simulate.js", + "test:unit": "node tests/unit", + "test:integration": "node tests/index.js", + "test:simulate": "node tests/simulate.js", + "coverage": "node tests/coverage.js", + "test:types": "cd types && npm install && npm test", + "test:cf": "sh tests/cf/run.sh", + "lint": "eslint src tests" + }, + "files": [ + "/src/*.js", + "/types/index.d.ts" + ], + "author": "Rasmus Porsager (https://www.porsager.com)", + "funding": { + "type": "individual", + "url": "https://github.com/sponsors/porsager" + }, + "license": "Unlicense", + "repository": "porsager/postgres" +} diff --git a/node_modules/postgres/src/build.js b/node_modules/postgres/src/build.js new file mode 100644 index 0000000..d4accdb --- /dev/null +++ b/node_modules/postgres/src/build.js @@ -0,0 +1,292 @@ +import { Errors } from './errors.js' +import { Parameter, infer } from './types.js' + +export const isQuery = Symbol('query') + +class NotTagged { + then() { notTagged() } + catch() { notTagged() } + finally() { notTagged() } +} + +export class Identifier extends NotTagged { + constructor(value) { + super() + this.value = escapeIdentifier(value) + } +} + +export class Join { + constructor(separator, items) { + this.separator = separator + this.items = items + } +} + +export const joinStrings = Object.assign(['', ''], { raw: ['', ''] }) + +export class Builder extends NotTagged { + constructor(first, rest) { + super() + this.first = first + this.rest = rest + } +} + +export function build(query, options) { + const values = [] + , oids = [] + , o = { transform: options.transform, infer: options.infer !== false, resolve: options.resolve, values, oids, dynamic: !query.tagged } + + const text = query.tagged + ? stringify(query, o) + : (query.args.forEach(x => value(x, o)), '' + query.strings[0]) + + if (values.length >= 65534) + throw Errors.generic('MAX_PARAMETERS_EXCEEDED', 'Max number of parameters (65534) exceeded') + + const types = oids.join() + return { strings: query.strings, dynamic: o.dynamic, types, text, values, oids } +} + +function stringify(q, o) { + let string = q.strings[0] + + for (let i = 1; i < q.strings.length; i++) + string += part(string, q.args[i - 1], o, q.strings[i]) + q.strings[i] + + return string +} + +function part(before, x, o, after = '') { + if (x instanceof Builder || x instanceof Identifier || isFragment(x) || (Array.isArray(x) && isFragment(x[0]))) + o.dynamic = true + + return isFragment(x) && x.strings === joinStrings ? joined(x.args[0], o, before, after) + : x instanceof Join ? joined(x, o, '', '') + : x instanceof Builder ? helper(before, x, o) + : isFragment(x) ? fragment(x, o) + : x instanceof Identifier ? x.value + : Array.isArray(x) && isFragment(x[0]) ? x.reduce((acc, x) => acc + ' ' + fragment(x, o), '') + : value(x, o) +} + +function joined(join, o, before, after) { + let text = '' + join.items.forEach((item, i) => { + i > 0 && (text = spaced(text, fragment(join.separator, o))) + text = spaced(text, part('', item, o)) + }) + before && text && !/\s$/.test(before) && !/^\s/.test(text) && (text = ' ' + text) + after && text && !/^\s/.test(after) && !/\s$/.test(text) && (text = text + ' ') + return text +} + +function spaced(a, b) { + return a && b && !/\s$/.test(a) && !/^\s/.test(b) ? a + ' ' + b : a + b +} + +function isFragment(x) { + return !!x && x[isQuery] === true +} + +function fragment(q, o) { + return q.tagged ? stringify(q, o) : q.strings[0] +} + +export function value(x, o) { + let v = x instanceof Parameter ? x.value : x + if (v === undefined) { + v = o.transform.undefined + if (v === undefined) + throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed') + x instanceof Parameter || (x = v) + } + o.values.push(v) + o.oids.push(x instanceof Parameter ? o.resolve(x.type) : o.infer ? infer(x) : 0) + return '$' + o.values.length +} + +const builders = { + values, + in: (...xs) => { + const x = values(...xs) + return x === '()' ? '(null)' : x + }, + select, + update, + insert, + call +} + +function call(first, rest, o) { + if (first === null || typeof first !== 'object' || Array.isArray(first) || isFragment(first)) + return select(first, rest, o) + + return columns(first, rest).map(x => + escapeIdentifier(column(x, o)) + ' => ' + part('values', first[x], o) + ).join(',') +} + +const clauses = { in: 'in', values: 'values', select: 'select', returning: 'select', set: 'update', distinct: 'select' } + , stops = new Set([ + 'from', 'where', 'on', 'to', 'join', 'group', 'order', 'by', 'having', 'limit', 'offset', 'union', + 'intersect', 'except', 'using', 'and', 'or', 'when', 'then', 'else', 'with', 'table', 'grant', + 'revoke', 'delete', 'update', 'case', 'not', 'like', 'ilike', 'between', 'is', 'exists', 'conflict', + 'do', 'nothing', 'window', 'over', 'partition', 'filter', 'lateral', 'cross', 'inner', 'left', 'right', + 'full', 'outer', 'natural', 'into' + ]) + +function helper(before, x, o) { + const kind = context(before) + return kind ? builders[kind](x.first, x.rest, o) : identifiers(typeof x.first === 'string' ? [x.first].concat(x.rest) : x.first, o) +} + +function context(sql) { + const words = [] + + let i = sql.length - 1 + , depth = 0 + + while (i >= 0) { + const c = sql[i] + if (c === ')') { + depth++ + i-- + } else if (c === '(') { + if (depth === 0) { + const word = previous(sql, i - 1) + if (words.length === 0) + return word === 'in' || word === 'values' ? word : word && !clauses[word] && !stops.has(word) ? 'call' : 'select' + return 'select' + } + depth-- + i-- + } else if (c === '\'' || c === '"') { + const end = i + i-- + while (i >= 0 && !(sql[i] === c && sql[i - 1] !== c)) + sql[i] === c ? i -= 2 : i-- + i-- + if (sql[i] === '.') + i-- + else + depth === 0 && c === '"' && words.push(sql.slice(i + 1, end + 1)) + } else if (/[a-z_0-9$]/i.test(c)) { + const end = i + 1 + while (i >= 0 && /[a-z_0-9$.]/i.test(sql[i])) + i-- + const word = depth === 0 && sql.slice(i + 1, end).toLowerCase() + if (word && clauses[word]) + return clauses[word] + if (word === 'into') + return insert_into(words, sql, i) ? 'insert' : null + if (word && stops.has(word)) + return null + word && words.push(word) + } else { + i-- + } + } + return null +} + +function previous(sql, i) { + while (i >= 0 && /\s/.test(sql[i])) + i-- + + if (sql[i] === '"') + return '"' + + const end = i + 1 + while (i >= 0 && /[a-z_0-9$.]/i.test(sql[i])) + i-- + + return sql.slice(i + 1, end).toLowerCase() +} + +function insert_into(words, sql, i) { + const target = words.length === 1 || (words.length === 3 && words[1] === 'as') + return target && previous(sql, i) === 'insert' +} + +function valuesBuilder(first, columns, o) { + return first.map(row => + '(' + columns.map(x => part('values', row[x], o)).join(',') + ')' + ).join(',') +} + +function values(first, rest, o) { + const rows = Array.isArray(first) && first.length > 0 && first[0] !== null && typeof first[0] === 'object' && !isFragment(first[0]) + , picked = columns(rows ? first[0] : first, rest) + + return valuesBuilder(rows ? first : [first], picked, o) +} + +function update(first, rest, o) { + const picked = columns(first, rest) + picked.length || empty('update') + + return picked.map(x => + escapeIdentifier(column(x, o)) + '=' + part('values', first[x], o) + ) +} + +function insert(first, rest, o) { + if (Array.isArray(first) && first.every(x => typeof x === 'string')) + return '(' + escapeIdentifiers(first.concat(rest.flat()), o) + ')' + + const picked = columns(Array.isArray(first) ? first[0] || {} : first, rest) + picked.length || empty('insert') + + return '(' + escapeIdentifiers(picked, o) + ')values' + valuesBuilder(Array.isArray(first) ? first : [first], picked, o) +} + +function columns(first, rest) { + return rest.length ? rest.flat() : Object.keys(first) +} + +function empty(x) { + throw Errors.generic('NO_COLUMNS', 'The ' + x + ' helper got no columns') +} + +function identifiers(first, o) { + return Array.isArray(first) + ? first.map(x => member(x, o)).join(',') + : member(first, o) +} + +function member(x, o) { + return isFragment(x) ? fragment(x, o) : x instanceof Identifier ? x.value : escapeIdentifier(column(x, o)) +} + +function select(first, rest, o) { + typeof first === 'string' && (first = [first].concat(rest)) + if (Array.isArray(first)) + return identifiers(first, o) + + return columns(first, rest).map(x => { + const v = first[x] + return ( + isFragment(v) ? fragment(v, o) : + v instanceof Identifier ? v.value : + value(v, o) + ) + ' as ' + escapeIdentifier(column(x, o)) + }).join(',') +} + +function column(x, o) { + return o.transform.column.to ? o.transform.column.to(x) : x +} + +function escapeIdentifiers(xs, o) { + return xs.map(x => escapeIdentifier(column(x, o))).join(',') +} + +export function escapeIdentifier(x) { + return '"' + x.replace(/"/g, '""').replace(/\./g, '"."') + '"' +} + +export function notTagged() { + throw Errors.generic('NOT_TAGGED_CALL', 'Query not called as a tagged template literal') +} diff --git a/node_modules/postgres/src/cf.js b/node_modules/postgres/src/cf.js new file mode 100644 index 0000000..b4ad81f --- /dev/null +++ b/node_modules/postgres/src/cf.js @@ -0,0 +1,151 @@ +import { connect } from 'cloudflare:sockets' +import { EventEmitter } from 'node:events' +import { Buffer } from 'node:buffer' +import postgres, { PostgresError } from './index.js' +import { Errors } from './errors.js' +import { secured, direct } from './socket.js' + +export default function Postgres(a, b) { + return typeof a === 'string' || !a + ? postgres(a, { socket, ...b }) + : postgres({ socket, ...a }) +} + +Object.assign(Postgres, postgres) + +export { PostgresError } + +export async function socket(options, host, port) { + if (direct(options)) + throw Errors.generic('SSL_NEGOTIATION_NOT_SUPPORTED', 'sslnegotiation: direct needs ALPN, which Cloudflare Workers sockets do not offer') + + const tls = secured(options) + let raw = connect({ hostname: host, port }, { secureTransport: tls ? 'starttls' : 'off', allowHalfOpen: false }) + await raw.opened + + let secure = false + if (tls) { + const writer = raw.writable.getWriter() + , reader = raw.readable.getReader() + await writer.write(sslRequest) + const { value, done } = await reader.read() + writer.releaseLock() + reader.releaseLock() + + if (done) + throw Errors.connection('CONNECTION_CLOSED', options, host, port) + + if (value[0] === 83) { + raw = raw.startTls() + await raw.opened + secure = true + } else if (options.ssl !== 'prefer' && options.ssl !== 'allow') { + raw.close() + throw Errors.generic('SSL_NOT_SUPPORTED', 'The server does not support SSL connections') + } + } + + return Stream(raw, secure, host, port) +} + +const sslRequest = Buffer.from([0, 0, 0, 8, 4, 210, 22, 47]) + , chunk = 16384 + +function Stream(raw, secure, host, port) { + const x = new EventEmitter() + , writer = raw.writable.getWriter() + , reader = raw.readable.getReader() + + let paused = false + , wake = null + , closed = false + , pending = 0 + , answered = !secure + + const written = () => --pending === 0 && x.emit('drain') + + Object.assign(x, { + secure, + negotiated: true, + destroyed: false, + write(data) { + if (closed) + return false + + for (let i = 0; i < data.length; i += chunk) { + pending++ + writer.write(data.subarray(i, i + chunk)).then(written, fail) + } + return pending < 16 + }, + end(data) { + data && x.write(data) + writer.close().catch(() => {}) + }, + destroy() { + x.destroyed = true + raw.close().catch(() => {}) + finish() + }, + pause() { + paused = true + }, + resume() { + paused = false + wake && (wake(), wake = null) + }, + setKeepAlive() {}, + setNoDelay() {} + }) + + read() + return x + + function resumed() { + return new Promise(r => wake = r) + } + + async function read() { + try { + while (true) { + paused && await resumed() + const { value, done } = await reader.read() + + if (done) + break + + answered = true + x.emit('data', Buffer.from(value.buffer, value.byteOffset, value.byteLength)) + } + } catch (error) { + closed || x.emit('error', handshake(error)) + } + finish() + } + + function fail(error) { + closed || x.emit('error', handshake(error)) + x.destroy() + } + + function finish() { + if (closed) + return + + answered || x.destroyed || x.emit('error', handshake()) + closed = true + x.emit('close') + } + + function handshake(error) { + if (answered) + return error + + answered = true + + return Object.assign(Errors.generic('TLS_HANDSHAKE_FAILED', + 'The TLS connection to ' + host + ':' + port + ' was lost before the server answered. ' + + 'Workers could not complete the TLS handshake, most often because the server certificate is not trusted by a public CA' + ), { cause: error }) + } +} diff --git a/node_modules/postgres/src/connection.js b/node_modules/postgres/src/connection.js new file mode 100644 index 0000000..7267206 --- /dev/null +++ b/node_modules/postgres/src/connection.js @@ -0,0 +1,1226 @@ +import Stream from 'stream' +import * as p from './protocol.js' +import { Errors, queryError } from './errors.js' +import Result from './result.js' +import { CLOSE } from './query.js' +import { now, channels, listened } from './diagnostics.js' + +export const slow = 100 +export const notable = 5 + +const text = p.text + , noop = () => {} + , ending = /^\s*(commit|end|abort|rollback(?!\s+to\b)|prepare\s+transaction)\b/i + , limit = 1000 + , refused = 'postgres.js: query could not be built' + , skip = Symbol('skip') + , unknown = 100 + , states = new WeakMap() + , after = 16 + +let ids = 1 + , compiles = true + +export function Connection(ready, options, events) { + const { socket } = ready + , timers = options.timers + , defer = timers.nextTick || process.nextTick + , { transform } = options + , sent = [] + , pending = [] + , running = new Set() + , open = new Set() + , prepared = new Map() + , out = p.Writer() + , frames = p.Frames(frame, socket.shared, error => (connection.fatal = error, socket.destroy())) + + let blocker = null + , rolling = false + , fence = null + , drained = null + , status = ready.status + , flushing = false + , closed = null + , closing = null + , portals = 0 + , traced = 0 + , epoch = 0 + , headSince = 0 + , notables = 0 + + const connection = { + id: ids++, + host: ready.host, + port: ready.port, + backend: ready.backend, + parameters: ready.parameters, + prepared, + lease: null, + get status() { return status }, + get inflight() { return sent.length + pending.length }, + get exclusive() { return !!blocker && exclusive(blocker) }, + get copying() { return !!blocker && blocker.streaming && blocker.open }, + get closed() { return closed }, + get closing() { return !!closing }, + send, + simple, + describe, + local, + cancel, + close, + destroy, + ref: () => socket.ref(), + unref: () => socket.unref(), + backlog, + heavy, + get notable() { return notables > 0 } + } + + socket.ondata = x => frames.push(x) + socket.ondrain = ondrain + socket.onclose = onclose + ready.rest && ready.rest.length && frames.push(ready.rest) + socket.resume() + + return connection + + function ondrain() { + const x = drained + drained = null + x && x() + } + + function schedule(now) { + if (now || out.length >= 65536) + return flush() + + flushing || (flushing = true, defer(flush)) + return true + } + + function flush() { + flushing = false + if (closed) + return (out.take(), true) + + return out.length ? socket.write(out.take()) : true + } + + function holds(x) { + return x.describing + || (!!x.error && !x.done) + || (x.flushing && !x.synced) + || (x.streaming && x.open) + || (x.alone && !x.done) + } + + function exclusive(x) { + return x.flushing || x.streaming || x.alone + } + + function refresh() { + blocker && !holds(blocker) && (blocker = null) + release() + } + + function queue(x) { + if (closed) + return settleError(x, closed) + + if (blocker && blocker.streaming && blocker.open) + return settleError(x, Errors.generic('COPY_IN_PROGRESS', 'You cannot execute queries during copy')) + + x.query && (x.query.state = connection.backend) + if (fence) + pending.splice(pending.indexOf(fence), 0, x) + else if (x.ends && open.size) + pending.push(fence = x) + else if (blocker || pending.length) + pending.push(x) + else + return (write(x), schedule()) + + release() + } + + function release() { + while (!blocker && pending.length && pending[0] !== fence) + write(pending.shift()) + + schedule() + } + + function write(x) { + if (x.kind === 'local' && sent.length === 0) + return queueMicrotask(() => settle(x)) + + const mark = out.length + let result + try { + result = x.write(x) + } catch (error) { + x.own = error + result = skip + } + if (result === skip) { + out.truncate(mark) + x.fresh = null + x.parses = [] + x.portal = '' + x.describing = x.synced = x.flushing = x.open = false + if (!x.own || x.kind === 'step' || !connection.lease) { + x.kind = 'local' + x.cost >= notable && notables-- + x.cost = undefined + return sent.length === 0 ? queueMicrotask(() => settle(x)) : sent.push(x) + } + + x.kind = 'simple' + x.text = refused + x.results = [] + x.entry = null + sync(x, true) + } + x.fresh && register(x.fresh) + x.portal && x.kind === 'query' && open.add(x) + x.query && (x.query.active = sent.length === 0) + x.ends && epoch++ + x.epoch = epoch + options.scheduler && sent.length === 0 && (headSince = timers.now()) + sent.push(x) + holds(x) && (blocker = x) + x.trace && wrote(x) + } + + function sync(x, refuse) { + if (x.synced) + return + + x.synced = true + refuse ? p.query(out, refused) : p.sync(out) + schedule() + } + + function register(entry) { + const current = prepared.get(entry.name) + current && prepared.delete(entry.name) + prepared.set(entry.name, entry) + entry.owner.entry = entry + entry.owner.fresh = null + if (prepared.size <= limit) + return + + for (const [name, x] of prepared) { + if (x.state !== 'parsing') { + prepared.delete(name) + p.close(out, 'S', name) + return + } + } + } + + function drop(entry) { + prepared.get(entry.name) === entry && prepared.delete(entry.name) + } + + function send(query) { + const { statement } = query.wire + , x = Exchange('query', query, connection.lease, extended) + + x.statement = statement + x.ends = statement.ends === undefined ? (statement.ends = ending.test(statement.text)) : statement.ends + options.scheduler && cost(x) + queue(x) + } + + function cost(x) { + const { query } = x + query.cost && !query.cursorFn && !query.streaming && (x.cost = query.cost.est === undefined ? unknown : query.cost.est) + x.cost >= notable && notables++ + } + + function timed(x) { + const t = timers.now() + + if (x.cost !== undefined) { + x.cost >= notable && notables-- + const sample = t - headSince + , c = x.query.cost + c.est = c.est === undefined || sample > c.est ? sample : c.est + (sample - c.est) * 0.1 + events.ontimed && events.ontimed(sample, t) + } + + headSince = t + } + + function backlog(t) { + let w = 0 + for (let i = 0; i < sent.length; i++) { + const e = sent[i].cost || 0 + if (i === 0) { + const elapsed = t - headSince + w += elapsed < e ? e - elapsed : elapsed + } else { + w += e + } + } + + for (let i = 0; i < pending.length; i++) + w += pending[i].cost || 0 + + return w + } + + function heavy() { + for (let i = 0; i < sent.length; i++) { + if (sent[i].cost >= slow) + return true + } + + for (let i = 0; i < pending.length; i++) { + if (pending[i].cost >= slow) + return true + } + + return false + } + + function extended(x) { + const { query } = x + , { built } = query.wire + , statement = x.statement + , name = statement.name + , current = name ? prepared.get(name) : null + + if (query.cursorFn) { + x.rows = query.cursorRows + x.portal = transaction() ? 'c' + portals++ : '' + x.flushing = !x.portal + } + + x.streaming = x.open = !!query.streaming + + if (current && current.state === 'parsing' && current.oids === null) + throw Errors.generic('STATEMENT_PENDING', 'A statement was used before its description arrived') + + if (current && current !== x.previous && usable(current, statement)) { + x.entry = current + x.columns = current.columns + x.values = serialize(current.oids, built, current) + return run(x, name) + } + + if (x.retried) { + x.verify = true + p.parse(out, '', statement.text, built.oids) + p.describe(out, 'S', '') + p.flush(out) + x.describing = true + return + } + + const typed = !inferred(built) + name && (x.fresh = Entry(name, x, typed ? built.oids : null)) + current && p.close(out, 'S', name) + parse(x, name, statement.text, built.oids) + p.describe(out, 'S', name) + + if (!typed) { + p.flush(out) + x.describing = true + return + } + + x.learn = true + x.values = serialize(built.oids, built, x.fresh || {}) + run(x, name) + } + + function parse(x, name, text, oids) { + p.parse(out, name, text, oids) + x.parses.push(name) + } + + function run(x, name) { + const mark = out.length + try { + p.run(out, x.portal, name, x.values, x.rows, x.flushing) + } catch (error) { + out.truncate(mark) + throw error + } + x.flushing || (x.synced = true) + debug(x.statement.text, x.values, x.entry ? x.entry.oids : x.params || x.query.wire.built.oids) + } + + function usable(entry, statement) { + return entry.oids !== null && (entry.state === 'parsing' || (entry.state === 'ready' && entry.version === statement.version)) + } + + function learned(entry, statement) { + const shape = entry.oids.join() + ':' + entry.columns.map(x => x.type).join() + if (statement.shape !== shape) { + statement.shape === undefined || statement.version++ + statement.shape = shape + } + entry.version = statement.version + } + + function inferred(built) { + for (let i = 0; i < built.oids.length; i++) { + if (!built.oids[i]) + return true + } + return false + } + + function serialize(oids, built, cache) { + const serializers = cache.serializers || (cache.serializers = oids.map(events.serializer)) + , values = built.values + , out = new Array(values.length) + + for (let i = 0; i < values.length; i++) { + out[i] = values[i] === null ? null : serializers[i](values[i]) + out[i] === null || out[i] === undefined || typeof out[i] === 'string' || out[i] instanceof Uint8Array || Buffer.byteLength(out[i]) + } + + return out + } + + function transaction() { + return !!connection.lease && connection.lease.kind === 'transaction' + } + + function described(x) { + x.describing = false + const { built } = x.query.wire + , name = x.statement.name + , params = x.params || [] + , columns = x.columns || [] + + try { + if (x.verify) { + const previous = x.previous + if (previous && same(previous, params, columns)) { + if (x.original) { + x.own = x.original + return sync(x) + } + } else if (previous) { + stale(previous) + x.statement.version++ + } + x.values = serialize(params, built, {}) + return run(x, '') + } + const entry = x.entry + entry && (entry.oids = params, entry.columns = columns, learned(entry, x.statement)) + x.values = serialize(params, built, entry || {}) + run(x, name) + } catch (error) { + x.own = error + sync(x, !!connection.lease) + } + } + + function same(entry, params, columns) { + const a = entry.oids || [] + , b = entry.columns + + return !!b + && a.length === params.length && params.every((x, i) => x === a[i]) + && b.length === columns.length && columns.every((x, i) => x.type === b[i].type) + } + + function describe(statement, oids) { + return new Promise((resolve, reject) => { + const x = Exchange('describe', null, connection.lease, x => { + p.parse(out, '', statement.text, oids) + p.describe(out, 'S', '') + sync(x) + }) + x.resolve = resolve + x.reject = reject + queue(x) + }) + } + + function simple(query, sql) { + const x = Exchange('simple', query, connection.lease, x => { + debug(sql, [], []) + p.query(out, sql) + x.synced = true + }) + x.text = sql + x.results = [] + x.ends = ending.test(sql) + x.streaming = x.open = !!query.streaming + options.scheduler && cost(x) + queue(x) + } + + function local(query, error) { + queue(Exchange('query', query, connection.lease, () => { throw error })) + } + + function cancel(query) { + if (running.has(query) || (sent[0] && sent[0].query === query && sent[0].awaiting)) + return (query.aborted = Errors.generic('57014', 'canceling statement due to user request'), Promise.resolve()) + const i = pending.findIndex(x => x.query === query) + + if (i !== -1) { + const [x] = pending.splice(i, 1) + x === fence && (fence = null) + x.cost >= notable && notables-- + settleError(x, Errors.generic('57014', 'canceling statement due to user request')) + release() + return Promise.resolve() + } + + const x = sent.find(x => x.query === query) + if (!x) + return Promise.resolve() + + return x === sent[0] && query.active + ? ready.cancel() + : new Promise((resolve, reject) => x.cancel = { resolve, reject }) + } + + function close() { + closing || (closing = new Promise(r => { + connection.onended = r + idle() && terminate() + })) + return closing + } + + function idle() { + return sent.length === 0 && pending.length === 0 + } + + function terminate() { + if (closed) + return connection.onended && connection.onended() + + flush() + socket.end(p.Terminate()) + } + + function destroy(error) { + closing || (closing = Promise.resolve()) + socket.destroy(error) + } + + function onclose(error) { + if (closed) + return + + out.take() + blocker = null + fence = null + notables = 0 + closed = Errors.connection(closing ? 'CONNECTION_DESTROYED' : 'CONNECTION_CLOSED', options, ready.host, ready.port) + closed.cause = connection.fatal || error || undefined + const head = sent[0] + sent.splice(0).forEach(x => { + x.stream && x.stream.destroy(closed) + x.own ? settle(x) + : x === head && x.error && x.error.severity === 'FATAL' ? settleError(x, x.error) + : settleError(x, closed) + }) + pending.splice(0).forEach(x => x.own ? settle(x) : settleError(x, closed)) + running.forEach(query => query.settled || query.reject(decorate(query, closed))) + running.clear() + open.clear() + connection.onended && connection.onended() + events.onclose(connection, closed) + } + + function decorate(query, error) { + return queryError(error, query, options.debug) + } + + function settleError(x, error) { + x.kind === 'describe' + ? x.reject(error) + : x.query && !x.query.settled && x.query.reject(decorate(x.query, error)) + } + + function debug(text, values, oids) { + typeof options.debug === 'function' && options.debug(connection.id, text, values, oids) + } + + function wrote(x) { + const trace = x.trace + traced++ + trace.query = x.text || x.statement.text + trace.statement = x.statement ? x.statement.name : '' + trace.parameters = options.debug ? x.query.parameters : undefined + trace.connection = connection.id + trace.host = connection.host + trace.port = connection.port + trace.sent = now() + } + + function first() { + const x = sent[0] + x && x.trace && x.trace.firstByte === null && (x.trace.firstByte = now()) + } + + function frame(type, x, start, end) { + traced && first() + try { + type === 68 ? DataRow(x, start) : + type === 100 ? CopyData(x, start, end) : + type === 90 ? ReadyForQuery(x, start) : + type === 67 ? CommandComplete(x, start, end) : + type === 50 ? BindComplete() : + type === 49 ? ParseComplete() : + type === 51 ? null : + type === 116 ? ParameterDescription(x, start) : + type === 84 ? RowDescription(x, start) : + type === 110 ? NoData() : + type === 69 ? ErrorResponse(x, start, end) : + type === 115 ? PortalSuspended() : + type === 73 ? EmptyQueryResponse() : + type === 65 ? NotificationResponse(x, start) : + type === 78 ? NoticeResponse(x, start, end) : + type === 83 ? ParameterStatus(x, start) : + type === 71 ? CopyInResponse() : + type === 72 ? CopyOutResponse() : + type === 87 ? CopyBothResponse() : + type === 99 ? CopyDone() : + type === 86 ? unsupported('FunctionCallResponse') : + type === 118 ? unsupported('NegotiateProtocolVersion') : + null + } catch (error) { + const x = sent[0] + x ? fail(x, error) : destroy(error) + } + blocker && !holds(blocker) && (blocker = null, release()) + out.length && schedule() + } + + function fail(x, error) { + x.error = x.error || error + x.describing = false + x.open = false + sync(x) + } + + function unsupported(x) { + sent[0] && fail(sent[0], Errors.notSupported(x)) + } + + function ParseComplete() { + const x = sent[0] + , name = x.parses.shift() + + name && x.entry && x.entry.name === name && x.entry.owner === x && x.entry.state === 'parsing' && (x.entry.state = 'ready') + } + + function BindComplete() { + const x = sent[0] + x.bound = true + if (!x.columns && x.entry) { + x.columns = x.entry.columns + x.result.columns = x.columns + } + } + + function ParameterDescription(x, start) { + sent[0].params = p.parameterDescription(x, start) + } + + function RowDescription(x, start) { + received(sent[0], p.rowDescription(x, start, 0, column)) + } + + function NoData() { + received(sent[0], []) + } + + function received(x, columns) { + if (x.kind === 'simple' && x.result.command !== null) { + x.results.push(x.result) + x.result = new Result() + } + x.columns = columns + x.result.columns = columns + if (x.learn) { + x.learn = false + x.entry && x.entry.owner === x && (x.entry.columns = columns, learned(x.entry, x.statement)) + } + x.describing && described(x) + } + + function column(name, table, number, type) { + const parser = events.parser(type) + return { + name: transform.column.from ? transform.column.from(name) : name, + parser: parser.identity ? null : parser, + decode: events.decoder(type, parser), + table, + number, + type + } + } + + function DataRow(x, start) { + const item = sent[0] + , { query, columns } = item + , raw = query.isRaw + , from = raw !== true ? transform.value.from : null + , shape = item.shaped === columns ? item.reader : (item.shaped = columns, item.reader = Rows(columns)) + , fast = raw !== true && read(shape, !!raw, text, from) + , n = columns.length + , result = item.result + + let row + if (fast) { + row = fast(x, start + 7) + } else { + row = raw ? new Array(n) : {} + let i = start + 7 + for (let j = 0; j < n; j++) { + const length = (x[i] << 24) | (x[i + 1] << 16) | (x[i + 2] << 8) | x[i + 3] + , column = columns[j] + i += 4 + let value = null + if (length !== -1) { + value = raw === true + ? Buffer.from(x.subarray(i, i + length)) + : column.decode + ? column.decode(x, i, i + length) + : column.parser + ? column.parser(text(x, i, i + length)) + : text(x, i, i + length) + i += length + } + from && (value = from(value, column)) + raw ? row[j] = value : column.name === '__proto__' ? own(row, column.name, value) : row[column.name] = value + } + } + + const out = transform.row.from ? transform.row.from(row) : row + query.forEachFn + ? query.forEachFn(out, result) + : result[result.length] = out + } + + function CommandComplete(x, start, end) { + const item = sent[0] + , { command, count } = p.commandComplete(x, start, end) + , result = item.result + + result.command = command + result.count = count + result.state = connection.backend + result.statement = item + item.query && (item.query.source = item) + result.columns = result.columns || item.columns + + item.final && (item.stream && Object.assign(item.stream, { count, command }), item.final(), item.final = null) + + if (item.kind === 'simple') { + item.results.push(item.result) + item.result = new Result() + return + } + + if (item.rows) { + item.finished = true + item.flushing && sync(item) + result.count && (item.last = new Promise(r => r(item.query.cursorFn(result)))).catch(noop) + } + } + + function unsafe(item) { + const error = () => Errors.generic('UNSAFE_TRANSACTION', 'Only use sql.begin, sql.reserved or max: 1') + rolling = true + item.own = error() + sent.forEach(x => x.kind !== 'local' && (x.own = error())) + pending.unshift(Exchange('internal', null, null, x => (p.query(out, 'rollback'), x.synced = true))) + } + + function EmptyQueryResponse() { + const item = sent[0] + item.kind === 'simple' && (item.results.push(item.result), item.result = new Result()) + } + + async function PortalSuspended() { + const item = sent[0] + if (!item.flushing) + return (item.suspended = true) + + try { + item.awaiting = true + const next = await item.query.cursorFn(item.result) + item.awaiting = false + item.result = new Result() + if (closed || item.synced || sent[0] !== item) + return + if (item.query.aborted) + throw item.query.aborted + next === CLOSE + ? (p.close(out, 'P', ''), sync(item)) + : (p.execute(out, '', item.rows), p.flush(out), schedule()) + } catch (error) { + item.awaiting = false + if (closed || item.synced || sent[0] !== item) + return + fail(item, error) + } + + refresh() + } + + function ErrorResponse(x, start, end) { + const item = sent[0] + , error = Errors.postgres(p.error(x, start, end)) + + if (!item) + return (connection.fatal = error) + + item.stream && item.stream.destroy(error) + item.final && (item.final(error), item.final = null) + fail(item, error) + } + + function ReadyForQuery(x, start) { + status = p.readyForQuery(x, start) + frames.own(false) + const item = sent.shift() + options.scheduler && timed(item) + item.done = true + item.open = false + item.trace && traced-- + item.kind === 'internal' && (rolling = false) + status !== 'I' && !rolling && !item.lease && !connection.lease && options.max !== 1 && unsafe(item) + blocker === item && (blocker = null) + settle(item) + while (sent.length && sent[0].kind === 'local') + settle(sent.shift()) + release() + + const next = sent[0] + if (next && next.query) { + next.query.active = true + next.cancel && ready.cancel().then(next.cancel.resolve, next.cancel.reject) + } + + closing && idle() && terminate() + events.onready(connection) + } + + function settle(x) { + if (x.kind === 'internal') + return + + if (x.kind === 'describe') { + return x.error + ? x.reject(x.error) + : x.resolve({ params: x.params || [], columns: x.columns }) + } + + const { query } = x + , cursor = x.origin || (x.portal ? x : null) + cursor && (x.own || x.error || !x.suspended) && unfence(cursor) + + if (x.own) + return query.reject(decorate(query, x.own)) + + if (x.error) + return failed(x) + + if (x.suspended) + return suspended(x) + + x.last + ? x.last.then(() => query.settled || finish(x), error => query.settled || query.reject(decorate(query, error))) + : query.settled || finish(x) + } + + function unfence(cursor) { + if (!open.delete(cursor) || open.size || !fence) + return + fence = null + release() + } + + function failed(x) { + const entry = x.kind === 'query' ? x.entry : null + const parsing = x.fresh || (entry && entry.owner === x && entry.state === 'parsing') + + if (x.error.code === '42P05' && x.kind === 'query' && x.statement.name && parsing) { + entry && drop(entry) + x.statement.name += '_' + return retryable(x) ? again(x, null) : settleError(x, x.error) + } + + if (!entry) + return settleError(x, x.error) + + if (entry.owner === x && entry.state === 'parsing') + return (drop(entry), settleError(x, x.error)) + + if (x.error.code === '26000') { + drop(entry) + return retryable(x) ? again(x, null) : settleError(x, x.error) + } + + if (x.bound) + return settleError(x, x.error) + + if (retryable(x)) + return again(x, x.error) + + stale(entry) + settleError(x, x.error) + } + + function stale(entry) { + prepared.get(entry.name) === entry && (entry.state = 'stale') + } + + function retryable(x) { + return !x.retried + && !x.cancel + && !x.query.cancelled + && !x.query.cursorFn + && !x.streaming + && x.lease === connection.lease + && status === 'I' + && !closing + && (sent.length === 0 || (!x.lease && options.max !== 1)) + } + + function again(x, original) { + const retry = Exchange('query', x.query, x.lease, extended) + retry.statement = x.statement + retry.ends = x.ends + retry.retried = true + retry.original = original + retry.previous = x.entry + retry.trace = x.trace + retry.cost = x.cost + + if (sent.length) + return queue(retry) + + pending.unshift(retry) + release() + } + + function suspended(x) { + const cursor = x.origin || x + , { query } = x + + running.add(query) + + new Promise(r => r(query.cursorFn(x.result))).then(next => { + running.delete(query) + if (query.settled) + return unfence(cursor) + queue(step(cursor, next === CLOSE || !!query.aborted, query.aborted || null)) + }, error => { + running.delete(query) + if (query.settled) + return unfence(cursor) + queue(step(cursor, true, error)) + }) + } + + function step(cursor, end, failure) { + const x = Exchange('step', cursor.query, cursor.lease, stepped) + x.origin = cursor + x.statement = cursor.statement + x.entry = cursor.entry + x.columns = cursor.columns + x.portal = cursor.portal + x.rows = cursor.rows + x.end = end + x.failure = failure + return x + } + + function stepped(x) { + const cursor = x.origin + + if (connection.lease !== cursor.lease || cursor.epoch !== epoch) { + if (x.failure) + throw x.failure + if (!x.end) + throw outlived() + return skip + } + + x.own = x.failure + x.end ? p.close(out, 'P', x.portal) : p.execute(out, x.portal, x.rows) + sync(x) + } + + function outlived() { + return Errors.generic('UNSAFE_TRANSACTION', 'The cursor outlived its transaction') + } + + function finish(x) { + const { query } = x + + if (x.kind === 'simple') { + x.result.command !== null && x.results.push(x.result) + const results = x.results + return query.resolve(results.length > 1 ? results : results[0] || x.result) + } + + query.resolve(x.result) + } + + function NotificationResponse(x, start) { + const { pid, channel, payload } = p.notification(x, start) + events.onnotify && guard(events.onnotify, channel, payload, pid) + } + + function guard(fn, ...xs) { + try { + fn(...xs) + } catch (error) { + noop(error) + } + } + + function NoticeResponse(x, start, end) { + const notice = p.error(x, start, end) + listened(channels.notice) && channels.notice.publish({ + notice, + connection: connection.id, + host: connection.host, + port: connection.port, + database: options.database + }) + options.onnotice + ? guard(options.onnotice, notice) + : options.onnotice === false || console.log(notice) + } + + function ParameterStatus(x, start) { + const [k, v] = p.parameterStatus(x, start) + connection.parameters[k] = v + events.onparameter && guard(events.onparameter, k, v) + } + + function writeData(chunk, callback) { + p.copyData(out, chunk) + flush() ? callback() : (drained = callback) + } + + function writable(item) { + return { + autoDestroy: true, + write(chunk, encoding, callback) { + writeData(chunk, callback) + }, + destroy(error, callback) { + callback(error) + item.stream = null + if (!item.copied && !closed && !item.error) { + p.copyFail(out, (error || 'The COPY stream was destroyed') + '') + item.copied = true + item.open = false + schedule(true) + refresh() + } + }, + final(callback) { + p.copyDone(out) + item.copied = true + item.open = false + item.final = callback + schedule(true) + refresh() + } + } + } + + function CopyInResponse() { + const item = sent[0] + item.stream = new Stream.Writable(writable(item)) + item.query.resolve(item.stream) + } + + function readable(item) { + return () => { + item.wanted = true + + if (!frames.paused) + return + + frames.resume() + frames.paused || socket.resume() + } + } + + function CopyOutResponse() { + const item = sent[0] + item.stream = new Stream.Readable({ read: readable(item) }) + item.open = false + frames.own(true) + item.query.resolve(item.stream) + } + + function CopyBothResponse() { + const item = sent[0] + item.stream = new Stream.Duplex({ ...writable(item), read: readable(item) }) + frames.own(true) + item.query.resolve(item.stream) + } + + function CopyData(x, start, end) { + const item = sent[0] + + if (!item.stream) + return + + item.wanted = false + if (!item.stream.push(frames.owns(x) ? x.subarray(start + 5, end) : Buffer.from(x.subarray(start + 5, end))) && !item.wanted) { + frames.pause() + socket.pause() + } + } + + function CopyDone() { + frames.own(false) + const item = sent[0] + item.stream && item.stream.push(null) + item.stream = null + } +} + +function key(name) { + const x = JSON.stringify(String(name)) + return name === '__proto__' ? '[' + x + ']' : x +} + +export function own(row, name, value) { + Object.defineProperty(row, name, { value, writable: true, enumerable: true, configurable: true }) +} + +function Exchange(kind, query, lease, write) { + return { + kind, + query, + lease, + write, + trace: query && query.trace || null, + statement: null, + text: '', + entry: null, + fresh: null, + previous: null, + parses: [], + values: null, + params: null, + columns: null, + shaped: null, + reader: null, + result: new Result(), + results: null, + origin: null, + portal: '', + rows: 0, + end: false, + failure: null, + flushing: false, + streaming: false, + open: false, + alone: !!(query && query.alone), + describing: false, + learn: false, + verify: false, + synced: false, + bound: false, + suspended: false, + finished: false, + done: false, + ends: false, + epoch: 0, + retried: false, + original: null, + error: null, + own: null, + cancel: null, + stream: null, + copied: false, + wanted: false, + final: null, + resolve: null, + reject: null, + cost: undefined + } +} + +function Entry(name, owner, oids) { + return { name, owner, oids, columns: null, serializers: null, state: 'parsing', version: -1 } +} + +function Rows(columns) { + let state = states.get(columns) + if (state === undefined) { + state = { + columns, + seen: 0, + object: null, + array: null, + compilable: compiles && columns.length <= 512 && !columns.some(x => String(x.name) === '__proto__') + } + states.set(columns, state) + } + return state +} + +function read(state, array, text, from) { + const key = array ? 'array' : 'object' + + if (state[key] !== null) + return state[key] + + if (!state.compilable || ++state.seen < after) + return null + + try { + return state[key] = compile(state.columns, array, text, from) + } catch (_) { + compiles = state.compilable = false + return null + } +} + +function compile(columns, array, text, from) { + const locals = [] + , body = ['let l = 0'] + , at = 'x, i, i + l' + + columns.forEach((c, j) => { + c.decode + ? locals.push('d' + j + ' = c[' + j + '].decode') + : c.parser && locals.push('p' + j + ' = c[' + j + '].parser') + const value = c.decode ? 'd' + j + '(' + at + ')' : c.parser ? 'p' + j + '(text(' + at + '))' : 'text(' + at + ')' + body.push( + 'l = (x[i] << 24) | (x[i + 1] << 16) | (x[i + 2] << 8) | x[i + 3]', + 'i += 4', + 'let v' + j + ' = null', + 'l !== -1 && (v' + j + ' = ' + value + ', i += l)', + from ? 'v' + j + ' = from(v' + j + ', c[' + j + '])' : '' + ) + }) + + body.push(array + ? 'return [' + columns.map((c, j) => 'v' + j).join(',') + ']' + : 'return {' + columns.map((c, j) => key(c.name) + ':v' + j).join(',') + '}' + ) + + return new Function('c', 'text', 'from', + (locals.length ? 'const ' + locals.join(', ') + '\n' : '') + + 'return function row(x, i) {\n' + body.filter(Boolean).join('\n') + '\n}' + )(columns, text, from) +} diff --git a/node_modules/postgres/src/diagnostics.js b/node_modules/postgres/src/diagnostics.js new file mode 100644 index 0000000..d26bc89 --- /dev/null +++ b/node_modules/postgres/src/diagnostics.js @@ -0,0 +1,73 @@ +import dc from 'diagnostics_channel' + +export const channels = { + query: tracing('postgres:query'), + connect: tracing('postgres:connect'), + transaction: tracing('postgres:transaction'), + pool: plain('postgres:pool'), + notice: plain('postgres:notice') +} + +const done = Symbol('done') + +export const now = () => performance.now() + +export const userName = options => typeof options.user === 'function' ? null : options.user + +export function active(t) { + return !!t && (t.hasSubscribers !== undefined + ? t.hasSubscribers + : t.start.hasSubscribers || t.end.hasSubscribers || t.asyncStart.hasSubscribers + || t.asyncEnd.hasSubscribers || t.error.hasSubscribers) +} + +export function listened(channel) { + return !!channel && channel.hasSubscribers +} + +export function start(t, context, fn) { + return typeof t.start.runStores === 'function' + ? t.start.runStores(context, run) + : (t.start.publish(context), run()) + + function run() { + try { + return fn() + } finally { + t.end.publish(context) + } + } +} + +export function finish(t, context, error, result) { + if (context[done]) + return + + context[done] = true + + if (error) { + context.error = error + t.error.publish(context) + } else { + context.result = result + } + + t.asyncStart.publish(context) + t.asyncEnd.publish(context) +} + +function tracing(name) { + try { + return typeof dc.tracingChannel === 'function' ? dc.tracingChannel(name) : null + } catch (error) { + return null + } +} + +function plain(name) { + try { + return dc.channel(name) + } catch (error) { + return null + } +} diff --git a/node_modules/postgres/src/errors.js b/node_modules/postgres/src/errors.js new file mode 100644 index 0000000..cf4ed85 --- /dev/null +++ b/node_modules/postgres/src/errors.js @@ -0,0 +1,88 @@ +export class PostgresError extends Error { + constructor(x) { + super(typeof x === 'string' ? x : x && x.message) + this.name = this.constructor.name + x && typeof x === 'object' && Object.assign(this, x) + } + + toJSON() { + return { ...this, message: this.message } + } +} + +export const Errors = { + connection, + postgres, + generic, + notSupported +} + +function connection(code, options, host, port) { + const address = options.path || host + , error = Object.assign( + new Error('write ' + code + ' ' + (options.path || host + ':' + port)), + { code, errno: code, address }, + options.path ? {} : { port } + ) + + Error.captureStackTrace(error, connection) + return error +} + +function postgres(x) { + const error = new PostgresError(x) + Error.captureStackTrace(error, postgres) + return error +} + +function generic(code, message) { + const error = Object.assign(new Error(code + ': ' + message), { code }) + Error.captureStackTrace(error, generic) + return error +} + +function notSupported(x) { + const error = Object.assign(new Error(x + ' (B) is not supported'), { code: 'MESSAGE_NOT_SUPPORTED', name: x }) + Error.captureStackTrace(error, notSupported) + return error +} + +const places = locations() + +export const ours = line => places.some(here => line.includes(here) && !line.slice(line.indexOf(here) + here.length).split(':')[0].includes('/')) + +function locations() { + try { + const url = new URL('.', import.meta.url) + return url.protocol === 'file:' ? [url.href, decodeURIComponent(url.pathname)] : [url.href] + } catch (error) { + return [] + } +} + +export function withOrigin(error, origin) { + origin && Object.defineProperty(error, 'stack', { + value: [error.stack.split('\n')[0], ...origin.split('\n').slice(1).filter(x => !ours(x))].join('\n'), + writable: true, + configurable: true, + enumerable: false + }) + return error +} + +export function queryError(error, q, debug) { + if (!error || typeof error !== 'object') + error = new Error(error) + + if (!q || 'query' in error) + return error + + const built = q.built + Object.defineProperties(error, { + query: { value: built ? built.text : q.strings[0], enumerable: !!debug, configurable: true, writable: true }, + parameters: { value: built ? built.values : [], enumerable: !!debug, configurable: true, writable: true }, + args: { value: q.args, enumerable: !!debug, configurable: true, writable: true }, + types: { value: built ? built.oids : [], enumerable: !!debug, configurable: true, writable: true } + }) + return withOrigin(error, q.origin) +} diff --git a/node_modules/postgres/src/index.js b/node_modules/postgres/src/index.js new file mode 100644 index 0000000..1f46d32 --- /dev/null +++ b/node_modules/postgres/src/index.js @@ -0,0 +1,617 @@ +import os from 'os' +import fs from 'fs' + +import { + Types, + Parameter, + toPascal, + pascal, + toCamel, + camel, + toKebab, + kebab, + fromPascal, + fromCamel, + fromKebab +} from './types.js' + +import { Identifier, Builder } from './build.js' +import { Query, CLOSE } from './query.js' +import { Pool } from './pool.js' +import { Errors, PostgresError } from './errors.js' +import Subscribe from './subscribe.js' +import largeObject from './large.js' +import { channels, active, start, finish, userName } from './diagnostics.js' + +Object.assign(Postgres, { + PostgresError, + toPascal, + pascal, + toCamel, + camel, + toKebab, + kebab, + fromPascal, + fromCamel, + fromKebab, + BigInt: { + to: 20, + from: [20], + parse: x => BigInt(x), + serialize: x => x.toString() + } +}) + +export default Postgres +export { PostgresError } + +function Postgres(a, b) { + const options = parseOptions(a, b) + , types = options.shared_types || Types(options) + , pool = Pool(options, types) + , subscribe = options.no_subscribe || Subscribe(Postgres, { ...options, shared_types: types }) + , listener = Listen(options) + + if (types.named && options.fetch_types === false) + throw Errors.generic('TYPE_NOT_FOUND', 'Custom types given by name need fetch_types to look them up') + + options.resolve = types.resolve + options.parsers = view(types.parsers, types.parser) + options.serializers = view(types.serializers, types.serializer) + + const sql = Sql(handler) + + Object.defineProperties(sql, { + parameters: { get: () => options.parameters, enumerable: true }, + stats: { get: () => pool.stats, enumerable: true } + }) + + Object.assign(sql, { + largeObject: largeObject.bind(null, sql), + subscribe, + CLOSE, + END: CLOSE, + PostgresError, + options, + reserve, + listen: listener.listen, + begin, + close, + end + }) + + Symbol.asyncDispose && (sql[Symbol.asyncDispose] = () => end()) + + return sql + + function handler(q) { + pool.query(q) + } + + function Sql(handler) { + handler.debug = options.debug + handler.options = options + handler.cancel = handler.cancel || pool.cancel + + const typed = (value, type) => new Parameter(value, type) + + Object.entries(options.types).forEach(([name, type]) => typed[name] = x => new Parameter(x, type.to)) + + Object.assign(sql, { + types: typed, + typed, + unsafe, + notify, + array, + json, + file + }) + + return sql + + function sql(strings, ...args) { + return strings && Array.isArray(strings.raw) + ? new Query(strings, args, handler) + : typeof strings === 'string' && !args.length + ? new Identifier(options.transform.column.to ? options.transform.column.to(strings) : strings) + : new Builder(strings, args) + } + + function unsafe(string, args = [], options = {}) { + arguments.length === 2 && !Array.isArray(args) && (options = args, args = []) + return new Query([string], args, handler, { + prepare: false, + ...options, + simple: 'simple' in options ? options.simple : args.length === 0 + }) + } + + async function notify(channel, payload) { + return await sql`select pg_notify(${ channel }, ${ '' + payload })` + } + + function file(path, args = [], options = {}) { + arguments.length === 2 && !Array.isArray(args) && (options = args, args = []) + const fileHandler = query => fs.readFile(path, 'utf8', (err, string) => { + if (err) + return query.reject(err) + query.strings = [string] + handler(query) + }) + Object.assign(fileHandler, handler) + return new Query([], args, fileHandler, { + ...options, + simple: 'simple' in options ? options.simple : args.length === 0 + }) + } + } + + function json(x) { + return new Parameter(x, 3802) + } + + function array() { + throw Errors.generic('ARRAY_REMOVED', 'sql.array() is removed in v4, pass the array as it is') + } + + async function reserve() { + const lease = await pool.lease('reserve') + , reserved = Sql(Object.assign(q => lease.send(q), { cancel: pool.cancel })) + + reserved.release = () => lease.release() + Symbol.dispose && (reserved[Symbol.dispose] = reserved.release) + Symbol.asyncDispose && (reserved[Symbol.asyncDispose] = async() => reserved.release()) + return reserved + } + + function begin(mode, fn) { + !fn && (fn = mode, mode = '') + if (!active(channels.transaction)) + return transaction(mode, fn, null) + + const context = { + mode, + database: options.database, + user: userName(options), + connection: null, + host: null, + port: null, + outcome: null + } + let promise + start(channels.transaction, context, () => promise = transaction(mode, fn, context)) + + return promise.then( + result => (finish(channels.transaction, context, null, result), result), + error => { + finish(channels.transaction, context, error) + throw error + } + ) + } + + async function transaction(mode, fn, context) { + const lease = await pool.lease('transaction') + + let savepoints = 0 + , prepare = null + + context && Object.assign(context, { + connection: lease.connection.id, + host: lease.connection.host, + port: lease.connection.port + }) + + try { + await control(lease, 'begin ' + mode.replace(/[^a-z ]/ig, '')) + const done = scope(fn) + done.catch(() => {}) + return await Promise.race([done, lease.closed]) + } finally { + lease.release() + } + + async function scope(fn, name, inside, above = () => false) { + let uncaught + , result + , rolled = null + , after = null + + if (above()) + throw rolledBack() + + const stopped = () => !!rolled || above() + , scoped = Sql(Object.assign(q => { + if (stopped()) + return q.reject(after || (after = rolledBack())) + q.catch(e => uncaught || (uncaught = e)) + lease.send(q) + }, { cancel: pool.cancel })) + + scoped.savepoint = savepoint + scoped.begin = nested + scoped.rollback = () => rolled || (rolled = control(lease, name ? 'rollback to ' + identifier(name) : 'rollback').then(() => {})) + scoped.prepare = x => { + if (inside) + throw Errors.generic('NESTED_TRANSACTION_MODE', 'A nested transaction can not be prepared, only the outermost one') + prepare = x.replace(/[^a-z0-9$\-_. ]/gi, '') + } + + name && await control(lease, 'savepoint ' + identifier(name)) + try { + result = await new Promise((resolve, reject) => { + const x = fn(scoped) + Promise.resolve(Array.isArray(x) ? Promise.all(x) : x).then(resolve, reject) + }) + if (uncaught && !stopped()) + throw uncaught + } catch (error) { + context && !name && (context.outcome = 'rollback') + stopped() + ? rolled && await rolled.catch(() => {}) + : lease.connection.closed || await control(lease, name ? 'rollback to ' + identifier(name) : 'rollback') + throw error instanceof PostgresError && error.code === '25P02' && uncaught || error + } + + if (stopped()) { + rolled && await rolled + context && !name && (context.outcome = 'rollback') + + if (after) + throw after + + return result + } + + if (!name) { + const done = await control(lease, prepare ? 'prepare transaction \'' + prepare.replace(/'/g, '\'\'') + '\'' : 'commit') + context && (context.outcome = prepare ? 'prepare' : done.command === 'COMMIT' ? 'commit' : 'rollback') + + if (!prepare && done.command !== 'COMMIT') + throw Errors.generic('TRANSACTION_ROLLED_BACK', 'The server rolled back the transaction instead of committing it') + } + + return result + + function savepoint(name, fn) { + if (name && Array.isArray(name.raw)) + return savepoint(sql => sql.apply(sql, arguments)) + + arguments.length === 1 && (fn = name, name = null) + return scope(fn, 's' + savepoints++ + (name ? '_' + name : ''), false, stopped) + } + + async function nested(inner, fn) { + !fn && (fn = inner, inner = '') + + if (normal(inner) && normal(inner) !== normal(mode)) + throw Errors.generic('NESTED_TRANSACTION_MODE', 'A nested transaction runs in a savepoint, which can not change the transaction mode') + + return scope(fn, 's' + savepoints++, true, stopped) + } + } + } + + function rolledBack() { + return Errors.generic('TRANSACTION_ROLLED_BACK', 'The query was not sent, the transaction was rolled back with sql.rollback()') + } + + function normal(x) { + return (x || '').toLowerCase().replace(/[^a-z ]/g, '').replace(/\s+/g, ' ').trim() + } + + function identifier(x) { + return '"' + x.replace(/"/g, '""') + '"' + } + + function control(lease, text) { + const q = new Query([text], [], Object.assign(q => lease.send(q), { options, cancel: pool.cancel }), { simple: true }) + return q.execute() + } + + async function end(options) { + await Promise.all([ + listener.end(), + subscribe.sql ? subscribe.sql.end({ timeout: 0 }) : null + ]) + return pool.end(options) + } + + function close() { + return pool.close() + } +} + +function Listen(options) { + const channels = new Map() + let sql = null + , closing = null + + return { + listen, + end: () => closing || (sql ? (closing = sql.end({ timeout: 0 })) : Promise.resolve()) + } + + function connection() { + return sql || (sql = Postgres({ + ...options, + max: 1, + idle_timeout: null, + max_lifetime: null, + fetch_types: false, + no_subscribe: true, + onclose() { + if (closing) + return + + channels.forEach((channel, name) => { + channel.result = start(name) + channel.result.then(result => { + Object.assign(channel.state, result.state) + channel.listeners.forEach(l => l.onlisten && l.onlisten()) + }, () => {}) + }) + }, + onnotify(channel, payload) { + channels.has(channel) && [...channels.get(channel).listeners].forEach(l => l.fn(payload)) + } + })) + } + + function start(name) { + const x = connection() + return x`listen ${ x.unsafe('"' + name.replace(/"/g, '""') + '"') }` + } + + async function listen(name, fn, onlisten) { + const listener = { fn, onlisten } + if (!channels.has(name)) + channels.set(name, { listeners: new Set(), result: start(name), state: {} }) + + const channel = channels.get(name) + channel.listeners.add(listener) + let result + try { + result = await channel.result + } catch (error) { + channel.listeners.delete(listener) + channel.listeners.size || channels.delete(name) + throw error + } + Object.assign(channel.state, result.state) + listener.onlisten && listener.onlisten() + + return { state: channel.state, unlisten } + + async function unlisten() { + if (!channel.listeners.delete(listener) || channel.listeners.size) + return + + channels.get(name) === channel && channels.delete(name) + const x = sql + + if (closing || !x) + return + + await x`unlisten ${ x.unsafe('"' + name.replace(/"/g, '""') + '"') }`.catch(e => { + if (!/^CONNECTION_/.test(e.code)) + throw e + }) + if (channels.size === 0 && sql === x) { + sql = null + await x.end() + } + } + } +} + +function parseOptions(a, b) { + if (a && a.shared) + return a + + const env = process.env + , o = (!a || typeof a === 'string' ? b : a) || {} + , url = parseUrl(a) + , query = [...url.url.searchParams].reduce((a, [b, c]) => (a[b] = c, a), {}) + , targets = hosts(o, query, url, env) + , port = o.port || query.port || env.PGPORT || 5432 + , user = o.user || o.username || url.url.username || env.PGUSERNAME || env.PGUSER || osUsername() + + o.no_prepare && (o.prepare = false) + query.sslmode && (query.ssl = query.sslmode, delete query.sslmode) + 'timeout' in o && (console.log('The timeout option is deprecated, use idle_timeout instead'), o.idle_timeout = o.timeout) + query.sslrootcert === 'system' && (query.ssl = 'verify-full') + + const ints = ['idle_timeout', 'connect_timeout', 'max_lifetime', 'max_pipeline', 'backoff', 'keep_alive', 'min', 'queue_timeout'] + const defaults = { + max : globalThis.Cloudflare ? 3 : 10, + min : 0, + ssl : false, + sslnegotiation : null, + channel_binding : 'prefer', + idle_timeout : null, + connect_timeout : 30, + queue_timeout : 0, + max_lifetime : max_lifetime, + max_pipeline : 100, + scheduler : true, + backoff : backoff, + keep_alive : 60, + prepare : true, + debug : false, + fetch_types : true, + infer : false, + publications : 'alltables', + slot : null, + target_session_attrs: null + } + + const options = { + host : targets.map(x => x[0]), + port : Array.isArray(port) ? port : targets.map(x => o.port || query.port ? +port : x[1] || +port), + path : o.path || targets[0][0].indexOf('/') > -1 && targets[0][0] + '/.s.PGSQL.' + (targets[0][1] || port), + database : o.database || o.db || (url.url.pathname || '').slice(1) || env.PGDATABASE || (typeof user === 'function' ? null : user), + user : user, + pass : o.pass || o.password || url.url.password || env.PGPASSWORD || '', + ...Object.entries(defaults).reduce( + (acc, [k, d]) => { + const value = k in o && o[k] !== undefined ? o[k] : k in query + ? (query[k] === 'disable' || query[k] === 'false' ? false : query[k]) + : env['PG' + k.toUpperCase()] || d + acc[k] = typeof value === 'string' && ints.includes(k) + ? +value + : value + return acc + }, + {} + ), + connection : { + application_name: env.PGAPPNAME || 'postgres.js', + ...o.connection, + ...Object.entries(query).reduce((acc, [k, v]) => (k in defaults || k === 'host' || k === 'port' || (acc[k] = v), acc), {}) + }, + types : o.types || {}, + target_session_attrs: tsa(o, url.url, env), + channel_binding : binding(o, url.url, env), + onnotice : o.onnotice, + onnotify : o.onnotify, + onclose : o.onclose, + onparameter : o.onparameter, + socket : o.socket, + onread : o.onread !== false, + open : o.open, + no_subscribe : o.no_subscribe, + unref_sockets : !!o.unref_sockets, + passfile : passfile(env), + shared_types : o.shared_types, + transform : parseTransform(o.transform || { undefined: undefined }), + parameters : {}, + shared : { retries: 0 }, + timers : o.timers || { + setTimeout, + clearTimeout, + setImmediate, + clearImmediate, + now: () => performance.now() + } + } + + options.infer = options.infer === true || options.infer === 'true' + options.max === 1 && (options.scheduler = false) + return options +} + +function tsa(o, url, env) { + const x = o.target_session_attrs || url.searchParams.get('target_session_attrs') || env.PGTARGETSESSIONATTRS + if (!x || ['read-write', 'read-only', 'primary', 'standby', 'prefer-standby'].includes(x)) + return x + + throw new Error('target_session_attrs ' + x + ' is not supported') +} + +function binding(o, url, env) { + const x = o.channel_binding || url.searchParams.get('channel_binding') || env.PGCHANNELBINDING || 'prefer' + if (['disable', 'prefer', 'require'].includes(x)) + return x + + throw new Error('channel_binding ' + x + ' is not supported') +} + +function backoff(retries) { + return (0.5 + Math.random() / 2) * Math.min(3 ** retries / 100, 20) +} + +function max_lifetime() { + return 60 * (30 + Math.random() * 30) +} + +function parseTransform(x) { + return { + undefined: x.undefined, + column: { + from: typeof x.column === 'function' ? x.column : x.column && x.column.from, + to: x.column && x.column.to + }, + value: { + from: typeof x.value === 'function' ? x.value : x.value && x.value.from, + to: x.value && x.value.to + }, + row: { + from: typeof x.row === 'function' ? x.row : x.row && x.row.from, + to: x.row && x.row.to + } + } +} + +function parseUrl(url) { + if (!url || typeof url !== 'string') + return { url: { searchParams: new Map() }, targets: [] } + + const rest = url.slice(url.indexOf('://') + 3) + , end = rest.search(/[/?]/) + , authority = end === -1 ? rest : rest.slice(0, end) + , at = authority.lastIndexOf('@') + , userinfo = at === -1 ? '' : authority.slice(0, at) + , colon = userinfo.indexOf(':') + , tail = new URL('postgres://x' + (end === -1 ? '' : rest.slice(end))) + + return { + url: { + username: decode(colon === -1 ? userinfo : userinfo.slice(0, colon)), + password: colon === -1 ? '' : decode(userinfo.slice(colon + 1)), + pathname: decode(tail.pathname), + searchParams: tail.searchParams + }, + targets: authority.slice(at + 1) ? split(authority.slice(at + 1), decode) : [] + } +} + +function decode(x) { + try { + return decodeURIComponent(x) + } catch (_) { + return x + } +} + +function hosts(o, query, url, env) { + const given = o.hostname || o.host || query.host + if (given) + return Array.isArray(given) ? given.map(x => [x, null]) : split(given) + + if (url.targets.some(([x]) => x)) + return url.targets + + return split(env.PGHOST || 'localhost').map(([x, p], i) => [x, p || (url.targets[i] && url.targets[i][1]) || null]) +} + +function split(x, decoded = x => x) { + return x.split(',').filter(Boolean).map(x => { + const m = x.match(/^\[([^\]]*)\](?::(\d*))?$/) || x.match(/^([^:]*)(?::(\d*))?$/) || [x, x] + return [decoded(m[1]), m[2] ? +m[2] : null] + }) +} + +function passfile(env) { + try { + return env.PGPASSFILE || (process.platform === 'win32' + ? (env.APPDATA || '') + '\\postgresql\\pgpass.conf' + : os.homedir() + '/.pgpass') + } catch (_) { + return null + } +} + +function osUsername() { + try { + return os.userInfo().username + } catch (_) { + return process.env.USERNAME || process.env.USER || process.env.LOGNAME + } +} + +function view(known, get) { + return new Proxy(known, { + get: (x, oid) => typeof oid === 'symbol' ? x[oid] : get(+oid) + }) +} diff --git a/node_modules/postgres/src/large.js b/node_modules/postgres/src/large.js new file mode 100644 index 0000000..7666538 --- /dev/null +++ b/node_modules/postgres/src/large.js @@ -0,0 +1,72 @@ +import Stream from 'stream' + +export default function largeObject(sql, oid, mode = 0x00020000 | 0x00040000) { + return new Promise(async(resolve, reject) => { + await sql.begin(async sql => { + let finish + !oid && ([{ oid }] = await sql`select lo_creat(-1) as oid`) + const [{ fd }] = await sql`select lo_open(${ oid }, ${ mode }) as fd` + + const lo = { + writable, + readable, + close : () => sql`select lo_close(${ fd })`.then(finish), + tell : () => sql`select lo_tell64(${ fd })`, + read : (x) => sql`select loread(${ fd }, ${ x }) as data`, + write : (x) => sql`select lowrite(${ fd }, ${ x })`, + truncate : (x) => sql`select lo_truncate64(${ fd }, ${ x })`, + seek : (x, whence = 0) => sql`select lo_lseek64(${ fd }, ${ x }, ${ whence })`, + size : () => sql` + select + lo_lseek64(${ fd }, location, 0) as position, + seek.size + from ( + select + lo_lseek64($1, 0, 2) as size, + tell.location + from (select lo_tell64($1) as location) tell + ) seek + ` + } + + resolve(lo) + + return new Promise(async r => finish = r) + + async function readable({ + highWaterMark = 2048 * 8, + start = 0, + end = Infinity + } = {}) { + let max = end - start + start && await lo.seek(start) + + return new Stream.Readable({ + highWaterMark, + async read(size) { + const l = Math.min(size, max) + max -= l + const [{ data }] = await lo.read(l) + data.length && this.push(data) + if (data.length < l || max === 0) + this.push(null) + } + }) + } + + async function writable({ + highWaterMark = 2048 * 8, + start = 0 + } = {}) { + start && await lo.seek(start) + + return new Stream.Writable({ + highWaterMark, + write(chunk, encoding, callback) { + lo.write(chunk).then(() => callback(), callback) + } + }) + } + }).catch(reject) + }) +} diff --git a/node_modules/postgres/src/pool.js b/node_modules/postgres/src/pool.js new file mode 100644 index 0000000..48f679c --- /dev/null +++ b/node_modules/postgres/src/pool.js @@ -0,0 +1,814 @@ +import { open as startup } from './startup.js' +import { Connection, slow, notable } from './connection.js' +import { Query } from './query.js' +import { Errors, PostgresError, queryError } from './errors.js' +import { channels, listened } from './diagnostics.js' + +const begins = /\bbegin\b/i + , starts = /\bstart\b/gi + , transaction = /^transaction\b/i + +export function Pool(options, types) { + const { setTimeout, clearTimeout, now } = options.timers + , statements = Statements(options.scheduler) + , connections = new Set() + , waiting = Queue() + , events = { + parser: types.parser, + decoder: types.decoder, + serializer: types.serializer, + onready, + onclose, + onnotify: options.onnotify, + onparameter, + ontimed + } + , work = { fast: 0, slow: 0, at: 0 } + + const signal = { aborted: false, sockets: new Set() } + , replacing = [] + + let opening = 0 + , ending = null + , used = false + , endTimer = null + , retries = 0 + , failingSince = null + , nextAttempt = 0 + , retryTimer = null + , typesLoaded = options.fetch_types === false + , typesError = null + , typesFailed = 0 + , failure = null + , typesLoading = false + + const pool = { + query, + lease, + cancel, + end, + close, + get stats() { + return { + connections: connections.size, + opening, + idle: [...connections].filter(x => x.inflight === 0 && !x.lease).length, + leased: [...connections].filter(x => x.lease).length, + waiting: waiting.length + } + } + } + + return pool + + function query(q, lease) { + if (ending && !lease) + return q.reject(queryError(Errors.connection('CONNECTION_ENDED', options, options.host[0], options.port[0]), q, options.debug)) + + let built + try { + built = q.build() + } catch (error) { + return unbuilt(q, error, lease) + } + + const free = !lease && options.max !== 1 + + if (q.options.simple && !built.values.length) { + const known = (free || options.scheduler) && statements.known(built.text) + q.alone = free && alone(known) + options.scheduler && (q.cost = known) + return place({ q, simple: built.text, exclusive: !!q.streaming || q.alone }, lease) + } + + if (q.onlyDescribe) + return describeOnly(q, built, lease) + + const statement = statements.get(built, options.prepare && q.options.prepare !== false) + q.alone = free && alone(statement.live ? statement : statements.known(built.text)) + q.wire = { statement, built } + options.scheduler && (q.cost = statement.cost) + place({ q, statement, exclusive: !!q.cursorFn || !!q.streaming || q.alone }, lease) + } + + function describeOnly(q, built, lease) { + const statement = { name: '', text: built.text, oids: built.oids, columns: null } + , run = c => (q.connection = c, c.describe(statement, built.oids).then( + ({ params, columns }) => q.resolve({ string: built.text, types: params, name: '', columns }), + error => q.reject(queryError(error, q, options.debug)) + ), q.onwrite && q.onwrite()) + lease ? run(lease.connection) : place({ run, q, reject: error => q.reject(queryError(error, q, options.debug)) }) + } + + function unbuilt(q, error, lease) { + error = queryError(error, q, options.debug) + if (!lease || lease.released || lease.connection.closed) + return q.reject(error) + + q.connection = lease.connection + lease.connection.local(q, error) + q.onwrite && q.onwrite() + } + + function place(job, lease) { + used = true + const missing = !lease && retype() + + if (missing) + return reject(job, missing) + + if (job.q && job.q.cancelled) + return job.q.reject(queryError(Errors.generic('57014', 'canceling statement due to user request'), job.q, options.debug)) + + if (lease) { + return lease.connection.closed ? job.q.reject(queryError(lease.connection.closed, job.q, options.debug)) + : lease.released ? job.q.reject(queryError(ended(lease), job.q, options.debug)) + : run(lease.connection, job) + } + + if (signal.aborted) + return reject(job, Errors.connection('CONNECTION_DESTROYED', options, options.host[0], options.port[0])) + + if (failingFast()) + return reject(job, copy(failure.error)) + + const c = waiting.length === 0 && pick(job) + if (c) + return run(c, job) + + waiting.push(wait(job)) + drain() + } + + function wait(job) { + if (!options.queue_timeout) + return job + + job.timer = setTimeout(() => { + job.timer = null + waiting.remove(x => x === job) && reject(job, Errors.generic( + 'QUEUE_TIMEOUT', 'Waited more than ' + options.queue_timeout + ' seconds for a connection' + )) + }, options.queue_timeout * 1000) + typeof job.timer.unref === 'function' && job.timer.unref() + return job + } + + function started(job) { + job.timer && (clearTimeout(job.timer), job.timer = null) + } + + function run(c, job) { + started(job) + hold(c) + + if (job.run) + return job.run(c) + + job.q.connection = c + job.simple !== undefined + ? c.simple(job.q, job.simple) + : c.send(job.q) + job.q.onwrite && job.q.onwrite() + } + + function drain() { + while (waiting.length) { + const job = waiting.peek() + , c = pick(job) + + if (!c && !copying(job)) + break + + waiting.shift() + !c ? reject(job, Errors.generic('COPY_IN_PROGRESS', 'You cannot execute queries during copy')) + : job.lease ? grant(c, job) + : run(c, job) + } + waiting.length && listened(channels.pool) && event('wait', null, { waiting: waiting.length }) + grow() + } + + function plain(job) { + return !!job.q && !job.lease && !job.exclusive && !job.run + } + + function copying(job) { + if (!job.q || connections.size + opening < options.max || connections.size === 0) + return false + + for (const c of connections) { + if (!c.copying) + return false + } + return true + } + + function usable(c) { + return !c.closed && !c.closing && !c.lease && !c.releasing && !c.retiring && !c.exclusive && !c.loading + } + + function pick(job) { + const statement = job.statement + , any = !statement || !statement.name + + let best = null + + for (const c of connections) { + const free = usable(c) + if (free && c.inflight === 0) { + if (any || c.prepared.has(statement.name)) + return c + best = best && best.inflight === 0 ? best : c + } else if (free && !job.lease && !job.exclusive + && c.inflight < options.max_pipeline && (!best || c.inflight < best.inflight)) { + best = c + } + } + + if (best && best.inflight === 0) + return best + + if (connections.size + opening < options.max && !failingSince) + return null + + best && options.scheduler && job.q && needed(job) && (best = scheduled(job) || best) + return best && opening && best.inflight >= Math.ceil(waiting.length / (opening + 1)) + ? null + : best + } + + function needed(job) { + if (!job.q.cost || job.q.cost.est === undefined || job.q.cost.est >= notable) + return true + + for (const c of connections) { + if (c.notable) + return true + } + + return false + } + + function scheduled(job) { + const t = now() + , e = job.q.cost ? job.q.cost.est : undefined + + if (e === undefined || e < slow) + return soonest(t, Infinity, false) + + let heavy = 0 + for (const c of connections) + c.inflight && c.heavy() && heavy++ + + decay(t) + const reserve = Math.max(1, Math.min(Math.ceil(work.fast / 2000 * 1.5) + 1, connections.size - Math.ceil(work.slow / 2000))) + return heavy < connections.size - reserve + ? soonest(t, Infinity, false) + : soonest(t, 2 * e, true) || soonest(t, Infinity, false) + } + + function soonest(t, most, heavy) { + let best = null + , value = Infinity + , ties = 0 + + for (const c of connections) { + const v = usable(c) && c.inflight < options.max_pipeline && (!heavy || c.heavy()) ? c.backlog(t) : Infinity + if (v <= most && v < value) + (best = c, value = v, ties = 1) + else if (v <= most && v === value && v !== Infinity && Math.random() * ++ties < 1) + best = c + } + + return best + } + + function ontimed(sample, t) { + decay(t) + sample < slow ? work.fast += sample : work.slow += sample + } + + function decay(t) { + const d = Math.exp((work.at - t) / 2000) + work.fast *= d + work.slow *= d + work.at = t + } + + function grow() { + if (ending && waiting.length === 0) + return + + if (failingSince !== null) { + if (opening || !waiting.length || retryTimer) + return + const wait = nextAttempt - now() + return wait > 0 + ? (retryTimer = setTimeout(() => (retryTimer = null, grow()), wait)) + : connect() + } + + let loading = 0 + for (const c of connections) + c.loading && loading++ + + const wanted = Math.max( + Math.min(waiting.length - opening - loading, options.max - connections.size - opening), + used && !ending ? Math.min(options.min, options.max) - connections.size - opening : 0 + ) + + for (let i = 0; i < wanted; i++) + connect() + } + + function connect() { + opening++ + retryTimer && (clearTimeout(retryTimer), retryTimer = null) + ;(options.open || startup)(options, signal, replacing.length ? replacing.shift() : 0).then(opened, failed) + } + + function copy(error) { + if (!error || typeof error !== 'object') + return error + + const x = Object.create(Object.getPrototypeOf(error), Object.getOwnPropertyDescriptors(error)) + Object.defineProperty(x, 'stack', { value: error.stack, writable: true, configurable: true }) + ;['query', 'parameters', 'args', 'types'].forEach(k => delete x[k]) + return x + } + + function failingFast() { + return !!failure && retries > 1 && opening === 0 && now() < nextAttempt && stuck() + } + + function stuck() { + for (const c of connections) { + if (!c.lease) + return false + } + return true + } + + function opened(ready) { + opening-- + retries = 0 + failingSince = null + failure = null + + if (signal.aborted || (ending && waiting.length === 0)) { + ready.socket.destroy() + return finishing() + } + + Object.entries(ready.parameters).forEach(([k, v]) => onparameter(k, v)) + const c = Connection(ready, options, events) + c.index = ready.index || 0 + connections.add(c) + lifetime(c) + listened(channels.pool) && event('open', c) + typesLoaded || typesLoading ? (c.loading = !typesLoaded) : loadTypes(c) + drain() + } + + function retype() { + if (!typesError) + return null + + if (now() - typesFailed < 1000) + return copy(typesError) + + typesError = null + connections.forEach(x => x.loading = true) + ;[...connections].some(x => !x.closed && (loadTypes(x), true)) + return null + } + + function loadTypes(c) { + hold(c) + typesLoading = true + c.loading = true + types.load(text => new Promise((resolve, reject) => { + const q = new Query([text], [], Object.assign(() => {}, { options }), { simple: true }) + q.executed = true + q.then(resolve, reject) + c.simple(q, text) + })).then(() => typesLoaded = true, error => error instanceof PostgresError + ? typesLoaded = true + : error && error.code === 'TYPE_NOT_FOUND' && (typesError = error, typesFailed = now()) + ).then(() => { + typesLoading = false + connections.forEach(x => x.loading = !typesLoaded && !typesError) + typesError + ? waiting.take().forEach(job => reject(job, copy(typesError))) + : typesLoaded || [...connections].some(x => !x.closed && (loadTypes(x), true)) + drain() + }) + } + + function failed(error) { + opening-- + if (signal.aborted) + return finishing() + + failingSince === null && (failingSince = now()) + retries++ + nextAttempt = now() + 1000 * (typeof options.backoff === 'function' ? options.backoff(retries) : options.backoff) + + const transient = !!error && (error.code === 'CONNECTION_CLOSED' || error.code === '53300') + , expired = now() - failingSince >= options.connect_timeout * 1000 + + failure = !transient || expired ? { error } : null + stuck() && opening === 0 && (failure || ending) && waiting.take().forEach((job, i) => reject(job, i ? copy(error) : error)) + ending ? finishing() : grow() + } + + function reject(job, error) { + started(job) + job.lease ? job.reject(error) : job.q ? job.q.reject(queryError(error, job.q, options.debug)) : job.reject(error) + } + + function lifetime(c) { + const life = typeof options.max_lifetime === 'function' ? options.max_lifetime() : options.max_lifetime + life && (c.lifeTimer = unref(setTimeout(() => { + c.retiring = true + c.inflight === 0 && !c.lease && c.close() + }, life * 1000))) + idle(c) + } + + function event(name, c, extra) { + channels.pool.publish({ + event: name, + connection: c ? c.id : null, + host: c ? c.host : null, + port: c ? c.port : null, + database: options.database, + stats: pool.stats, + ...extra + }) + } + + function idle(c) { + listened(channels.pool) && event('idle', c) + if (c.inflight || c.lease) + return + + options.unref_sockets && !c.loading && waiting.length === 0 && c.unref() + if (!options.idle_timeout) + return + + c.idleSince = now() + c.idleTimer || (c.idleTimer = unref(setTimeout(() => idled(c), options.idle_timeout * 1000))) + } + + function hold(c) { + options.unref_sockets && c.ref() + } + + function unref(timer) { + options.unref_sockets && timer && typeof timer.unref === 'function' && timer.unref() + return timer + } + + function idled(c) { + c.idleTimer = null + if (c.inflight || c.lease || c.closed) + return + + if (connections.size <= options.min) + return + + const left = options.idle_timeout * 1000 - (now() - c.idleSince) + left >= 1 + ? c.idleTimer = unref(setTimeout(() => idled(c), left)) + : c.close() + } + + function onready(c) { + if (c.releasing) { + if (c.inflight) + return + + c.releasing = false + if (c.status !== 'I') + return c.close() + } + if (c.inflight === 0 && !c.lease && (c.retiring || (ending && waiting.length === 0))) + return c.close() + + idle(c) + while (waiting.length > connections.size && usable(c) && c.inflight < options.max_pipeline && plain(waiting.peek())) + run(c, waiting.shift()) + + waiting.length && !c.lease && c.inflight < options.max_pipeline && drain() + ending && waiting.length === 0 && finishing() + } + + function onclose(c, error) { + connections.delete(c) + ending || replacing.push((c.index + 1) % (options.path ? 1 : options.host.length)) + replacing.length > options.max && replacing.shift() + c.retired && c.retired.forEach(r => r()) + c.idleTimer && clearTimeout(c.idleTimer) + c.lifeTimer && clearTimeout(c.lifeTimer) + c.lease && c.lease.onclose && c.lease.onclose(error.code === 'CONNECTION_DESTROYED' ? Errors.connection('CONNECTION_CLOSED', options, c.host, c.port) : error) + options.onclose && options.onclose(c.id) + listened(channels.pool) && event('close', c, { error }) + connections.size === 0 && opening === 0 && statements.clear() + drain() + ending && finishing() + } + + function onparameter(k, v) { + options.parameters[k] !== v && (options.parameters[k] = v, options.onparameter && options.onparameter(k, v)) + } + + async function lease(kind) { + used = true + await 1 + if (ending) + throw Errors.connection('CONNECTION_ENDED', options, options.host[0], options.port[0]) + + if (failingFast()) + throw copy(failure.error) + + const missing = retype() + if (missing) + throw missing + + return new Promise((resolve, reject) => { + waiting.push(wait({ lease: true, kind, resolve, reject, queued: listened(channels.pool) ? now() : 0 })) + drain() + }) + } + + function grant(c, job) { + started(job) + hold(c) + c.idleTimer && (clearTimeout(c.idleTimer), c.idleTimer = null) + let chain = Promise.resolve() + , released = false + , lost + + const closed = new Promise((_, reject) => lost = reject) + closed.catch(() => {}) + + const x = { + kind: job.kind, + connection: c, + closed, + get released() { return released }, + send(q) { + if (c.closed) + return q.reject(queryError(c.closed, q, options.debug)) + + if (released) + return q.reject(queryError(ended(x), q, options.debug)) + + chain = chain.then(() => new Promise(resolve => { + q.onwrite = resolve + q.then(resolve, resolve) + query(q, x) + })) + }, + release() { + if (released) + return + released = true + c.lease === x && (c.lease = null) + listened(channels.pool) && event('release', c, { kind: job.kind }) + if (c.closed) + return + + if (c.inflight) + return (c.releasing = true) + + c.status === 'I' ? onready(c) : c.close() + }, + onclose(error) { + lost(error) + } + } + + c.lease = x + listened(channels.pool) && event('lease', c, { kind: job.kind, waited: job.queued ? now() - job.queued : 0 }) + job.resolve(x) + } + + function ended(lease) { + return Errors.generic('UNSAFE_TRANSACTION', 'The ' + lease.kind + ' has ended') + } + + function cancel(q) { + if (waiting.remove(x => x.q === q && (started(x), true))) { + q.reject(queryError(Errors.generic('57014', 'canceling statement due to user request'), q, options.debug)) + return Promise.resolve() + } + + if (q.connection) + return q.connection.cancel(q) + + q.cancelled = true + return Promise.resolve() + } + + function end({ timeout = null } = {}) { + if (ending) + return ending + + ending = new Promise(resolve => { + pool.ended = resolve + timeout !== null && (endTimer = setTimeout(destroy, timeout * 1000)) + retryTimer && (clearTimeout(retryTimer), retryTimer = null) + Promise.resolve().then(finishing) + }) + + return ending + } + + function finishing() { + if (!pool.ended) + return + + if (waiting.length === 0) + connections.forEach(c => c.inflight === 0 && !c.lease && c.close()) + + if (connections.size === 0 && opening === 0 && waiting.length) { + const error = Errors.connection('CONNECTION_ENDED', options, options.host[0], options.port[0]) + waiting.take().forEach(job => reject(job, error)) + } + + if (connections.size === 0 && (opening === 0 || signal.aborted) && waiting.length === 0) { + endTimer && clearTimeout(endTimer) + retryTimer && clearTimeout(retryTimer) + const resolve = pool.ended + pool.ended = null + resolve() + } + } + + function destroy() { + endTimer = null + signal.aborted = true + signal.sockets.forEach(x => x.destroy()) + const error = Errors.connection('CONNECTION_DESTROYED', options, options.host[0], options.port[0]) + waiting.take().forEach(job => reject(job, error)) + connections.forEach(c => c.destroy()) + connections.size === 0 && finishing() + } + + function close() { + used = false + return Promise.all([...connections].map(c => c.lease + ? new Promise(r => (c.retiring = true, (c.retired || (c.retired = [])).push(r))) + : c.close() + )) + } +} + +export function Queue() { + let xs = [] + , head = 0 + + return { + get length() { return xs.length - head }, + push: x => xs.push(x), + peek: () => xs[head], + shift() { + const x = xs[head] + xs[head++] = undefined + head === xs.length ? (xs = [], head = 0) : head > 1024 && head * 2 > xs.length && (xs = xs.slice(head), head = 0) + return x + }, + take() { + const all = xs.slice(head) + xs = [] + head = 0 + return all + }, + remove(fn) { + for (let i = head; i < xs.length; i++) { + if (fn(xs[i])) + return (xs.splice(i, 1), true) + } + return false + } + } +} + +const limit = 2000 + +function alone(x) { + return x.alone === undefined + ? x.alone = opens(x.text) + : x.alone +} + +function opens(text) { + if (begins.test(text)) + return true + + starts.lastIndex = 0 + let match + while ((match = starts.exec(text))) { + const from = match.index + 5 + let i = from + while (true) { + while (i < text.length && /\s/.test(text[i])) + i++ + + if (text[i] !== '/' || text[i + 1] !== '*') + break + + const end = text.indexOf('*/', i + 2) + if (end === -1) + return false + + i = end + 2 + } + + if (i > from && transaction.test(text.slice(i, i + 12))) + return true + + starts.lastIndex = Math.max(starts.lastIndex, i) + } + + return false +} + +function Statements(scheduler) { + const prefix = Math.random().toString(36).slice(2, 10) + , map = new Map() + , templates = new WeakMap() + + let counter = 1 + , clock = 0 + + const texts = new Map() + + return { get, clear, known } + + function known(text) { + let x = texts.get(text) + if (x) + return x + + texts.set(text, x = { text, est: undefined, alone: undefined }) + texts.size > limit && texts.delete(texts.keys().next().value) + return x + } + + function get(built, prepare) { + if (!prepare) + return unnamed(built.text) + + const tagged = !built.dynamic && (templates.get(built.strings) || set(built.strings)) + , cached = tagged && tagged.get(built.types) + + if (cached && cached.live) + return (cached.used = clock++, cached) + + const key = built.types + '\0' + built.text + let statement = map.get(key) + statement ? statement.used = clock++ : statement = add(key, built.text) + tagged && tagged.set(built.types, statement) + return statement + } + + function unnamed(text) { + return { + key: null, live: false, name: '', text, ends: undefined, shape: undefined, version: 0, used: 0, + cost: scheduler ? known(text) : null + } + } + + function add(key, text) { + const statement = { + key, live: true, name: prefix + counter++, text, ends: undefined, shape: undefined, version: 0, used: clock++, + cost: { est: undefined }, alone: undefined + } + map.set(key, statement) + map.size > limit && evict() + return statement + } + + function evict() { + let oldest = null + for (const x of map.values()) + (!oldest || x.used < oldest.used) && (oldest = x) + oldest.live = false + map.delete(oldest.key) + } + + function set(strings) { + const x = new Map() + templates.set(strings, x) + return x + } + + function clear() { + map.forEach(x => x.live = false) + map.clear() + } +} diff --git a/node_modules/postgres/src/protocol.js b/node_modules/postgres/src/protocol.js new file mode 100644 index 0000000..726fd56 --- /dev/null +++ b/node_modules/postgres/src/protocol.js @@ -0,0 +1,458 @@ +export function Writer(size = 16384) { + let b = Buffer.allocUnsafe(size) + , i = 0 + , at = 0 + + const w = { + get length() { return i }, + type(x) { + fit(5) + at = i + b[i] = x + i += 5 + return w + }, + untyped() { + fit(4) + at = i + i += 4 + return w + }, + end() { + b.writeInt32BE(i - at - 1, at + 1) + return w + }, + endUntyped() { + b.writeInt32BE(i - at, at) + return w + }, + str(x) { + fit(x.length * 3 + 1) + i += b.write(x, i) + b[i++] = 0 + return w + }, + bytes(x) { + if (typeof x === 'string') { + fit(x.length * 3) + i += b.write(x, i) + } else { + fit(x.length) + b.set(x, i) + i += x.length + } + return w + }, + value(x) { + if (x === null || x === undefined) + return w.i32(-1) + const n = i + i += 4 + w.bytes(x) + b.writeInt32BE(i - n - 4, n) + return w + }, + u8(x) { + fit(1) + b[i++] = x + return w + }, + i16(x) { + fit(2) + b.writeInt16BE(x, i) + i += 2 + return w + }, + u16(x) { + fit(2) + b.writeUInt16BE(x, i) + i += 2 + return w + }, + i32(x) { + fit(4) + b.writeInt32BE(x, i) + i += 4 + return w + }, + truncate(n) { + i = n + return w + }, + take() { + const out = i < 4096 ? Buffer.from(b.subarray(0, i)) : b.subarray(0, i) + i >= 4096 && (b = Buffer.allocUnsafe(size)) + i = at = 0 + return out + } + } + + return w + + function fit(n) { + if (b.length - i >= n) + return + + const prev = b + b = Buffer.allocUnsafe(Math.max(size, prev.length * 2, i + n)) + prev.copy(b, 0, 0, i) + } +} + +const own = Writer(1024) + +const S = 83 + , H = 72 + , X = 88 + , c = 99 + , Q = 81 + , p = 112 + , d = 100 + , f = 102 + , D = 68 + , C = 67 + , E = 69 + , P = 80 + , B = 66 + +export const sync = w => w.type(S).end() +export const flush = w => w.type(H).end() +export const terminate = w => w.type(X).end() +export const copyDone = w => w.type(c).end() +export const sslRequest = w => w.untyped().i32(80877103).endUntyped() +export const query = (w, text) => w.type(Q).str(text).end() +export const password = (w, x) => w.type(p).str(x).end() +export const saslResponse = (w, x) => w.type(p).bytes(x).end() +export const copyData = (w, x) => w.type(d).bytes(x).end() +export const copyFail = (w, x) => w.type(f).str(x).end() +export const describe = (w, kind, name) => w.type(D).u8(kind.charCodeAt(0)).str(name).end() +export const close = (w, kind, name) => w.type(C).u8(kind.charCodeAt(0)).str(name).end() +export const execute = (w, portal, rows = 0) => w.type(E).str(portal).i32(rows).end() +export const cancel = (w, pid, secret) => w.untyped().i32(80877102).i32(pid).i32(secret).endUntyped() + +export const Sync = one(sync) +export const Flush = one(flush) +export const Terminate = one(terminate) +export const CopyDone = one(copyDone) +export const SSLRequest = one(sslRequest) +export const Query = one(query) +export const Password = one(password) +export const SASLResponse = one(saslResponse) +export const CopyData = one(copyData) +export const CopyFail = one(copyFail) +export const Describe = one(describe) +export const Close = one(close) +export const Execute = one(execute) +export const Cancel = one(cancel) +export const Startup = one(startup) +export const SASL = one(sasl) +export const Parse = one(parse) +export const Bind = one(bind) +export const Run = one(run) + +function one(fn) { + return (...xs) => { + try { + fn(own, ...xs) + } catch (error) { + own.truncate(0) + throw error + } + return own.take() + } +} + +export function startup(w, parameters) { + w.untyped().i32(196608) + for (const k in parameters) + parameters[k] && w.str(unbroken(k, k)).str(unbroken(k, '' + parameters[k])) + + return w.u8(0).endUntyped() +} + +function unbroken(k, x) { + if (x.indexOf('\0') !== -1) + throw Object.assign(new Error('The connection parameter ' + k + ' contains a NUL character'), { code: 'NUL_CHARACTER' }) + + return x +} + +export function sasl(w, mechanism, initial) { + return w.type(p).str(mechanism).i32(Buffer.byteLength(initial)).bytes(initial).end() +} + +export function parse(w, name, text, oids = []) { + w.type(P).str(name).str(text).u16(oids.length) + for (let j = 0; j < oids.length; j++) + w.i32(oids[j] | 0) + + return w.end() +} + +export function bind(w, portal, name, values = [], formats = [], resultFormats = []) { + w.type(B).str(portal).str(name).i16(formats.length) + for (let j = 0; j < formats.length; j++) + w.i16(formats[j]) + + w.u16(values.length) + for (let j = 0; j < values.length; j++) + w.value(values[j]) + + w.i16(resultFormats.length) + for (let j = 0; j < resultFormats.length; j++) + w.i16(resultFormats[j]) + + return w.end() +} + +export function run(w, portal, name, values, rows, flushing) { + bind(w, portal, name, values) + execute(w, portal, rows) + return flushing ? flush(w) : sync(w) +} + +const largest = 0x40000000 + +export function Frames(onframe, shared = false, onerror = null) { + const chunks = [] + , owned = new WeakSet() + + let data = null + , owning = false + , at = 0 + , part = null + , filled = 0 + , paused = false + , running = false + , broken = false + + return { + push(x) { + if (broken) + return + + chunks.push(shared && (paused || owning) ? own(x) : x) + run() + }, + get paused() { + return paused + }, + owns(x) { + return !shared || owned.has(x) + }, + own(x) { + owning = x + x && settle() + }, + pause() { + paused = true + settle() + }, + resume() { + paused = false + run() + } + } + + function own(x) { + const copy = Buffer.from(x) + owned.add(copy) + return copy + } + + function settle() { + if (!shared) + return + + data && at < data.length && !owned.has(data) && (data = own(data.subarray(at)), at = 0) + for (let i = 0; i < chunks.length; i++) + owned.has(chunks[i]) || (chunks[i] = own(chunks[i])) + } + + function run() { + if (running) + return + + running = true + try { + while (true) { + if (broken || paused || !(data && at < data.length || next())) + break + part ? fill() : frame() + } + } finally { + running = false + } + } + + function invalid(length) { + if (length >= 4 && length <= largest) + return false + + broken = true + chunks.length = 0 + data = part = null + at = filled = 0 + const error = Object.assign(new Error('The server sent a message with an invalid length (' + length + ')'), { code: 'PROTOCOL_ERROR' }) + onerror && onerror(error) + return true + } + + function next() { + data = chunks.shift() || null + at = 0 + return data !== null + } + + function frame() { + const left = data.length - at + if (left < 5) + return start(5) + + const length = data.readInt32BE(at + 1) + if (invalid(length)) + return + + const end = at + 1 + length + if (end > data.length) + return start(end - at) + + const begin = at + at = end + onframe(data[begin], data, begin, end) + } + + function start(length) { + part = Buffer.allocUnsafe(length) + shared && owned.add(part) + filled = data.copy(part, 0, at) + at = data.length + } + + function fill() { + const n = data.copy(part, filled, at, at + part.length - filled) + filled += n + at += n + if (filled < part.length) + return + + if (part.length === 5) { + const head = part + , length = head.readInt32BE(1) + if (invalid(length)) + return + + part = Buffer.allocUnsafe(1 + length) + shared && owned.add(part) + filled = head.copy(part) + return filled === part.length && done() + } + done() + } + + function done() { + const x = part + part = null + onframe(x[0], x, 0, x.length) + } +} + +const errorFields = { + 83: 'severity_local', + 86: 'severity', + 67: 'code', + 77: 'message', + 68: 'detail', + 72: 'hint', + 80: 'position', + 112: 'internal_position', + 113: 'internal_query', + 87: 'where', + 115: 'schema_name', + 116: 'table_name', + 99: 'column_name', + 100: 'data_type_name', + 110: 'constraint_name', + 70: 'file', + 76: 'line', + 82: 'routine' +} + +export function error(x, start, end) { + const fields = {} + for (let i = start + 5; i < end - 1;) { + const zero = x.indexOf(0, i + 1) + fields[errorFields[x[i]] || String.fromCharCode(x[i])] = x.toString('utf8', i + 1, zero) + i = zero + 1 + } + return fields +} + +export const text = typeof Buffer.prototype.utf8Slice === 'function' + ? (x, start, end) => x.utf8Slice(start, end) + : (x, start, end) => x.toString('utf8', start, end) + +const u32 = (x, i) => ((x[i] << 24) | (x[i + 1] << 16) | (x[i + 2] << 8) | x[i + 3]) >>> 0 + , u16 = (x, i) => (x[i] << 8) | x[i + 1] + , field = (name, table, number, type) => ({ name, table, number, type }) + +export function rowDescription(x, start, end, make = field) { + const columns = new Array((x[start + 5] << 8) | x[start + 6]) + for (let i = start + 7, j = 0; j < columns.length; j++) { + let zero = i + while (x[zero] !== 0) + zero++ + columns[j] = make(text(x, i, zero), u32(x, zero + 1), u16(x, zero + 5), u32(x, zero + 7)) + i = zero + 19 + } + return columns +} + +export function parameterDescription(x, start) { + const oids = new Array(x.readUInt16BE(start + 5)) + for (let j = 0; j < oids.length; j++) + oids[j] = x.readUInt32BE(start + 7 + j * 4) + + return oids +} + +export function commandComplete(x, start, end) { + const first = start + 5 + + let e = end - 1 + , count = null + + while (true) { + let s = e - 1 + while (s >= first && x[s] >= 48 && x[s] <= 57) + s-- + if (s === e - 1 || s < first || x[s] !== 32) + break + count === null && (count = +text(x, s + 1, e)) + e = s + } + + return { command: text(x, first, e), count } +} + +export function readyForQuery(x, start) { + return String.fromCharCode(x[start + 5]) +} + +export function notification(x, start) { + const zero = x.indexOf(0, start + 9) + return { + pid: x.readInt32BE(start + 5), + channel: x.toString('utf8', start + 9, zero), + payload: x.toString('utf8', zero + 1, x.indexOf(0, zero + 1)) + } +} + +export function parameterStatus(x, start) { + const zero = x.indexOf(0, start + 5) + return [x.toString('utf8', start + 5, zero), x.toString('utf8', zero + 1, x.indexOf(0, zero + 1))] +} + +export function backendKeyData(x, start) { + return { pid: x.readInt32BE(start + 5), secret: x.readInt32BE(start + 9) } +} diff --git a/node_modules/postgres/src/query.js b/node_modules/postgres/src/query.js new file mode 100644 index 0000000..202de47 --- /dev/null +++ b/node_modules/postgres/src/query.js @@ -0,0 +1,298 @@ +import util from 'util' +import { build, isQuery, Join, joinStrings } from './build.js' +import { ours } from './errors.js' +import { channels, active, start, finish, now, userName } from './diagnostics.js' +import { statement } from './result.js' + +const origins = new WeakMap() + +export const CLOSE = {} + +export class Query extends Promise { + constructor(strings, args, handler, options = {}) { + let resolve + , reject + + super((a, b) => { + resolve = a + reject = b + }) + + this.fulfil = resolve + this.fail = reject + + this[isQuery] = true + this.tagged = Array.isArray(strings.raw) + this.strings = strings + this.args = args + this.handler = handler + this.options = options + + this.state = null + this.source = null + this.active = false + this.executed = false + this.settled = false + this.built = null + this.trace = null + this.aborts = null + + this.originError = handler.debug ? new Error() : null + this.tagged && !handler.debug && !origins.has(strings) && origins.set(strings, located()) + } + + static get [Symbol.species]() { + return Promise + } + + join(items) { + const kept = [...items].filter(x => x !== false && x !== null && x !== undefined) + , joined = new Query(joinStrings, [new Join(this, kept)], this.handler) + + Object.defineProperty(joined, 'length', { value: kept.length }) + return joined + } + + resolve(x) { + this.aborts && this.aborts() + this.active = false + this.settled = true + this.trace && traced(this, null, x) + this.fulfil(x) + } + + reject(x) { + this.aborts && this.aborts() + this.active = false + this.settled = true + this.trace && traced(this, x) + this.fail(x) + } + + get origin() { + return this.originError + ? this.originError.stack + : this.tagged && origins.get(this.strings) || '' + } + + get statement() { + return this.source && statement(this.source) + } + + build() { + return this.built || (this.built = build(this, this.handler.options)) + } + + get text() { + return this.build().text + } + + get parameters() { + return this.build().values + } + + [util.inspect.custom](depth, options, inspect) { + if (!this.handler.debug) + return 'Query {}' + + let x + try { + x = this.build() + } catch (error) { + return 'Query { ' + error.message + ' }' + } + return 'Query ' + inspect({ text: x.text, parameters: x.values }, options) + } + + cancel() { + return this.handler.cancel ? this.handler.cancel(this) : Promise.resolve() + } + + signal(signal) { + if (!signal || this.settled) + return this + + if (signal.aborted) + return (this.cancel(), this) + + const abort = () => this.cancel() + signal.addEventListener('abort', abort, { once: true }) + this.aborts = () => (this.aborts = null, signal.removeEventListener('abort', abort)) + return this + } + + simple() { + this.options.simple = true + this.options.prepare = false + return this + } + + async readable() { + this.simple() + this.streaming = true + return this + } + + async writable() { + this.simple() + this.streaming = true + return this + } + + cursor(rows = 1, fn) { + this.options.simple = false + if (typeof rows === 'function') { + fn = rows + rows = 1 + } + + this.cursorRows = rows + + if (typeof fn === 'function') + return (this.cursorFn = fn, this) + + let prev + return { + [Symbol.asyncIterator]: () => ({ + next: () => { + if (this.executed && !this.active) + return { done: true } + + prev && prev() + const promise = new Promise((resolve, reject) => { + this.cursorFn = value => { + resolve({ value, done: false }) + return new Promise(r => prev = r) + } + this.resolve = x => (this.active = false, this.settled = true, this.trace && traced(this, null, x), resolve({ done: true })) + this.reject = x => (this.active = false, this.settled = true, this.trace && traced(this, x), reject(x)) + }) + this.execute() + return promise + }, + return() { + prev && prev(CLOSE) + return { done: true } + } + }) + } + } + + describe() { + this.options.simple = false + this.onlyDescribe = this.options.prepare = true + return this + } + + stream() { + throw new Error('.stream has been renamed to .forEach') + } + + forEach(fn) { + this.forEachFn = fn + this.handle() + return this + } + + raw() { + this.isRaw = true + return this + } + + values() { + this.isRaw = 'values' + return this + } + + handle() { + if (this.executed) + return + + this.executed = true + queueMicrotask(() => this.run()) + } + + run() { + active(channels.query) + ? start(channels.query, this.trace = context(this), () => this.handler(this)) + : this.handler(this) + } + + execute() { + this.handle() + return this + } + + then(fulfilled, rejected) { + this.handle() + return super.then(fulfilled, rejected) + } + + catch(rejected) { + this.handle() + return super.catch(rejected) + } + + finally(fn) { + this.handle() + return super.finally(fn) + } +} + +function context(q) { + const options = q.handler.options || {} + let text = null + if (q.strings.length) { + try { + text = q.text + } catch (error) { + text = null + } + } + return { + query: text, + parameters: undefined, + database: options.database, + user: userName(options), + host: null, + port: null, + connection: null, + statement: null, + command: null, + count: null, + queued: now(), + sent: null, + firstByte: null, + complete: null + } +} + +function traced(q, error, result) { + const x = q.trace + q.trace = null + x.complete = now() + if (result && typeof result === 'object' && 'command' in result) { + x.command = result.command + x.count = result.count + } + finish(channels.query, x, error, result) +} + +function located() { + const limit = Error.stackTraceLimit + Error.stackTraceLimit = 8 + try { + return trim(String(new Error().stack)) + } catch (error) { + return '' + } finally { + Error.stackTraceLimit = limit + } +} + +function trim(stack) { + const lines = stack.split('\n') + , i = lines.findIndex((x, i) => i > 0 && !ours(x)) + + return i === -1 ? stack : lines.slice(0, i + 1).join('\n') +} diff --git a/node_modules/postgres/src/result.js b/node_modules/postgres/src/result.js new file mode 100644 index 0000000..b4a8208 --- /dev/null +++ b/node_modules/postgres/src/result.js @@ -0,0 +1,36 @@ +export default class Result extends Array { + #count = null + #state = null + #command = null + #columns = null + #statement = null + + get count() { return this.#count } + set count(x) { this.#count = x } + get state() { return this.#state } + set state(x) { this.#state = x } + get command() { return this.#command } + set command(x) { this.#command = x } + get columns() { return this.#columns } + set columns(x) { this.#columns = x } + get statement() { + const x = this.#statement + return x && x.kind ? (this.#statement = statement(x)) : x + } + + set statement(x) { this.#statement = x } + + static get [Symbol.species]() { + return Array + } +} + +export function statement(item) { + const x = item.statement + return { + name: x ? x.name : '', + string: x ? x.text : item.text || '', + types: item.params || (item.entry && item.entry.oids) || (x && x.oids) || [], + columns: item.columns || [] + } +} diff --git a/node_modules/postgres/src/socket.js b/node_modules/postgres/src/socket.js new file mode 100644 index 0000000..090b8fb --- /dev/null +++ b/node_modules/postgres/src/socket.js @@ -0,0 +1,149 @@ +import net from 'net' +import tls from 'tls' + +const noop = () => {} + , agent = globalThis.navigator && globalThis.navigator.userAgent || '' + , workers = agent.startsWith('Cloudflare-Workers') + , onreadSafe = !agent || agent.startsWith('Node.js') || agent.startsWith('Bun') || agent.startsWith('Deno') + +export async function Socket(options, host, port, track = noop) { + const raw = options.socket + ? await options.socket(options, host, port) + : await connect(options, host, port, track) + + return wrap(raw, host) +} + +export function secureOptions(ssl) { + return ssl === 'require' || ssl === 'allow' || ssl === 'prefer' + ? workers ? {} : { rejectUnauthorized: false } + : typeof ssl === 'object' ? ssl : {} +} + +export const secured = options => !!options.ssl && options.ssl !== 'disable' + +export const direct = options => secured(options) && options.sslnegotiation === 'direct' + +function connect(options, host, port, track) { + return new Promise((resolve, reject) => { + const tlsNow = direct(options) + , plain = !secured(options) + , reads = (plain || tlsNow) && onreadSafe && options.onread !== false && { + buffer: Buffer.allocUnsafe(65536), + callback: (n, b) => socket.ondata(b.subarray(0, n)) + } + , target = options.path ? { path: options.path } : { port, host } + , socket = tlsNow + ? tls.connect({ + ...target, + servername: net.isIP(host || '') || options.path ? undefined : host, + ...secureOptions(options.ssl), + ALPNProtocols: ['postgresql'], + ...(reads ? { onread: reads } : {}) + }) + : net.connect({ ...target, ...(reads ? { onread: reads } : {}) }) + track(socket) + socket.shared = !!reads + socket.secure = tlsNow + socket.ondata = noop + socket.once('error', reject) + socket.once(tlsNow ? 'secureConnect' : 'connect', () => { + socket.off('error', reject) + socket.setNoDelay(true) + resolve(socket) + }) + }) +} + +function wrap(socket, host) { + let closed = false + , failure = null + + socket.shared && (socket.ondata = data) + + const x = { + ondata: noop, + ondrain: noop, + onclose: noop, + get raw() { return socket }, + get closed() { return closed }, + get shared() { return !!socket.shared }, + get negotiated() { return !!socket.secure || !!socket.negotiated }, + certificate() { + const x = typeof socket.getPeerCertificate === 'function' && socket.getPeerCertificate() + return x && x.raw || null + }, + write: data => !closed && socket.write(data), + upgrade, + pause: () => socket.pause(), + resume: () => socket.resume(), + ref: () => socket.ref && socket.ref(), + unref: () => socket.unref && socket.unref(), + end(data) { + closed || (data ? socket.end(data) : socket.end()) + }, + destroy(error) { + error && !failure && (failure = error) + socket.destroy() + }, + keepAlive(seconds) { + seconds && socket.setKeepAlive && socket.setKeepAlive(true, 1000 * seconds) + } + } + + listen() + return x + + function listen() { + socket.on('data', data) + socket.on('drain', drain) + socket.on('error', error) + socket.on('close', close) + } + + function unlisten() { + socket.off('data', data) + socket.off('drain', drain) + socket.off('error', error) + socket.off('close', close) + } + + function data(buffer) { x.ondata(buffer) } + function drain() { x.ondrain() } + function error(err) { + failure || (failure = err) + socket.destroy() + close() + } + + function close() { + if (closed) + return + + closed = true + x.onclose(failure) + } + + function upgrade(options = {}) { + return new Promise((resolve, reject) => { + unlisten() + const secure = tls.connect({ + socket, + servername: net.isIP(host || '') ? undefined : host, + ...options + }) + const fail = err => { + secure.off('secureConnect', ready) + reject(err) + } + function ready() { + secure.off('error', fail) + socket = secure + listen() + resolve(x) + } + secure.once('secureConnect', ready) + secure.once('error', fail) + }) + } +} diff --git a/node_modules/postgres/src/startup.js b/node_modules/postgres/src/startup.js new file mode 100644 index 0000000..bb5a24d --- /dev/null +++ b/node_modules/postgres/src/startup.js @@ -0,0 +1,469 @@ +import crypto from 'crypto' +import fs from 'fs' +import * as p from './protocol.js' +import { Socket, secured, secureOptions } from './socket.js' +import { Errors } from './errors.js' +import { channels, active, start, finish, userName } from './diagnostics.js' + +const noop = () => {} + +const R = 82 + , S = 83 + , K = 75 + , E = 69 + , N = 78 + , D = 68 + , Z = 90 + +export async function open(options, signal = { aborted: false, sockets: new Set() }, first = 0) { + const hosts = options.path ? [null] : options.host + , wanted = options.target_session_attrs + , passes = wanted === 'prefer-standby' ? ['standby', 'any'] : [wanted || 'any'] + + let last + + for (const want of passes) { + for (let n = 0; n < hosts.length; n++) { + const i = (first + n) % hosts.length + , host = hosts[i] + , port = options.port[i] || options.port[0] + , [failed, error, ready] = await traced(options, host, port, signal).then(x => [false, null, x], x => [true, x]) + if (!failed && fits(want, ready.attributes)) + return (ready.index = i, ready) + failed || ready.socket.end(p.Terminate()) + last = failed ? error : Errors.connection('CONNECTION_DESTROYED', options, host, port) + if (signal.aborted) + throw last + } + } + + throw last +} + +function traced(options, host, port, signal) { + if (!active(channels.connect)) + return attempt(options, host, port, signal) + + const context = { + host: options.path ? null : host, + port: options.path ? null : port, + path: options.path || null, + database: options.database, + user: userName(options), + ssl: secured(options), + sslnegotiation: options.sslnegotiation || 'postgres' + } + let promise + start(channels.connect, context, () => promise = attempt(options, host, port, signal)) + + return promise.then(ready => { + finish(channels.connect, context, null, { + pid: ready.backend.pid, + status: ready.status, + readOnly: ready.attributes.readOnly, + standby: ready.attributes.standby + }) + return ready + }, error => { + finish(channels.connect, context, error) + throw error + }) +} + +function fits(want, { readOnly, standby }) { + return want === 'any' + || (want === 'read-write' && !readOnly) + || (want === 'read-only' && readOnly) + || (want === 'primary' && !standby) + || (want === 'standby' && standby) +} + +function attempt(options, host, port, signal) { + const { setTimeout, clearTimeout } = options.timers + , fail = code => Errors.connection(code, options, host, port) + + return new Promise((resolve, reject) => { + const timer = options.connect_timeout && setTimeout(() => done(true, fail('CONNECT_TIMEOUT')), options.connect_timeout * 1000) + + let socket = null + , raw = null + , settled = false + + session().then(x => done(false, null, x), e => done(true, e)) + + function done(failed, error, ready) { + if (settled) + return + + settled = true + timer && clearTimeout(timer) + socket && signal.sockets.delete(socket) + signal.aborted && !failed && (failed = true, error = fail('CONNECTION_DESTROYED')) + + if (failed) { + socket ? socket.destroy() : raw && raw.destroy() + return reject(error) + } + + ready.socket.onclose = () => {} + resolve(ready) + } + + async function session() { + socket = await Socket(options, host, port, x => raw = x) + if (settled || signal.aborted) + return (socket.destroy(), done(true, fail('CONNECTION_DESTROYED'))) + + signal.sockets.add(socket) + socket.onclose = error => done(true, signal.aborted ? fail('CONNECTION_DESTROYED') : error && error.code ? error : fail('CONNECTION_CLOSED')) + socket.keepAlive(options.keep_alive) + await negotiate(socket, options) + const user = typeof options.user === 'function' ? await options.user() : options.user + return startup(user, options.database || user) + } + + function startup(user, database) { + return new Promise((resolve, reject) => { + const stored = () => pgpass(options.passfile, options.path ? 'localhost' : host, port, database, user) || '' + , auth = Auth({ user, pass: options.pass || stored, binding: options.channel_binding, socket }) + , parameters = {} + , backend = { pid: null, secret: null } + , frames = p.Frames(frame, false, error => (reject(error), socket.destroy())) + , rows = [] + + let probing = false + , status = null + , authing = Promise.resolve() + + socket.ondata = x => frames.push(x) + socket.write(p.Startup({ user, database, client_encoding: 'UTF8', ...options.connection })) + + function frame(type, x, start, end) { + try { + type === R ? authenticate(Buffer.from(x.subarray(start, end))) + : type === S ? (([k, v]) => parameters[k] = v)(p.parameterStatus(x, start)) + : type === K ? Object.assign(backend, p.backendKeyData(x, start)) + : type === E ? reject(Errors.postgres(p.error(x, start, end))) + : type === N ? notice(p.error(x, start, end)) + : type === D ? rows.push(x.toString('utf8', start + 11, start + 11 + x.readInt32BE(start + 7))) + : type === Z && settled(p.readyForQuery(x, start), Buffer.from(x.subarray(end))) + } catch (error) { + reject(error) + } + } + + function notice(x) { + try { + options.onnotice ? options.onnotice(x) : options.onnotice === false || console.log(x) + } catch (error) { + noop(error) + } + } + + function authenticate(x) { + authing = authing.then(() => auth(x)).then(reply => reply && socket.write(reply)) + authing.catch(error => (reject(error), socket.destroy())) + } + + function settled(x, rest) { + authing.then(() => ready(x, rest), () => {}) + } + + function ready(x, rest) { + if (!auth.authenticated) + return reject(Errors.generic('AUTHENTICATION_INCOMPLETE', 'The server was ready before it accepted the authentication')) + + status = x + const known = 'in_hot_standby' in parameters && 'default_transaction_read_only' in parameters + + if (options.target_session_attrs && !known && !probing) { + probing = true + return socket.write(p.Query('show transaction_read_only; select pg_catalog.pg_is_in_recovery()')) + } + + frames.pause() + socket.ondata = () => {} + socket.pause() + resolve({ + socket, + rest, + backend, + parameters, + status, + attributes: { + readOnly: (known ? parameters.default_transaction_read_only : rows[0]) === 'on', + standby: known ? parameters.in_hot_standby === 'on' : rows[1] === 't' + }, + host, + port, + cancel: () => cancel(options, host, port, backend) + }) + } + }) + } + }) +} + +async function negotiate(socket, options) { + if (!secured(options) || socket.negotiated) + return + + const ssl = options.ssl + , tls = secureOptions(ssl) + + if (options.sslnegotiation === 'direct') + return socket.upgrade({ ...tls, ALPNProtocols: ['postgresql'] }) + + const answer = new Promise(r => socket.ondata = x => r(x[0])) + socket.write(p.SSLRequest()) + + if (await answer === S) + return socket.upgrade(tls) + + if (ssl !== 'prefer' && ssl !== 'allow') + throw Errors.generic('SSL_NOT_SUPPORTED', 'The server does not support SSL connections') +} + +async function cancel(options, host, port, { pid, secret }) { + const socket = await Socket(options, host, port) + try { + await negotiate(socket, options) + } catch (error) { + socket.destroy() + throw error + } + return new Promise(resolve => { + socket.onclose = () => resolve() + socket.end(p.Cancel(pid, secret)) + }) +} + +const salted = new Map() + +function Auth({ user, pass, binding = 'prefer', socket }) { + let nonce + , signature + , verified = true + , bound = false + , header = 'n,,' + + respond.authenticated = false + return respond + + async function respond(x) { + const type = x.readInt32BE(5) + if ((type === 3 || type === 5) && binding === 'require') + throw unbound('the server asked for ' + (type === 3 ? 'a cleartext' : 'an MD5') + ' password') + + return type === 0 ? ok() + : type === 3 ? p.Password(await password()) + : type === 5 ? p.Password('md5' + md5(Buffer.concat([Buffer.from(md5(await password() + user)), x.subarray(9, 13)]))) + : type === 10 ? start(x) + : type === 11 ? proceed(x, await password()) + : type === 12 ? finish(x) + : unsupported(type) + } + + function start(x) { + const offered = x.toString('utf8', 9).split('\0') + , certificate = binding !== 'disable' && socket && socket.certificate && socket.certificate() + , hash = certificate && endpoint(certificate) + , plus = !!hash && offered.includes('SCRAM-SHA-256-PLUS') + + if (binding === 'require' && !plus) + throw unbound(offered.includes('SCRAM-SHA-256-PLUS') ? 'the server certificate could not be hashed for it' : 'the server did not offer it') + + if (!plus && !offered.includes('SCRAM-SHA-256')) + throw Errors.generic('SASL_MECHANISM_NOT_SUPPORTED', 'The server offered no supported SASL mechanism') + + header = plus ? 'p=tls-server-end-point,,' : hash ? 'y,,' : 'n,,' + bound = plus ? hash : false + nonce = crypto.randomBytes(18).toString('base64') + verified = false + return p.SASL(plus ? 'SCRAM-SHA-256-PLUS' : 'SCRAM-SHA-256', header + 'n=*,r=' + nonce) + } + + function proceed(x, pass) { + const res = x.toString('utf8', 9).split(',').reduce((acc, x) => (acc[x[0]] = x.slice(2), acc), {}) + , key = sha256(pass + '\0' + res.s + '\0' + res.i).toString('base64') + + if (!res.r.startsWith(nonce)) + throw Errors.generic('SASL_NONCE_MISMATCH', 'The server nonce does not start with the client nonce') + + if (!salted.has(key)) { + salted.size >= 64 && salted.delete(salted.keys().next().value) + salted.set(key, crypto.pbkdf2Sync(pass, Buffer.from(res.s, 'base64'), +res.i, 32, 'sha256')) + } + + const saltedPassword = salted.get(key) + , clientKey = hmac(saltedPassword, 'Client Key') + , channel = (bound ? Buffer.concat([Buffer.from(header), bound]) : Buffer.from(header)).toString('base64') + , auth = 'n=*,r=' + nonce + ',r=' + res.r + ',s=' + res.s + ',i=' + res.i + ',c=' + channel + ',r=' + res.r + + signature = hmac(hmac(saltedPassword, 'Server Key'), auth).toString('base64') + return p.SASLResponse('c=' + channel + ',r=' + res.r + ',p=' + xor(clientKey, hmac(sha256(clientKey), auth)).toString('base64')) + } + + function finish(x) { + if (!signature || x.toString('utf8', 9).split('\0', 1)[0].slice(2) !== signature) + throw Errors.generic('SASL_SIGNATURE_MISMATCH', 'The server did not return the correct signature') + + verified = true + return null + } + + function ok() { + if (!verified) + throw Errors.generic('SASL_SIGNATURE_MISMATCH', 'The server ended SCRAM authentication without proving it knows the password') + + if (binding === 'require' && !bound) + throw unbound('the server authenticated without it') + + respond.authenticated = true + return null + } + + function unsupported(type) { + throw Errors.generic('AUTH_TYPE_NOT_IMPLEMENTED', 'Authentication type ' + type + ' is not supported') + } + + function password() { + return Promise.resolve(typeof pass === 'function' ? pass() : pass) + } +} + +function unbound(reason) { + return Errors.generic('CHANNEL_BINDING_REQUIRED', 'channel_binding is require, but ' + reason) +} + +const signatures = { + '2a864886f70d010104': 'sha256', + '2a864886f70d010105': 'sha256', + '2a864886f70d01010e': 'sha224', + '2a864886f70d01010b': 'sha256', + '2a864886f70d01010c': 'sha384', + '2a864886f70d01010d': 'sha512', + '2a8648ce3d0401': 'sha256', + '2a8648ce3d040301': 'sha224', + '2a8648ce3d040302': 'sha256', + '2a8648ce3d040303': 'sha384', + '2a8648ce3d040304': 'sha512', + '2a8648ce380403': 'sha256', + '608648016503040302': 'sha256' +} + +const digests = { + '2b0e03021a': 'sha256', + '608648016503040201': 'sha256', + '608648016503040202': 'sha384', + '608648016503040203': 'sha512', + '608648016503040204': 'sha224' +} + +function endpoint(certificate) { + try { + const x = Buffer.from(certificate) + , algorithm = signature(x) + return algorithm ? crypto.createHash(algorithm).update(x).digest() : null + } catch (_) { + return null + } +} + +function signature(x) { + const certificate = der(x, 0) + , tbs = der(x, certificate.body) + , algorithm = der(x, tbs.end) + , oid = der(x, algorithm.body) + , name = x[oid.start] === 0x06 && x.toString('hex', oid.body, oid.end) + + if (name !== '2a864886f70d01010a') + return signatures[name] + + if (oid.end >= algorithm.end) + return 'sha256' + + const params = der(x, oid.end) + , first = params.body < params.end && der(x, params.body) + + if (!first || x[first.start] !== 0xa0) + return 'sha256' + + const hash = der(x, der(x, first.body).body) + return digests[x.toString('hex', hash.body, hash.end)] +} + +function der(x, start) { + let length = x[start + 1] + , body = start + 2 + + if (length & 0x80) { + const n = length & 0x7f + length = 0 + for (let i = 0; i < n; i++) + length = length * 256 + x[body + i] + body += n + } + + if (body + length > x.length) + throw new Error('Truncated certificate') + + return { start, body, end: body + length } +} + +function md5(x) { + return crypto.createHash('md5').update(x).digest('hex') +} + +function hmac(key, x) { + return crypto.createHmac('sha256', key).update(x).digest() +} + +function sha256(x) { + return crypto.createHash('sha256').update(x).digest() +} + +function xor(a, b) { + const x = Buffer.allocUnsafe(a.length) + for (let i = 0; i < a.length; i++) + x[i] = a[i] ^ b[i] + return x +} + +function pgpass(file, host, port, database, user) { + if (!file) + return null + + let text + try { + const stat = fs.statSync(file) + if (!stat.isFile() || (process.platform !== 'win32' && (stat.mode & 0o077))) + return null + text = fs.readFileSync(file, 'utf8') + } catch (_) { + return null + } + const wanted = [host, String(port), database, user] + for (const line of text.split(/\r?\n/)) { + const fields = line && line[0] !== '#' ? split(line) : [] + if (fields.length === 5 && wanted.every((x, i) => fields[i] === '*' || fields[i] === x)) + return fields[4] + } + return null +} + +function split(line) { + const fields = [] + let field = '' + for (let i = 0; i < line.length; i++) { + const c = line[i] + if (c === '\\' && i + 1 < line.length) + field += line[++i] + else if (c === ':' && fields.length < 4) + fields.push(field), field = '' + else + field += c + } + fields.push(field) + return fields +} diff --git a/node_modules/postgres/src/subscribe.js b/node_modules/postgres/src/subscribe.js new file mode 100644 index 0000000..093b271 --- /dev/null +++ b/node_modules/postgres/src/subscribe.js @@ -0,0 +1,403 @@ +import { own } from './connection.js' + +const noop = () => {} + , statusInterval = 10000 + , epoch = BigInt(Date.UTC(2000, 0, 1)) * 1000n + +const lsnToString = x => (x >> 32n).toString(16).toUpperCase() + '/' + (x & 0xFFFFFFFFn).toString(16).toUpperCase() + +export default function Subscribe(postgres, options) { + const subscribers = new Map() + , persistent = !!options.slot + , slot = options.slot || 'postgresjs_' + Math.random().toString(36).slice(2) + , state = {} + , timers = options.timers + + let connection + , current = null + , ended = false + , retries = 0 + + const sql = subscribe.sql = postgres({ + ...options, + transform: { column: {}, value: {}, row: {} }, + max: 1, + idle_timeout: null, + max_lifetime: null, + connection: { + ...options.connection, + replication: 'database' + }, + onclose: () => { + current && current.stop() + current = null + state.pid = state.secret = undefined + ended || restart() + }, + no_subscribe: true + }) + + const end = sql.end + , close = sql.close + + sql.end = async() => { + ended = true + current && await current.finish() + return end() + } + + sql.close = async() => { + current && await current.finish() + return close() + } + + return subscribe + + async function subscribe(event, fn, onsubscribe = noop, onerror) { + event = parseEvent(event) + + connection || (connection = init()) + + const subscriber = { fn, onsubscribe, onerror } + const fns = subscribers.has(event) + ? subscribers.get(event).add(subscriber) + : subscribers.set(event, new Set([subscriber])).get(event) + + const unsubscribe = () => { + fns.delete(subscriber) + fns.size === 0 && subscribers.delete(event) + } + + return connection.then(() => { + onsubscribe() + return { unsubscribe, state, sql } + }, error => { + unsubscribe() + connection = null + throw error + }) + } + + function restart() { + const delay = Math.min(100 * 2 ** retries++, 10000) + connection = new Promise(r => timers.setTimeout(r, retries === 1 ? 0 : delay)).then(() => ended || init()).then( + x => { + retries = 0 + ended || subscribers.forEach(event => event.forEach(({ onsubscribe }) => onsubscribe())) + return x + }, + error => { + report(error) + ended || restart() + } + ) + connection.catch(noop) + } + + async function init() { + if (!options.publications) + throw new Error('Missing publication names') + + await sql.unsafe(`CREATE_REPLICATION_SLOT ${ slot }${ persistent ? '' : ' TEMPORARY' } LOGICAL pgoutput NOEXPORT_SNAPSHOT`).catch(error => { + if (!persistent || error.code !== '42710') + throw error + }) + + const query = sql.unsafe(`START_REPLICATION SLOT ${ slot } LOGICAL 0/0 (proto_version '1', publication_names '${ options.publications }')`) + query.catch(noop) + const stream = await query.writable() + current = Stream(stream) + state.pid = query.state && query.state.pid + state.secret = query.state && query.state.secret + return current + } + + function Stream(stream) { + const relations = {} + let acked = 0n + , received = 0n + , transaction = null + , queue = null + , failed = false + , stopped = false + , timer = timers.setTimeout(tick, statusInterval) + , soon = null + + stream.on('data', data) + stream.on('error', error => failed || report(error)) + stream.on('close', () => { + const unexpected = !stopped + stop() + unexpected && close() + }) + + return { stop, finish } + + function data(x) { + if (x[0] === 0x77) { + received = max(received, x.readBigUInt64BE(9)) + parse(x.subarray(25), relations, sql.options.parsers, message, options.transform) + } else if (x[0] === 0x6b) { + received = max(received, x.readBigUInt64BE(1)) + idle() && (acked = max(acked, received)) + x[17] && status() + } + } + + function message(kind, x, info) { + if (kind === 'begin') + return transaction = { lsn: x.lsn, end: null, time: x.time, xid: x.xid } + + if (kind === 'commit') { + const done = transaction + done.end = x.end + transaction = null + return run(() => commit(done)) + } + + const at = transaction || {} + info.lsn = at.lsn && lsnToString(at.lsn) + info.time = at.time + info.xid = at.xid + run(() => handle(x, info)) + } + + function run(fn) { + if (failed || stopped) + return + + if (queue) { + queue = queue.then(() => failed || stopped ? null : fn()) + return + } + + const result = fn() + if (result && typeof result.then === 'function') { + queue = result + stream.pause() + drain() + } + } + + function drain() { + const at = queue + at.then(() => { + if (queue !== at) + return queue && drain() + + queue = null + stopped || failed || stream.resume() + }, noop) + } + + function commit(done) { + acked = max(acked, done.end) + persistent && !soon && (soon = timers.setImmediate(() => (soon = null, status()))) + } + + function handle(row, info) { + const path = info.relation.schema + '.' + info.relation.table + , key = row && info.relation.keys.length ? '=' + info.relation.keys.map(x => row[x.name]) : '' + , pending = [] + + call(pending, '*', row, info) + call(pending, '*:' + path, row, info) + key && call(pending, '*:' + path + key, row, info) + call(pending, info.command, row, info) + call(pending, info.command + ':' + path, row, info) + key && call(pending, info.command + ':' + path + key, row, info) + return pending.length ? Promise.all(pending) : null + } + + function call(pending, event, row, info) { + subscribers.has(event) && subscribers.get(event).forEach(subscriber => { + let result + try { + result = subscriber.fn(row, info, event) + } catch (error) { + return fail(error, subscriber) + } + result && typeof result.then === 'function' && pending.push(result.catch(error => fail(error, subscriber))) + }) + } + + function fail(error, subscriber) { + report(error, subscriber) + if (!persistent || failed) + return + + failed = true + queue = null + stop() + stream.destroy(new Error('A subscriber failed, so the transaction is delivered again')) + close() + } + + function idle() { + return !transaction && !queue + } + + function tick() { + timer = null + if (stopped) + return + + status() + timer = timers.setTimeout(tick, statusInterval) + } + + function status() { + if (stopped || stream.destroyed || !stream.writable) + return + + const x = Buffer.alloc(34) + x[0] = 0x72 + x.writeBigUInt64BE(acked, 1) + x.writeBigUInt64BE(acked, 9) + x.writeBigUInt64BE(acked, 17) + x.writeBigInt64BE(BigInt(Date.now()) * 1000n - epoch, 25) + stream.write(x) + } + + async function finish() { + queue && await queue.catch(noop) + if (!failed) { + idle() && (acked = max(acked, received)) + status() + } + stop() + stream.destroyed || await new Promise(r => (stream.once('close', r), stream.end())) + } + + function stop() { + if (stopped) + return + + stopped = true + timer && timers.clearTimeout(timer) + soon && timers.clearImmediate(soon) + timer = soon = null + } + } + + function report(error, subscriber) { + const handlers = subscriber + ? [subscriber.onerror] + : [...subscribers.values()].flatMap(x => [...x].map(x => x.onerror)) + + const listeners = handlers.filter(Boolean) + listeners.length + ? listeners.forEach(fn => fn(error)) + : console.error('postgres.js: logical replication error', error) + } +} + +function max(a, b) { + return a > b ? a : b +} + +function Time(x) { + return new Date(Date.UTC(2000, 0, 1) + Number(x / 1000n)) +} + +function parse(x, relations, parsers, message, transform) { + const type = x[0] + if (type === 82) { + let i = 1 + const r = relations[x.readUInt32BE(i)] = { + schema: x.toString('utf8', i += 4, i = x.indexOf(0, i)) || 'pg_catalog', + table: x.toString('utf8', i + 1, i = x.indexOf(0, i + 1)), + columns: Array(x.readUInt16BE(i += 2)), + keys: [] + } + i += 2 + + let columnIndex = 0 + , column + + while (i < x.length) { + column = r.columns[columnIndex++] = { + key: x[i++], + name: transform.column.from + ? transform.column.from(x.toString('utf8', i, i = x.indexOf(0, i))) + : x.toString('utf8', i, i = x.indexOf(0, i)), + type: x.readUInt32BE(i += 1), + parser: parsers[x.readUInt32BE(i)], + atttypmod: x.readUInt32BE(i += 4) + } + + column.key && r.keys.push(column) + i += 4 + } + } else if (type === 66) { + message('begin', { lsn: x.readBigUInt64BE(1), time: Time(x.readBigInt64BE(9)), xid: x.readUInt32BE(17) }) + } else if (type === 67) { + message('commit', { lsn: x.readBigUInt64BE(2), end: x.readBigUInt64BE(10) }) + } else if (type === 73) { + const relation = relations[x.readUInt32BE(1)] + message('change', tuples(x, relation.columns, 8, transform).row, { command: 'insert', relation }) + } else if (type === 68) { + let i = 1 + const relation = relations[x.readUInt32BE(i)] + i += 4 + const key = x[i] === 75 + message('change', key || x[i] === 79 + ? tuples(x, relation.columns, i += 3, transform).row + : null + , { command: 'delete', relation, key }) + } else if (type === 85) { + let i = 1 + const relation = relations[x.readUInt32BE(i)] + i += 4 + const key = x[i] === 75 + const xs = key || x[i] === 79 + ? tuples(x, relation.columns, i += 3, transform) + : null + + xs && (i = xs.i) + + const { row } = tuples(x, relation.columns, i + 3, transform) + message('change', row, { command: 'update', relation, key, old: xs && xs.row }) + } else if (type === 84) { + const count = x.readUInt32BE(1) + , flags = x[5] + for (let i = 0; i < count; i++) { + message('change', null, { + command: 'truncate', + relation: relations[x.readUInt32BE(6 + i * 4)], + cascade: (flags & 1) === 1, + restartIdentity: (flags & 2) === 2 + }) + } + } +} + +function tuples(x, columns, xi, transform) { + let type + , column + , value + + const row = {} + for (let i = 0; i < columns.length; i++) { + type = x[xi++] + column = columns[i] + value = type === 110 + ? null + : type === 117 + ? undefined + : column.parser(x.toString('utf8', xi + 4, xi += 4 + x.readUInt32BE(xi))) + + value = transform.value.from ? transform.value.from(value, column) : value + column.name === '__proto__' ? own(row, column.name, value) : row[column.name] = value + } + + return { i: xi, row: transform.row.from ? transform.row.from(row) : row } +} + +function parseEvent(x) { + const [, command, path, key] = x.match(/^(\*|insert|update|delete|truncate)?:?([^.]+?\.?[^=]+)?=?(.+)?/i) + + return (command || '*') + + (path ? ':' + (path.indexOf('.') === -1 ? 'public.' + path : path) : '') + + (key ? '=' + key : '') +} diff --git a/node_modules/postgres/src/types.js b/node_modules/postgres/src/types.js new file mode 100644 index 0000000..b3c4287 --- /dev/null +++ b/node_modules/postgres/src/types.js @@ -0,0 +1,349 @@ +import { Errors } from './errors.js' + +const number = x => +x + , bool = x => x === 't' + , json = x => JSON.parse(x) + , string = x => x instanceof Date ? serializeDate(x) : Array.isArray(x) ? serializeArray(x, string) : literal(x) ? JSON.stringify(x) : '' + x + , literal = x => x !== null && typeof x === 'object' && (Object.getPrototypeOf(x) === Object.prototype || Object.getPrototypeOf(x) === null) + +const arrays = { + 16: 1000, 17: 1001, 18: 1002, 19: 1003, 20: 1016, 21: 1005, 22: 1006, 23: 1007, 24: 1008, + 25: 1009, 26: 1028, 27: 1010, 28: 1011, 29: 1012, 30: 1013, 114: 199, 142: 143, 600: 1017, + 601: 1018, 602: 1019, 603: 1020, 604: 1027, 628: 629, 650: 651, 700: 1021, 701: 1022, 718: 719, + 774: 775, 790: 791, 829: 1040, 869: 1041, 1033: 1034, 1042: 1014, 1043: 1015, 1082: 1182, + 1083: 1183, 1114: 1115, 1184: 1185, 1186: 1187, 1266: 1270, 1560: 1561, 1562: 1563, 1700: 1231, + 1790: 2201, 2202: 2207, 2203: 2208, 2204: 2209, 2205: 2210, 2206: 2211, 2249: 2287, 2275: 1263, + 2950: 2951, 2970: 2949, 3220: 3221, 3614: 3643, 3615: 3645, 3734: 3735, 3769: 3770, 3802: 3807, + 3904: 3905, 3906: 3907, 3908: 3909, 3910: 3911, 3912: 3913, 3926: 3927, 4072: 4073, 4089: 4090, + 4096: 4097, 5038: 5039, 5069: 271 +} + +export const types = { + string: { to: 25, from: null, serialize: string }, + number: { to: 0, from: [21, 23, 26, 700, 701], serialize: string, parse: number }, + json: { to: 114, from: [114, 3802], serialize: x => JSON.stringify(x), parse: json }, + boolean: { to: 16, from: [16], serialize: x => x === true ? 't' : 'f', parse: bool }, + date: { to: 1184, from: [1082, 1114, 1184], serialize: serializeDate, parse: null }, + bytea: { to: 17, from: [17], serialize: x => '\\x' + Buffer.from(x).toString('hex'), parse: x => Buffer.from(x.slice(2), 'hex') } +} + +const dates = { 1082: parseDate, 1114: parseTimestamp, 1184: parseTimestamptz } + +function integer(x, i, end) { + const negative = x[i] === 45 + let n = 0 + for (negative && i++; i < end; i++) + n = n * 10 + x[i] - 48 + return negative ? -n : n +} + +function boolean(x, i) { + return x[i] === 116 +} + +const shaped = (is, serialize) => x => is(x) ? serialize(x) : string(x) + +const shapedTypes = { + ...types, + boolean: { ...types.boolean, serialize: shaped(x => typeof x === 'boolean', types.boolean.serialize) }, + date: { ...types.date, serialize: shaped(x => x instanceof Date, types.date.serialize) }, + bytea: { ...types.bytea, serialize: shaped(x => x instanceof Uint8Array, types.bytea.serialize) } +} + +export function Types(options = {}) { + const parsers = {} + , serializers = {} + , elements = {} + , undefinedValue = options.transform && options.transform.undefined + + Object.entries(arrays).forEach(([oid, array]) => elements[array] = [+oid, +oid === 603 ? ';' : ',']) + register(options.infer === false ? shapedTypes : types) + Object.assign(parsers, dates) + options.infer === false && (parsers[1114] = parseDate) + const custom = Object.values(options.types || {}) + , named = custom.filter(x => [x.to].concat(x.from || []).some(y => typeof y === 'string')) + , oids = {} + + register(custom.filter(x => !named.includes(x))) + + const bases = {} + + return { parser, decoder, serializer, load, infer, resolve, named: named.length > 0, parsers, serializers } + + function resolve(type) { + return typeof type === 'string' ? oids[type] || 0 : type + } + + function decoder(oid, parse) { + return parse === number && (oid === 21 || oid === 23 || oid === 26) ? integer + : parse === bool && oid === 16 ? boolean + : null + } + + function register(xs) { + Object.values(xs).forEach(x => { + const from = [].concat(x.from || []) + x.parse && from.forEach(oid => parsers[oid] = x.parse) + if (x.serialize) { + serializers[x.to] = x.serialize + from.forEach(oid => serializers[oid] = x.serialize) + } + }) + } + + function parser(oid) { + if (oid in parsers) + return parsers[oid] + + if (oid in bases) + return parsers[oid] = parser(bases[oid]) + + if (oid in elements) { + const [element, delimiter] = elements[oid] + , parse = parser(element) + return parsers[oid] = x => parseArray(x, parse === identity ? null : parse, delimiter) + } + + return identity + } + + function serializer(oid) { + if (oid in serializers) + return serializers[oid] + + if (oid in bases) + return serializers[oid] = serializer(bases[oid]) + + if (oid in elements) { + const [element, delimiter] = elements[oid] + , serialize = serializer(element) + return serializers[oid] = xs => Array.isArray(xs) ? serializeArray(xs, serialize, delimiter, undefinedValue) : serialize(xs) + } + + return string + } + + function load(run) { + return Promise.all([fetched(run), named.length && names(run)]) + } + + async function names(run) { + const wanted = [...new Set(named.flatMap(x => [x.to].concat(x.from || [])).filter(x => typeof x === 'string'))] + , list = wanted.map(x => '\'' + x.split('.').pop().replace(/'/g, '\'\'') + '\'').join(',') + , rows = await run( + 'select t.oid::int, t.typarray::int as array, t.typdelim as delimiter, t.typname as name, n.nspname as schema, ' + + 'pg_catalog.pg_type_is_visible(t.oid) as visible from pg_catalog.pg_type t ' + + 'join pg_catalog.pg_namespace n on n.oid = t.typnamespace where t.typname in (' + list + ')' + ) + , missing = [] + wanted.forEach(x => { + const [schema, name] = x.includes('.') ? x.split('.') : [null, x] + , row = rows.find(r => r.name === name && (schema ? r.schema === schema : r.visible)) + row ? (oids[x] = row.oid, row.array && !(row.array in elements) && (elements[row.array] = [row.oid, row.delimiter])) : missing.push(x) + }) + if (missing.length) { + throw Errors.generic('TYPE_NOT_FOUND', missing.length > 1 + ? 'The types ' + missing.join(', ') + ' do not exist' + : 'The type ' + missing[0] + ' does not exist') + } + register(named.map(x => ({ ...x, to: resolve(x.to), from: [].concat(x.from || []).map(resolve) }))) + } + + function fetched(run) { + return run( + 'select oid::int, typelem::int as element, typdelim as delimiter, typbasetype::int as base, typtype as kind ' + + 'from pg_catalog.pg_type where typtype = \'d\' or (typcategory = \'A\' and oid >= 16384)' + ).then(rows => rows.forEach(({ oid, element, delimiter, base, kind }) => { + if (oid in parsers || oid in serializers) + return + kind === 'd' + ? bases[oid] = base + : element && !(oid in elements) && (elements[oid] = [element, delimiter]) + })) + } +} + +const identity = x => x +identity.identity = true + +export class Parameter { + constructor(value, type) { + this.value = value + this.type = type + } +} + +export function infer(x) { + return ( + x instanceof Parameter ? x.type : + x instanceof Date ? 1184 : + x instanceof Uint8Array ? 17 : + (x === true || x === false) ? 16 : + typeof x === 'bigint' ? 20 : + Array.isArray(x) ? arrays[infer(x[0])] || 0 : + 0 + ) +} + +export function parseArray(x, parse, delimiter = ',') { + let i = x[0] === '[' ? x.indexOf('=') + 1 : 0 + return level() + + function level() { + const xs = [] + i++ + while (i < x.length && x[i] !== '}') { + if (x[i] === '{') { + xs.push(level()) + } else if (x[i] === '"') { + let s = '' + for (i++; x[i] !== '"'; i++) + s += x[i] === '\\' ? x[++i] : x[i] + i++ + xs.push(parse ? parse(s) : s) + } else { + const start = i + while (x[i] !== delimiter && x[i] !== '}') + i++ + const s = x.slice(start, i) + xs.push(s === 'NULL' ? null : parse ? parse(s) : s) + } + x[i] === delimiter && i++ + } + i++ + return xs + } +} + +export function serializeArray(xs, serialize = string, delimiter = ',', undefinedValue) { + return '{' + xs.map(x => { + const typed = x instanceof Parameter + typed && (x = x.value) + x === undefined && (x = undefinedValue) + if (x === undefined) + throw Errors.generic('UNDEFINED_VALUE', 'Undefined values are not allowed') + return Array.isArray(x) && !typed + ? serializeArray(x, serialize, delimiter, undefinedValue) + : x === null + ? 'NULL' + : '"' + ('' + serialize(x)).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"' + }).join(delimiter) + '}' +} + +function serializeDate(x) { + return x === Infinity ? 'infinity' + : x === -Infinity ? '-infinity' + : (x instanceof Date ? x : new Date(x)).toISOString() +} + +const timestamp = /^(\d{4,})-(\d\d)-(\d\d)(?: (\d\d):(\d\d):(\d\d)(?:\.(\d+))?)?(?:([+-])(\d\d)(?::(\d\d))?(?::(\d\d))?)?( BC)?$/ + +function parts(x) { + const m = x.match(timestamp) + if (!m) + return null + + const year = m[12] ? 1 - m[1] : +m[1] + , ms = m[7] ? +(m[7] + '00').slice(0, 3) : 0 + , offset = m[8] ? (m[8] === '-' ? -1 : 1) * ((m[9] * 60 + +(m[10] || 0)) * 60 + +(m[11] || 0)) * 1000 : 0 + + return { year, month: m[2] - 1, day: +m[3], hour: +(m[4] || 0), minute: +(m[5] || 0), second: +(m[6] || 0), ms, offset } +} + +function infinite(x) { + return x === 'infinity' ? Infinity : x === '-infinity' ? -Infinity : null +} + +function utc(x) { + const date = new Date(Date.UTC(2000, x.month, x.day, x.hour, x.minute, x.second, x.ms)) + date.setUTCFullYear(x.year) + return date +} + +function plain(x) { + const n = x.length + return x.charCodeAt(0) !== 48 && x.charCodeAt(n - 1) !== 67 && !(x.charCodeAt(n - 3) === 58 && x.charCodeAt(n - 6) === 58) + && x.charCodeAt(0) !== 45 && x.charCodeAt(0) !== 105 +} + +function parseTimestamptz(x) { + if (plain(x)) + return new Date(x) + + const p = infinite(x) || parts(x) + if (!p) + return new Date(x) + + if (typeof p === 'number') + return p + + const date = utc(p) + date.setTime(date.getTime() - p.offset) + return date +} + +function parseDate(x) { + const p = infinite(x) || parts(x) + return !p ? new Date(x) : typeof p === 'number' ? p : utc(p) +} + +function parseTimestamp(x) { + const p = infinite(x) || parts(x) + if (!p || typeof p === 'number') + return p || new Date(x) + + const date = new Date(2000, p.month, p.day, p.hour, p.minute, p.second, p.ms) + date.setFullYear(p.year) + return date +} + +export const toCamel = x => { + let str = x[0] + for (let i = 1; i < x.length; i++) + str += x[i] === '_' ? x[++i].toUpperCase() : x[i] + return str +} + +export const toPascal = x => { + let str = x[0].toUpperCase() + for (let i = 1; i < x.length; i++) + str += x[i] === '_' ? x[++i].toUpperCase() : x[i] + return str +} + +export const toKebab = x => x.replace(/_/g, '-') + +export const fromCamel = x => x.replace(/([A-Z])/g, '_$1').toLowerCase() +export const fromPascal = x => (x.slice(0, 1) + x.slice(1).replace(/([A-Z])/g, '_$1')).toLowerCase() +export const fromKebab = x => x.replace(/-/g, '_') + +function createJsonTransform(fn) { + return function jsonTransform(x, column) { + return typeof x === 'object' && x !== null && (column.type === 114 || column.type === 3802) + ? Array.isArray(x) + ? x.map(x => jsonTransform(x, column)) + : Object.entries(x).reduce((acc, [k, v]) => Object.assign(acc, { [fn(k)]: jsonTransform(v, column) }), {}) + : x + } +} + +toCamel.column = { from: toCamel } +toCamel.value = { from: createJsonTransform(toCamel) } +fromCamel.column = { to: fromCamel } + +export const camel = { ...toCamel } +camel.column.to = fromCamel + +toPascal.column = { from: toPascal } +toPascal.value = { from: createJsonTransform(toPascal) } +fromPascal.column = { to: fromPascal } + +export const pascal = { ...toPascal } +pascal.column.to = fromPascal + +toKebab.column = { from: toKebab } +toKebab.value = { from: createJsonTransform(toKebab) } +fromKebab.column = { to: fromKebab } + +export const kebab = { ...toKebab } +kebab.column.to = fromKebab diff --git a/node_modules/postgres/types/index.d.ts b/node_modules/postgres/types/index.d.ts new file mode 100644 index 0000000..959b4f1 --- /dev/null +++ b/node_modules/postgres/types/index.d.ts @@ -0,0 +1,908 @@ +import type { Readable, Writable } from 'node:stream' +import type { ConnectionOptions as TlsOptions } from 'node:tls' + +type ParsedTypes> = + Record extends T + ? {} + : { [K in keyof T]: T[K] extends postgres.PostgresType ? R : never } + +declare function postgres = {}>( + options?: postgres.Options +): postgres.Sql> +declare function postgres = {}>( + url: string, + options?: postgres.Options +): postgres.Sql> + +declare const PRIVATE: unique symbol + +declare class NotAPromise { + private [PRIVATE]: never + /** @deprecated Not a query, and so not a promise: use the tagged template, ```await sql`...` ``` */ + private then(): never + /** @deprecated Not a query, and so not a promise: use the tagged template, ```await sql`...` ``` */ + private catch(): never + /** @deprecated Not a query, and so not a promise: use the tagged template, ```await sql`...` ``` */ + private finally(): never +} + +type UnwrapPromiseArray = T extends readonly any[] + ? { -readonly [K in keyof T]: Awaited } + : T + +type Keys = string + +type SerializableObject = + number extends K['length'] + ? {} + : Partial< + Record | undefined> + & Record + > + +type First = + T extends TemplateStringsArray ? TemplateStringsArray : + T extends string ? string : + T extends readonly any[][] ? readonly postgres.EscapableArray[] : + T extends readonly (object & infer R)[] + ? R extends postgres.SerializableParameter + ? readonly postgres.SerializableParameter[] + : readonly SerializableObject[] + : T extends readonly any[] ? readonly postgres.SerializableParameter[] : + T extends object ? SerializableObject : + never + +type Rest = + T extends TemplateStringsArray ? never : + T extends string ? readonly string[] : + T extends readonly any[][] ? readonly [] : + T extends readonly (object & infer R)[] + ? readonly (Keys & keyof R)[] | [readonly (Keys & keyof R)[]] | [readonly string[]] + : T extends readonly any[] ? readonly [] : + T extends object ? readonly (Keys & keyof T)[] | [readonly (Keys & keyof T)[]] | [readonly string[]] : + any + +type Return = + [T] extends [TemplateStringsArray] + ? [unknown] extends [T] + ? postgres.Helper + : [TemplateStringsArray] extends [T] ? postgres.PendingQuery : postgres.Helper + : postgres.Helper + +declare namespace postgres { + /** An error the server sent */ + class PostgresError extends globalThis.Error { + constructor(message?: string | Partial) + name: 'PostgresError' + severity_local: string + severity: string + code: string + position: string + file: string + line: string + routine: string + + detail?: string | undefined + hint?: string | undefined + internal_position?: string | undefined + internal_query?: string | undefined + where?: string | undefined + schema_name?: string | undefined + table_name?: string | undefined + column_name?: string | undefined + data?: string | undefined + data_type_name?: string | undefined + constraint_name?: string | undefined + + /** The text of the query, when the query is known */ + query: string + /** The parameters of the query; only with `debug` */ + parameters: any[] + /** The types of the parameters; only with `debug` */ + types?: number[] | undefined + } + + /** snake_case to PascalCase */ + function toPascal(str: string): string + namespace toPascal { + namespace column { function from(str: string): string } + namespace value { function from(str: unknown, column: Column): string } + } + /** PascalCase to snake_case */ + function fromPascal(str: string): string + namespace fromPascal { + namespace column { function to(str: string): string } + } + /** snake_case to and from PascalCase, as a transform */ + namespace pascal { + namespace column { + function from(str: string): string + function to(str: string): string + } + namespace value { function from(str: unknown, column: Column): string } + } + /** snake_case to camelCase */ + function toCamel(str: string): string + namespace toCamel { + namespace column { function from(str: string): string } + namespace value { function from(str: unknown, column: Column): string } + } + /** camelCase to snake_case */ + function fromCamel(str: string): string + namespace fromCamel { + namespace column { function to(str: string): string } + } + /** snake_case to and from camelCase, as a transform */ + namespace camel { + namespace column { + function from(str: string): string + function to(str: string): string + } + namespace value { function from(str: unknown, column: Column): string } + } + /** snake_case to kebab-case */ + function toKebab(str: string): string + namespace toKebab { + namespace column { function from(str: string): string } + namespace value { function from(str: unknown, column: Column): string } + } + /** kebab-case to snake_case */ + function fromKebab(str: string): string + namespace fromKebab { + namespace column { function to(str: string): string } + } + /** snake_case to and from kebab-case, as a transform */ + namespace kebab { + namespace column { + function from(str: string): string + function to(str: string): string + } + namespace value { function from(str: unknown, column: Column): string } + } + + /** int8 as bigint: `types: { bigint: postgres.BigInt }` */ + const BigInt: PostgresType + + interface PostgresType { + /** The oid values of this type are sent as, or the type's name, looked up when the pool starts */ + to: number | string + /** The oids or type names parsed with `parse` */ + from: (number | string)[] + serialize: (value: T) => unknown + parse: (raw: any) => T + } + + interface ConnectionParameters { + /** @default 'postgres.js' */ + application_name: string + default_transaction_isolation: 'read uncommitted' | 'read committed' | 'repeatable read' | 'serializable' + default_transaction_read_only: boolean + default_transaction_deferrable: boolean + statement_timeout: number + lock_timeout: number + idle_in_transaction_session_timeout: number + idle_session_timeout: number + DateStyle: string + IntervalStyle: string + TimeZone: string + [name: string]: string | number | boolean + } + + type SSL = boolean | 'require' | 'allow' | 'prefer' | 'verify-full' | 'disable' | TlsOptions + + /** A socket of your own: anything with the events and methods of a net.Socket that are used */ + interface SocketLike { + write(data: Uint8Array): boolean + end(data?: Uint8Array): unknown + destroy(error?: Error): unknown + pause(): unknown + resume(): unknown + on(event: 'data', fn: (data: Uint8Array) => void): unknown + on(event: 'drain' | 'close', fn: () => void): unknown + on(event: 'error', fn: (error: Error) => void): unknown + off(event: string, fn: (...args: any[]) => void): unknown + setKeepAlive?(enable: boolean, delay: number): unknown + /** Set when the socket did the TLS negotiation itself, so it is not done again */ + negotiated?: boolean + secure?: boolean + } + + interface Options = {}> { + /** Host or hosts, with `host:port` allowed; tried in order @default process.env.PGHOST || 'localhost' */ + host?: string | string[] | undefined + /** An alias for `host` */ + hostname?: string | string[] | undefined + /** @default process.env.PGPORT || 5432 */ + port?: number | number[] | undefined + /** A unix socket directory, like '/tmp' */ + path?: string | undefined + /** @default process.env.PGDATABASE || user */ + database?: string | undefined + /** An alias for `database` */ + db?: string | undefined + /** A string, or a function giving one each time a connection opens @default process.env.PGUSERNAME || process.env.PGUSER || os.userInfo().username */ + user?: string | (() => string | Promise) | undefined + /** An alias for `user` */ + username?: string | (() => string | Promise) | undefined + /** A string, or a function giving one each time a connection opens @default process.env.PGPASSWORD, then PGPASSFILE or ~/.pgpass */ + password?: string | (() => string | Promise) | undefined + /** An alias for `password` */ + pass?: string | (() => string | Promise) | undefined + + /** + * TLS: false, a mode as in libpq's sslmode, or options for tls.connect. + * 'require', 'allow' and 'prefer' do not verify the certificate; Cloudflare Workers always do. + * @default false + */ + ssl?: SSL | undefined + /** + * 'direct' starts TLS on the first byte instead of asking first (PostgreSQL 17 and later). + * On Node it is also the fastest TLS, as it reads into the shared buffer. + * @default 'postgres' + */ + sslnegotiation?: 'postgres' | 'direct' | null | undefined + + /** + * SCRAM-SHA-256-PLUS over TLS, binding the login to the server certificate, as libpq's channel_binding. + * 'require' rejects a connection that can not be bound with CHANNEL_BINDING_REQUIRED. + * @default 'prefer' + */ + channel_binding?: 'disable' | 'prefer' | 'require' | undefined + + /** Most connections at a time @default 10 */ + max?: number | undefined + /** Connections kept open once the pool is used, even when idle @default 0 */ + min?: number | undefined + /** Most queries pipelined on one connection @default 100 */ + max_pipeline?: number | undefined + /** + * Pipeline a query on the busy connection where it should be done soonest, keeping slow queries together + * so quick ones don't wait behind them; false pipelines on the connection with fewest queries in flight + * @default true + */ + scheduler?: boolean | undefined + /** Seconds before an idle connection closes; 0, null or false to keep it @default null */ + idle_timeout?: number | null | false | undefined + /** Seconds a query, transaction or reserve may wait for a connection before QUEUE_TIMEOUT; 0 to wait as long as it takes @default 0 */ + queue_timeout?: number | undefined + /** Seconds to connect before CONNECT_TIMEOUT; 0, null or false to wait as long as it takes @default 30 */ + connect_timeout?: number | null | false | undefined + /** Seconds a connection lives at most; a function gives a number per connection; 0, null or false for no limit @default 30 to 60 minutes */ + max_lifetime?: number | null | false | (() => number) | undefined + /** Seconds before reconnecting after a failure; a function of the number of attempts @default exponential */ + backoff?: boolean | number | ((attempts: number) => number) | undefined + /** Seconds of TCP keep-alive; 0 or null for none @default 60 */ + keep_alive?: number | null | false | undefined + + /** Named prepared statements @default true */ + prepare?: boolean | undefined + /** + * false leaves every parameter to the server, as libpq does, and writes each value for the type it + * asks for. true types parameters from their values as v3 did: a Date as timestamptz, a Uint8Array as + * bytea, a boolean, a bigint as int8 and an array by its first element. + * @default false + */ + infer?: boolean | undefined + /** Fetches array types and the types of columns it does not know @default true */ + fetch_types?: boolean | undefined + /** Custom types; see the README */ + types?: T | undefined + + /** Called with each notice; false to drop them @default console.log */ + onnotice?: false | ((notice: Notice) => void) | undefined + /** Called with each notification, whether listened to or not */ + onnotify?: ((channel: string, payload: string, pid: number) => void) | undefined + /** Called when a server parameter changes */ + onparameter?: ((key: string, value: string) => void) | undefined + /** Called with the id of each connection that closes */ + onclose?: ((connection: number) => void) | undefined + /** true, or a function called with every query */ + debug?: boolean | ((connection: number, query: string, parameters: any[], types: number[]) => void) | undefined + + /** Transforms of column names, values and rows */ + transform?: TransformOptions | undefined + /** Run-time parameters sent at startup */ + connection?: Partial | undefined + /** For several hosts: which kind of server to settle on @default process.env.PGTARGETSESSIONATTRS */ + target_session_attrs?: 'read-write' | 'read-only' | 'primary' | 'standby' | 'prefer-standby' | null | undefined + + /** Publications for `sql.subscribe` @default 'alltables' */ + publications?: string | undefined + /** + * A permanent replication slot for `sql.subscribe`, created if it does not exist. Streaming starts + * where the slot was last confirmed, and a transaction is confirmed once its handlers finish. + * Without one, subscribe uses a temporary slot. + */ + slot?: string | null | undefined + + /** A socket of your own for each connection */ + socket?: ((options: ParsedOptions, host: string, port: number) => SocketLike | Promise) | undefined + /** Reads plain and direct TLS connections into one shared buffer per connection (Node, Bun and Deno) @default true */ + onread?: boolean | undefined + /** Idle connections do not keep the process alive, so it can exit without sql.end() @default false */ + unref_sockets?: boolean | undefined + + /** @deprecated use `prepare: false` */ + no_prepare?: boolean | undefined + /** @deprecated use `idle_timeout` */ + timeout?: number | undefined + } + + interface TransformOptions { + /** What undefined is sent as, instead of failing with UNDEFINED_VALUE */ + undefined?: any + column?: ((column: string) => string) | { + /** Column names in results */ + from?: ((column: string) => string) | undefined + /** Column names given to helpers */ + to?: ((column: string) => string) | undefined + } | undefined + value?: ((value: any) => any) | { + /** Values in results */ + from?: ((value: unknown, column: Column) => any) | undefined + } | undefined + row?: ((row: Row) => any) | { + /** Whole rows in results */ + from?: ((row: Row) => any) | undefined + } | undefined + } + + interface Transform { + undefined: any + column: { + from: ((column: string) => string) | undefined + to: ((column: string) => string) | undefined + } + value: { + from: ((value: any, column?: Column) => any) | undefined + to: undefined + } + row: { + from: ((row: Row) => any) | undefined + to: undefined + } + } + + interface ParsedOptions = {}> { + host: string[] + port: number[] + path: string | false + database: string | null + user: string | (() => string | Promise) + pass: string | (() => string | Promise) + ssl: SSL + sslnegotiation: 'postgres' | 'direct' | null + channel_binding: 'disable' | 'prefer' | 'require' + max: number + min: number + max_pipeline: number + scheduler: boolean + idle_timeout: number | null + connect_timeout: number + queue_timeout: number + max_lifetime: number | null | (() => number) + backoff: boolean | number | ((attempts: number) => number) + keep_alive: number | null + prepare: boolean + infer: boolean + fetch_types: boolean + debug: Options['debug'] + publications: string + slot: string | null + onread: boolean + unref_sockets: boolean + target_session_attrs: Options['target_session_attrs'] + connection: Partial + types: { [K in keyof T]: PostgresType } + transform: Transform + parameters: Record + serializers: Record unknown> + parsers: Record unknown> + } + + interface Notice { + [field: string]: string + } + + interface Parameter extends NotAPromise { + /** The oid of the type */ + type: number + /** The value as sent */ + value: string | null + /** The value as given */ + raw: T | null + } + + interface ConnectionError extends globalThis.Error { + code: + | 'CONNECTION_DESTROYED' + | 'CONNECT_TIMEOUT' + | 'CONNECTION_CLOSED' + | 'CONNECTION_ENDED' + errno: this['code'] + address: string + port?: number | undefined + } + + interface NotSupportedError extends globalThis.Error { + code: 'MESSAGE_NOT_SUPPORTED' + name: string + } + + interface GenericError extends globalThis.Error { + code: + | '57014' + | 'NOT_TAGGED_CALL' + | 'UNDEFINED_VALUE' + | 'MAX_PARAMETERS_EXCEEDED' + | 'ARRAY_REMOVED' + | 'COPY_IN_PROGRESS' + | 'UNSAFE_TRANSACTION' + | 'TRANSACTION_ROLLED_BACK' + | 'SSL_NOT_SUPPORTED' + | 'CHANNEL_BINDING_REQUIRED' + | 'PROTOCOL_ERROR' + | 'NUL_CHARACTER' + | 'SSL_NEGOTIATION_NOT_SUPPORTED' + | 'SASL_MECHANISM_NOT_SUPPORTED' + | 'SASL_NONCE_MISMATCH' + | 'SASL_SIGNATURE_MISMATCH' + | 'TLS_HANDSHAKE_FAILED' + | 'NO_COLUMNS' + | 'QUEUE_TIMEOUT' + | 'TYPE_NOT_FOUND' + | 'NESTED_TRANSACTION_MODE' + message: string + } + + interface AuthNotImplementedError extends globalThis.Error { + code: 'AUTH_TYPE_NOT_IMPLEMENTED' + message: string + } + + type Error = + | PostgresError + | ConnectionError + | NotSupportedError + | GenericError + | AuthNotImplementedError + + interface ColumnInfo { + key: number + name: string + type: number + parser?(raw: string): unknown + atttypmod: number + } + + interface RelationInfo { + schema: string + table: string + columns: ColumnInfo[] + keys: ColumnInfo[] + } + + interface TransactionInfo { + /** The LSN of the transaction, like '0/1A2B3C4' */ + lsn: string | undefined + /** When it committed */ + time: Date | undefined + xid: number | undefined + } + + type ReplicationEvent = TransactionInfo & ( + | { command: 'insert', relation: RelationInfo } + | { command: 'update', relation: RelationInfo, key: boolean, old: Row | null } + | { command: 'delete', relation: RelationInfo, key: boolean } + | { command: 'truncate', relation: RelationInfo, cascade: boolean, restartIdentity: boolean } + ) + + interface SubscriptionHandle { + unsubscribe(): void + state: { pid: number | undefined, secret: number | undefined } + sql: Sql + } + + interface LargeObject { + writable(options?: { + highWaterMark?: number | undefined + start?: number | undefined + }): Promise + readable(options?: { + highWaterMark?: number | undefined + start?: number | undefined + end?: number | undefined + }): Promise + + close(): Promise + tell(): Promise + read(size: number): Promise + write(buffer: Uint8Array): Promise<[{ data: Uint8Array }]> + truncate(size: number): Promise + seek(offset: number, whence?: number): Promise + size(): Promise<[{ position: bigint, size: bigint }]> + } + + type EscapableArray = readonly (Serializable | Helper | Parameter | readonly SerializableParameter[])[] + + type Serializable = + | null + | boolean + | number + | bigint + | string + | Date + | Uint8Array + + type SerializableParameter = + | T + | Serializable + | Helper + | Parameter + | readonly SerializableParameter[] + + type JSONValue = + | null + | string + | number + | boolean + | Date + | readonly JSONValue[] + | { toJSON(): any } + | { readonly [prop: string | number]: undefined | JSONValue | ((...args: any) => any) } + | object + + interface Row { + [column: string]: any + } + + type MaybeRow = Row | undefined + + interface Column { + name: T + type: number + table: number + number: number + parser?: ((raw: string) => unknown) | undefined + } + + type ColumnList = (T extends string ? Column : never)[] + + interface State { + status: string + pid: number + secret: number + } + + interface Statement { + /** The name it is prepared as, '' when unnamed */ + name: string + /** The text sent */ + string: string + /** The types of its parameters */ + types: number[] + columns: ColumnList + } + + interface ResultMeta { + count: T + command: string + statement: Statement + state: State + } + + interface ResultQueryMeta extends ResultMeta { + columns: ColumnList + } + + type ExecutionResult = [] & ResultQueryMeta> + type ValuesRowList = + T[number][keyof T[number]][][] & ResultQueryMeta + type RawRowList = + Buffer[][] & Iterable & ResultQueryMeta + type RowList = + T & Iterable> & ResultQueryMeta + + interface PendingQueryModifiers { + /** Sends it with the simple protocol, which allows several statements */ + simple(): this + /** For `copy ... to stdout` */ + readable(): Promise + /** For `copy ... from stdin` */ + writable(): Promise + + /** Sends it now instead of when awaited */ + execute(): this + /** Cancels it, sent or not */ + cancel(): Promise + /** Cancels it when the signal aborts: `.signal(AbortSignal.timeout(5000))` */ + signal(signal: AbortSignal | null | undefined): this + + /** @deprecated renamed to `.forEach` */ + stream(cb: (row: NonNullable, result: ExecutionResult) => void): never + /** Calls back with each row as it arrives, instead of collecting them */ + forEach(cb: (row: NonNullable, result: ExecutionResult) => void): Promise> + + /** Rows in batches: `for await (const rows of sql`...`.cursor(10))` */ + cursor(rows?: number): AsyncIterable[]> + /** One row at a time; return a promise to wait, or `sql.CLOSE` to stop */ + cursor(cb: (row: [NonNullable]) => unknown): Promise> + /** Batches of rows; return a promise to wait, or `sql.CLOSE` to stop */ + cursor(rows: number, cb: (rows: NonNullable[]) => unknown): Promise> + } + + interface PendingDescribeQuery extends Promise {} + + interface PendingValuesQuery + extends Promise>, PendingQueryModifiers { + describe(): PendingDescribeQuery + } + + interface PendingRawQuery + extends Promise>, PendingQueryModifiers {} + + interface PendingQuery + extends Promise>, PendingQueryModifiers { + /** Parses and describes it without running it */ + describe(): PendingDescribeQuery + /** Rows as arrays of values */ + values(): PendingValuesQuery + /** Rows as arrays of the raw bytes */ + raw(): PendingRawQuery + /** As a separator: ``sql` and `.join(fragments)``; falsy items are left out, and spaces are added where missing */ + join(items: readonly (ParameterOrFragment | false | null | undefined)[]): PendingQuery & { readonly length: number } + /** The text it will be sent as */ + readonly text: string + /** The values it will be sent with */ + readonly parameters: any[] + } + + interface PendingRequest extends Promise<[] & ResultMeta> {} + + interface ListenRequest extends Promise {} + interface ListenMeta { + state: State + unlisten(): Promise + } + + interface Helper extends NotAPromise { + first: T + rest: U + } + + type Fragment = PendingQuery + + type ParameterOrJSON = + | SerializableParameter + | JSONValue + + type ParameterOrFragment = + | SerializableParameter + | Fragment + | Fragment[] + + interface UnsafeQueryOptions { + /** As a named prepared statement @default false */ + prepare?: boolean | undefined + /** With the simple protocol @default true without parameters */ + simple?: boolean | undefined + } + + /** The context of the `postgres:query` tracing channel */ + interface QueryTrace { + /** The text sent, with $1, $2 for the parameters */ + query: string | null + /** The values; only with `debug` */ + parameters: any[] | undefined + /** The name it is prepared as, '' if unnamed; null until sent */ + statement: string | null + database: string + user: string + connection: number | null + host: string | null + port: number | null + command: string | null + count: number | null + /** Times from performance.now() */ + queued: number + sent: number | null + firstByte: number | null + complete: number | null + result?: unknown + error?: Error | globalThis.Error + } + + /** The context of the `postgres:connect` tracing channel */ + interface ConnectTrace { + host: string | null + port: number | null + path: string | null + database: string + user: string + ssl: boolean + sslnegotiation: 'postgres' | 'direct' + result?: { pid: number, status: string, readOnly: boolean, standby: boolean } + error?: Error | globalThis.Error + } + + /** The context of the `postgres:transaction` tracing channel */ + interface TransactionTrace { + mode: string + database: string + user: string + connection: number | null + host: string | null + port: number | null + outcome: 'commit' | 'rollback' | 'prepare' | null + result?: unknown + error?: Error | globalThis.Error + } + + /** A message on the `postgres:pool` channel */ + interface PoolEvent { + event: 'open' | 'idle' | 'wait' | 'lease' | 'release' | 'close' + connection: number | null + host: string | null + port: number | null + database: string + stats: PoolStats + kind?: string + waited?: number + waiting?: number + error?: Error | globalThis.Error + } + + /** A message on the `postgres:notice` channel */ + interface NoticeEvent { + notice: Notice + connection: number + host: string + port: number + database: string + } + + interface PoolStats { + connections: number + opening: number + idle: number + leased: number + waiting: number + } + + interface ISql = {}> { + /** + * A helper: an identifier, a list of values, or the columns and values of objects + * @example sql`insert into users ${ sql(user, 'name', 'age') }` + */ + >(first: T & First, ...rest: K): Return + + /** + * A query + * @example const users = await sql`select * from users where id = ${ id }` + */ + ( + template: TemplateStringsArray, + ...parameters: readonly ParameterOrFragment[] + ): PendingQuery + + types: this['typed'] + /** A value with the oid to send it as, or one of the custom types by name */ + typed: ((value: T, oid: number) => Parameter) & { + [name in keyof TTypes]: (value: TTypes[name]) => Parameter + } + + /** A query from a string: never with values from users in the string itself */ + unsafe)[]>( + query: string, + parameters?: ParameterOrJSON[], + options?: UnsafeQueryOptions + ): PendingQuery + unsafe)[]>(query: string, options: UnsafeQueryOptions): PendingQuery + + notify(channel: string, payload: string): PendingRequest + + /** @deprecated removed in v4: pass the array as it is, and cast it if needed (`${ xs }::int[]`) */ + array(value: any, type?: number): never + + /** A query from a file */ + file(path: string | Buffer | URL | number, options?: { cache?: boolean | undefined }): PendingQuery + file( + path: string | Buffer | URL | number, + args: ParameterOrJSON[], + options?: { cache?: boolean | undefined } + ): PendingQuery + + /** A value sent as json */ + json(value: JSONValue): Parameter + } + + interface Sql = {}> extends ISql { + /** Return from a cursor callback to stop it */ + CLOSE: {} + END: this['CLOSE'] + PostgresError: typeof PostgresError + + options: ParsedOptions + /** The server's parameters, as last reported */ + parameters: ConnectionParameters + /** What the pool is doing right now */ + readonly stats: PoolStats + + /** Waits for queries to finish, then closes every connection; queries after it reject */ + end(options?: { timeout?: number | undefined }): Promise + /** Closes every connection once its queries finish; the pool stays usable */ + close(): Promise + + listen(channel: string, onnotify: (value: string) => void, onlisten?: () => void): ListenRequest + + /** + * Logical replication. A handler may return a promise: handlers run one after the other, in + * commit order, and with a `slot` a transaction is confirmed only once they all finish. + * @param event 'insert', 'update', 'delete', 'truncate' or '*', then optionally ':table' and '=key' + */ + subscribe( + event: string, + cb: (row: Row | null, info: ReplicationEvent, event: string) => unknown, + onsubscribe?: () => void, + onerror?: (error: globalThis.Error) => void + ): Promise + + largeObject(oid?: number, /** @default 0x00020000 | 0x00040000 */ mode?: number): Promise + + begin(cb: (sql: TransactionSql) => T | Promise): Promise> + begin(options: string, cb: (sql: TransactionSql) => T | Promise): Promise> + + /** A connection of your own until `release()` */ + reserve(): Promise> + + /** `await using sql = postgres()` ends the pool when it goes out of scope */ + [Symbol.asyncDispose](): Promise + } + + interface TransactionSql = {}> extends ISql { + /** A savepoint; a mode other than the transaction's throws NESTED_TRANSACTION_MODE */ + begin(cb: (sql: TransactionSql) => T | Promise): Promise> + begin(options: string, cb: (sql: TransactionSql) => T | Promise): Promise> + savepoint(cb: (sql: TransactionSql) => T | Promise): Promise> + savepoint(name: string, cb: (sql: TransactionSql) => T | Promise): Promise> + + /** Ends with PREPARE TRANSACTION name instead of COMMIT */ + prepare(name: string): string + /** Rolls back the transaction, or the savepoint it is called in, at once; later queries are not sent and reject with TRANSACTION_ROLLED_BACK */ + rollback(): Promise + } + + interface ReservedSql = {}> extends ISql { + release(): void + /** `using reserved = await sql.reserve()` releases it when it goes out of scope */ + [Symbol.dispose](): void + [Symbol.asyncDispose](): Promise + } +} + +export default postgres + +export type Sql = {}> = postgres.Sql +export type TransactionSql = {}> = postgres.TransactionSql +export type ReservedSql = {}> = postgres.ReservedSql +export type Options = {}> = postgres.Options +export type ParsedOptions = {}> = postgres.ParsedOptions +export type PendingQuery = postgres.PendingQuery +export type RowList = postgres.RowList +export type Row = postgres.Row +export type Fragment = postgres.Fragment +export type Helper = postgres.Helper +export type Parameter = postgres.Parameter +export type PostgresType = postgres.PostgresType +export type ReplicationEvent = postgres.ReplicationEvent +export type Notice = postgres.Notice +export declare const PostgresError: typeof postgres.PostgresError +export type PostgresError = postgres.PostgresError +/** What Sql, TransactionSql and ReservedSql have in common: take this to accept any of them */ +export type ISql = {}> = postgres.ISql +export type Error = postgres.Error +export type QueryTrace = postgres.QueryTrace +export type ConnectTrace = postgres.ConnectTrace +export type TransactionTrace = postgres.TransactionTrace +export type PoolEvent = postgres.PoolEvent +export type NoticeEvent = postgres.NoticeEvent diff --git a/node_modules/qrcode/README.md b/node_modules/qrcode/README.md new file mode 100644 index 0000000..510e6b9 --- /dev/null +++ b/node_modules/qrcode/README.md @@ -0,0 +1,770 @@ +# node-qrcode +> QR code/2d barcode generator. + +[![Travis](https://img.shields.io/travis/soldair/node-qrcode.svg?style=flat-square)](http://travis-ci.org/soldair/node-qrcode) +[![npm](https://img.shields.io/npm/v/qrcode.svg?style=flat-square)](https://www.npmjs.com/package/qrcode) +[![npm](https://img.shields.io/npm/dt/qrcode.svg?style=flat-square)](https://www.npmjs.com/package/qrcode) +[![npm](https://img.shields.io/npm/l/qrcode.svg?style=flat-square)](https://github.com/soldair/node-qrcode/blob/master/license) + +- [Highlights](#highlights) +- [Installation](#installation) +- [Usage](#usage) +- [Error correction level](#error-correction-level) +- [QR Code capacity](#qr-code-capacity) +- [Encoding Modes](#encoding-modes) +- [Binary data](#binary-data) +- [Multibyte characters](#multibyte-characters) +- [API](#api) +- [GS1 QR Codes](#gs1-qr-codes) +- [Credits](#credits) +- [License](#license) + +## Highlights +- Works on server and client (and react native with svg) +- CLI utility +- Save QR code as image +- Support for Numeric, Alphanumeric, Kanji and Byte mode +- Support for mixed modes +- Support for chinese, cyrillic, greek and japanese characters +- Support for multibyte characters (like emojis :smile:) +- Auto generates optimized segments for best data compression and smallest QR Code size +- App agnostic readability, QR Codes by definition are app agnostic + +## Installation +Inside your project folder do: + +```shell +npm install --save qrcode +``` + +or, install it globally to use `qrcode` from the command line to save qrcode images or generate ones you can view in your terminal. + +```shell +npm install -g qrcode +``` + +## Usage +### CLI + +``` +Usage: qrcode [options] + +QR Code options: + -v, --qversion QR Code symbol version (1 - 40) [number] + -e, --error Error correction level [choices: "L", "M", "Q", "H"] + -m, --mask Mask pattern (0 - 7) [number] + +Renderer options: + -t, --type Output type [choices: "png", "svg", "utf8"] + -w, --width Image width (px) [number] + -s, --scale Scale factor [number] + -q, --qzone Quiet zone size [number] + -l, --lightcolor Light RGBA hex color + -d, --darkcolor Dark RGBA hex color + --small Output smaller QR code to terminal [boolean] + +Options: + -o, --output Output file + -h, --help Show help [boolean] + --version Show version number [boolean] + +Examples: + qrcode "some text" Draw in terminal window + qrcode -o out.png "some text" Save as png image + qrcode -d F00 -o out.png "some text" Use red as foreground color +``` +If not specified, output type is guessed from file extension.
+Recognized extensions are `png`, `svg` and `txt`. + +### Browser +`node-qrcode` can be used in browser through module bundlers like [Browserify](https://github.com/substack/node-browserify) and [Webpack](https://github.com/webpack/webpack) or by including the precompiled bundle present in `build/` folder. + +#### Module bundlers +```html + + + + + + + +``` + +```javascript +// index.js -> bundle.js +var QRCode = require('qrcode') +var canvas = document.getElementById('canvas') + +QRCode.toCanvas(canvas, 'sample text', function (error) { + if (error) console.error(error) + console.log('success!'); +}) +``` + +#### Precompiled bundle +```html + + + + +``` + +If you install through `npm`, precompiled files will be available in `node_modules/qrcode/build/` folder. + +The precompiled bundle have support for [Internet Explorer 10+, Safari 5.1+, and all evergreen browsers](https://browserl.ist/?q=defaults%2C+IE+%3E%3D+10%2C+Safari+%3E%3D+5.1). + +### NodeJS +Require the module `qrcode` + +```javascript +var QRCode = require('qrcode') + +QRCode.toDataURL('I am a pony!', function (err, url) { + console.log(url) +}) +``` + +render a qrcode for the terminal +```js +var QRCode = require('qrcode') + +QRCode.toString('I am a pony!',{type:'terminal'}, function (err, url) { + console.log(url) +}) +``` + +### ES6/ES7 +Promises and Async/Await can be used in place of callback function. + +```javascript +import QRCode from 'qrcode' + +// With promises +QRCode.toDataURL('I am a pony!') + .then(url => { + console.log(url) + }) + .catch(err => { + console.error(err) + }) + +// With async/await +const generateQR = async text => { + try { + console.log(await QRCode.toDataURL(text)) + } catch (err) { + console.error(err) + } +} +``` + +## Error correction level +Error correction capability allows to successfully scan a QR Code even if the symbol is dirty or damaged. +Four levels are available to choose according to the operating environment. + +Higher levels offer a better error resistance but reduce the symbol's capacity.
+If the chances that the QR Code symbol may be corrupted are low (for example if it is showed through a monitor) +is possible to safely use a low error level such as `Low` or `Medium`. + +Possible levels are shown below: + +| Level | Error resistance | +|------------------|:----------------:| +| **L** (Low) | **~7%** | +| **M** (Medium) | **~15%** | +| **Q** (Quartile) | **~25%** | +| **H** (High) | **~30%** | + +The percentage indicates the maximum amount of damaged surface after which the symbol becomes unreadable. + +Error level can be set through `options.errorCorrectionLevel` property.
+If not specified, the default value is `M`. + +```javascript +QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, function (err, url) { + console.log(url) +}) +``` + +## QR Code capacity +Capacity depends on symbol version and error correction level. Also encoding modes may influence the amount of storable data. + +The QR Code versions range from version **1** to version **40**.
+Each version has a different number of modules (black and white dots), which define the symbol's size. +For version 1 they are `21x21`, for version 2 `25x25` e so on. +Higher is the version, more are the storable data, and of course bigger will be the QR Code symbol. + +The table below shows the maximum number of storable characters in each encoding mode and for each error correction level. + +| Mode | L | M | Q | H | +|--------------|------|------|------|------| +| Numeric | 7089 | 5596 | 3993 | 3057 | +| Alphanumeric | 4296 | 3391 | 2420 | 1852 | +| Byte | 2953 | 2331 | 1663 | 1273 | +| Kanji | 1817 | 1435 | 1024 | 784 | + +**Note:** Maximum characters number can be different when using [Mixed modes](#mixed-modes). + +QR Code version can be set through `options.version` property.
+If no version is specified, the more suitable value will be used. Unless a specific version is required, this option is not needed. + +```javascript +QRCode.toDataURL('some text', { version: 2 }, function (err, url) { + console.log(url) +}) +``` + +## Encoding modes +Modes can be used to encode a string in a more efficient way.
+A mode may be more suitable than others depending on the string content. +A list of supported modes are shown in the table below: + +| Mode | Characters | Compression | +|--------------|-----------------------------------------------------------|-------------------------------------------| +| Numeric | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 | 3 characters are represented by 10 bits | +| Alphanumeric | 0–9, A–Z (upper-case only), space, $, %, *, +, -, ., /, : | 2 characters are represented by 11 bits | +| Kanji | Characters from the Shift JIS system based on JIS X 0208 | 2 kanji are represented by 13 bits | +| Byte | Characters from the ISO/IEC 8859-1 character set | Each characters are represented by 8 bits | + +Choose the right mode may be tricky if the input text is unknown.
+In these cases **Byte** mode is the best choice since all characters can be encoded with it. (See [Multibyte characters](#multibyte-characters))
+However, if the QR Code reader supports mixed modes, using [Auto mode](#auto-mode) may produce better results. + +### Mixed modes +Mixed modes are also possible. A QR code can be generated from a series of segments having different encoding modes to optimize the data compression.
+However, switching from a mode to another has a cost which may lead to a worst result if it's not taken into account. +See [Manual mode](#manual-mode) for an example of how to specify segments with different encoding modes. + +### Auto mode +By **default**, automatic mode selection is used.
+The input string is automatically splitted in various segments optimized to produce the shortest possible bitstream using mixed modes.
+This is the preferred way to generate the QR Code. + +For example, the string **ABCDE12345678?A1A** will be splitted in 3 segments with the following modes: + +| Segment | Mode | +|----------|--------------| +| ABCDE | Alphanumeric | +| 12345678 | Numeric | +| ?A1A | Byte | + +Any other combinations of segments and modes will result in a longer bitstream.
+If you need to keep the QR Code size small, this mode will produce the best results. + +### Manual mode +If auto mode doesn't work for you or you have specific needs, is also possible to manually specify each segment with the relative mode. +In this way no segment optimizations will be applied under the hood.
+Segments list can be passed as an array of object: + +```javascript + var QRCode = require('qrcode') + + var segs = [ + { data: 'ABCDEFG', mode: 'alphanumeric' }, + { data: '0123456', mode: 'numeric' } + ] + + QRCode.toDataURL(segs, function (err, url) { + console.log(url) + }) +``` + +### Kanji mode +With kanji mode is possible to encode characters from the Shift JIS system in an optimized way.
+Unfortunately, there isn't a way to calculate a Shifted JIS values from, for example, a character encoded in UTF-8, for this reason a conversion table from the input characters to the SJIS values is needed.
+This table is not included by default in the bundle to keep the size as small as possible. + +If your application requires kanji support, you will need to pass a function that will take care of converting the input characters to appropriate values. + +An helper method is provided by the lib through an optional file that you can include as shown in the example below. + +**Note:** Support for Kanji mode is only needed if you want to benefit of the data compression, otherwise is still possible to encode kanji using Byte mode (See [Multibyte characters](#multibyte-characters)). + +```javascript + var QRCode = require('qrcode') + var toSJIS = require('qrcode/helper/to-sjis') + + QRCode.toDataURL(kanjiString, { toSJISFunc: toSJIS }, function (err, url) { + console.log(url) + }) +``` + +With precompiled bundle: + +```html + + + + + +``` + +## Binary data +QR Codes can hold arbitrary byte-based binary data. If you attempt to create a binary QR Code by first converting the data to a JavaScript string, it will fail to encode propery because string encoding adds additional bytes. Instead, you must pass a [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) or compatible array, or a Node [Buffer](https://nodejs.org/api/buffer.html), as follows: + +```javascript +// Regular array example +// WARNING: Element values will be clamped to 0-255 even if your data contains higher values. +const QRCode = require('qrcode') +QRCode.toFile( + 'foo.png', + [{ data: [253,254,255], mode: 'byte' }], + ...options..., + ...callback... +) +``` + +```javascript +// Uint8ClampedArray example +const QRCode = require('qrcode') + +QRCode.toFile( + 'foo.png', + [{ data: new Uint8ClampedArray([253,254,255]), mode: 'byte' }], + ...options..., + ...callback... +) +``` + +```javascript +// Node Buffer example +// WARNING: Element values will be clamped to 0-255 even if your data contains higher values. +const QRCode = require('qrcode') + +QRCode.toFile( + 'foo.png', + [{ data: Buffer.from([253,254,255]), mode: 'byte' }], + ...options..., + ...callback... +) +``` + +TypeScript users: if you are using [@types/qrcode](https://www.npmjs.com/package/@types/qrcode), you will need to add a `// @ts-ignore` above the data segment because it expects `data: string`. + +## Multibyte characters +Support for multibyte characters isn't present in the initial QR Code standard, but is possible to encode UTF-8 characters in Byte mode. + +QR Codes provide a way to specify a different type of character set through ECI (Extended Channel Interpretation), but it's not fully implemented in this lib yet. + +Most QR Code readers, however, are able to recognize multibyte characters even without ECI. + +Note that a single Kanji/Kana or Emoji can take up to 4 bytes. + +## API +Browser: +- [create()](#createtext-options) +- [toCanvas()](#tocanvascanvaselement-text-options-cberror) +- [toDataURL()](#todataurltext-options-cberror-url) +- [toString()](#tostringtext-options-cberror-string) + +Server: +- [create()](#createtext-options) +- [toCanvas()](#tocanvascanvas-text-options-cberror) +- [toDataURL()](#todataurltext-options-cberror-url-1) +- [toString()](#tostringtext-options-cberror-string-1) +- [toFile()](#tofilepath-text-options-cberror) +- [toFileStream()](#tofilestreamstream-text-options) + +### Browser API +#### `create(text, [options])` +Creates QR Code symbol and returns a qrcode object. + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +See [QR Code options](#qr-code-options). + +##### `returns` +Type: `Object` + +```javascript +// QRCode object +{ + modules, // Bitmatrix class with modules data + version, // Calculated QR Code version + errorCorrectionLevel, // Error Correction Level + maskPattern, // Calculated Mask pattern + segments // Generated segments +} +``` + +
+ +#### `toCanvas(canvasElement, text, [options], [cb(error)])` +#### `toCanvas(text, [options], [cb(error, canvas)])` +Draws qr code symbol to canvas.
+If `canvasElement` is omitted a new canvas is returned. + +##### `canvasElement` +Type: `DOMElement` + +Canvas where to draw QR Code. + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +See [Options](#options). + +##### `cb` +Type: `Function` + +Callback function called on finish. + +##### Example +```javascript +QRCode.toCanvas('text', { errorCorrectionLevel: 'H' }, function (err, canvas) { + if (err) throw err + + var container = document.getElementById('container') + container.appendChild(canvas) +}) +``` + +
+ +#### `toDataURL(text, [options], [cb(error, url)])` +#### `toDataURL(canvasElement, text, [options], [cb(error, url)])` +Returns a Data URI containing a representation of the QR Code image.
+If provided, `canvasElement` will be used as canvas to generate the data URI. + +##### `canvasElement` +Type: `DOMElement` + +Canvas where to draw QR Code. + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +- ###### `type` + Type: `String`
+ Default: `image/png` + + Data URI format.
+ Possible values are: `image/png`, `image/jpeg`, `image/webp`.
+ +- ###### `rendererOpts.quality` + Type: `Number`
+ Default: `0.92` + + A Number between `0` and `1` indicating image quality if the requested type is `image/jpeg` or `image/webp`. + +See [Options](#options) for other settings. + +##### `cb` +Type: `Function` + +Callback function called on finish. + +##### Example +```javascript +var opts = { + errorCorrectionLevel: 'H', + type: 'image/jpeg', + quality: 0.3, + margin: 1, + color: { + dark:"#010599FF", + light:"#FFBF60FF" + } +} + +QRCode.toDataURL('text', opts, function (err, url) { + if (err) throw err + + var img = document.getElementById('image') + img.src = url +}) +``` +
+ +#### `toString(text, [options], [cb(error, string)])` + +Returns a string representation of the QR Code.
+ + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +- ###### `type` + Type: `String`
+ Default: `utf8` + + Output format.
+ Possible values are: `terminal`,`utf8`, and `svg`. + +See [Options](#options) for other settings. + +##### `cb` +Type: `Function` + +Callback function called on finish. + +##### Example +```javascript +QRCode.toString('http://www.google.com', function (err, string) { + if (err) throw err + console.log(string) +}) +``` + +
+ + +### Server API +#### `create(text, [options])` +See [create](#createtext-options). + +
+ +#### `toCanvas(canvas, text, [options], [cb(error)])` +Draws qr code symbol to [node canvas](https://github.com/Automattic/node-canvas). + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +See [Options](#options). + +##### `cb` +Type: `Function` + +Callback function called on finish. + +
+ +#### `toDataURL(text, [options], [cb(error, url)])` +Returns a Data URI containing a representation of the QR Code image.
+Only works with `image/png` type for now. + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +See [Options](#options) for other settings. + +##### `cb` +Type: `Function` + +Callback function called on finish. + +
+ +#### `toString(text, [options], [cb(error, string)])` +Returns a string representation of the QR Code.
+If choosen output format is `svg` it will returns a string containing xml code. + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +- ###### `type` + Type: `String`
+ Default: `utf8` + + Output format.
+ Possible values are: `utf8`, `svg`, `terminal`. + +See [Options](#options) for other settings. + +##### `cb` +Type: `Function` + +Callback function called on finish. + +##### Example +```javascript +QRCode.toString('http://www.google.com', function (err, string) { + if (err) throw err + console.log(string) +}) +``` + +
+ +#### `toFile(path, text, [options], [cb(error)])` +Saves QR Code to image file.
+If `options.type` is not specified, the format will be guessed from file extension.
+Recognized extensions are `png`, `svg`, `txt`. + +##### `path` +Type: `String` + +Path where to save the file. + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +- ###### `type` + Type: `String`
+ Default: `png` + + Output format.
+ Possible values are: `png`, `svg`, `utf8`. + +- ###### `rendererOpts.deflateLevel` **(png only)** + Type: `Number`
+ Default: `9` + + Compression level for deflate. + +- ###### `rendererOpts.deflateStrategy` **(png only)** + Type: `Number`
+ Default: `3` + + Compression strategy for deflate. + +See [Options](#options) for other settings. + +##### `cb` +Type: `Function` + +Callback function called on finish. + +##### Example +```javascript +QRCode.toFile('path/to/filename.png', 'Some text', { + color: { + dark: '#00F', // Blue dots + light: '#0000' // Transparent background + } +}, function (err) { + if (err) throw err + console.log('done') +}) +``` + +
+ +#### `toFileStream(stream, text, [options])` +Writes QR Code image to stream. Only works with `png` format for now. + +##### `stream` +Type: `stream.Writable` + +Node stream. + +##### `text` +Type: `String|Array` + +Text to encode or a list of objects describing segments. + +##### `options` +See [Options](#options). + +
+ +### Options + +#### QR Code options +##### `version` + Type: `Number`
+ + QR Code version. If not specified the more suitable value will be calculated. + +##### `errorCorrectionLevel` + Type: `String`
+ Default: `M` + + Error correction level.
+ Possible values are `low, medium, quartile, high` or `L, M, Q, H`. + +##### `maskPattern` + Type: `Number`
+ + Mask pattern used to mask the symbol.
+ Possible values are `0`, `1`, `2`, `3`, `4`, `5`, `6`, `7`.
+ If not specified the more suitable value will be calculated. + +##### `toSJISFunc` + Type: `Function`
+ + Helper function used internally to convert a kanji to its Shift JIS value.
+ Provide this function if you need support for Kanji mode. + +#### Renderers options +##### `margin` + Type: `Number`
+ Default: `4` + + Define how much wide the quiet zone should be. + +##### `scale` + Type: `Number`
+ Default: `4` + + Scale factor. A value of `1` means 1px per modules (black dots). + +##### `small` + Type: `Boolean`
+ Default: `false` + + Relevant only for terminal renderer. Outputs smaller QR code. + +##### `width` + Type: `Number`
+ + Forces a specific width for the output image.
+ If width is too small to contain the qr symbol, this option will be ignored.
+ Takes precedence over `scale`. + +##### `color.dark` +Type: `String`
+Default: `#000000ff` + +Color of dark module. Value must be in hex format (RGBA).
+Note: dark color should always be darker than `color.light`. + +##### `color.light` +Type: `String`
+Default: `#ffffffff` + +Color of light module. Value must be in hex format (RGBA).
+ +
+ +## GS1 QR Codes +There was a real good discussion here about them. but in short any qrcode generator will make gs1 compatible qrcodes, but what defines a gs1 qrcode is a header with metadata that describes your gs1 information. + +https://github.com/soldair/node-qrcode/issues/45 + + +## Credits +This lib is based on "QRCode for JavaScript" which Kazuhiko Arase thankfully MIT licensed. + +## License +[MIT](https://github.com/soldair/node-qrcode/blob/master/license) + +The word "QR Code" is registered trademark of:
+DENSO WAVE INCORPORATED diff --git a/node_modules/qrcode/bin/qrcode b/node_modules/qrcode/bin/qrcode new file mode 100644 index 0000000..dd990b6 --- /dev/null +++ b/node_modules/qrcode/bin/qrcode @@ -0,0 +1,159 @@ +#!/usr/bin/env node +var yargs = require('yargs') +var qr = require('../lib') + +function save (file, text, options) { + qr.toFile(file, text, options, function (err, data) { + if (err) { + console.error('Error:', err.message) + process.exit(1) + } + + console.log('saved qrcode to: ' + file + '\n') + }) +} + +function print (text, options) { + options.type = 'terminal' + qr.toString(text, options, function (err, text) { + if (err) { + console.error('Error:', err.message) + process.exit(1) + } + + console.log(text) + }) +} + +function parseOptions (args) { + return { + version: args.qversion, + errorCorrectionLevel: args.error, + type: args.type, + small: !!args.small, + inverse: !!args.inverse, + maskPattern: args.mask, + margin: args.qzone, + width: args.width, + scale: args.scale, + color: { + light: args.lightcolor, + dark: args.darkcolor + } + } +} + +function processInputs (text, opts) { + if (!text.length) { + yargs.showHelp() + process.exit(1) + } + + if (opts.output) { + save(opts.output, text, parseOptions(opts)) + } else { + print(text, parseOptions(opts)) + } +} + +var argv = yargs + .detectLocale(false) + .usage('Usage: $0 [options] ') + .option('v', { + alias: 'qversion', + description: 'QR Code symbol version (1 - 40)', + group: 'QR Code options:', + type: 'number' + }) + .option('e', { + alias: 'error', + description: 'Error correction level', + choices: ['L', 'M', 'Q', 'H'], + group: 'QR Code options:' + }) + .option('m', { + alias: 'mask', + description: 'Mask pattern (0 - 7)', + group: 'QR Code options:', + type: 'number' + }) + .option('t', { + alias: 'type', + description: 'Output type', + choices: ['png', 'svg', 'utf8'], + implies: 'output', + group: 'Renderer options:' + }) + .option('i', { + alias: 'inverse', + type: 'boolean', + description: 'Invert colors', + group: 'Renderer options:' + }) + .option('w', { + alias: 'width', + description: 'Image width (px)', + conflicts: 'scale', + group: 'Renderer options:', + type: 'number' + }) + .option('s', { + alias: 'scale', + description: 'Scale factor', + conflicts: 'width', + group: 'Renderer options:', + type: 'number' + }) + .option('q', { + alias: 'qzone', + description: 'Quiet zone size', + group: 'Renderer options:', + type: 'number' + }) + .option('l', { + alias: 'lightcolor', + description: 'Light RGBA hex color', + group: 'Renderer options:' + }) + .option('d', { + alias: 'darkcolor', + description: 'Dark RGBA hex color', + group: 'Renderer options:' + }) + .option('small', { + type: 'boolean', + description: 'Output smaller QR code to terminal', + conflicts: 'type', + group: 'Renderer options:' + }) + .option('o', { + alias: 'output', + description: 'Output file' + }) + .help('h') + .alias('h', 'help') + .version() + .example('$0 "some text"', 'Draw in terminal window') + .example('$0 -o out.png "some text"', 'Save as png image') + .example('$0 -d F00 -o out.png "some text"', 'Use red as foreground color') + .parserConfiguration({'parse-numbers': false}) + .argv + +if (process.stdin.isTTY) { + processInputs(argv._.join(' '), argv) +} else { + var text = '' + process.stdin.setEncoding('utf8') + process.stdin.on('readable', function () { + var chunk = process.stdin.read() + if (chunk !== null) { + text += chunk + } + }) + + process.stdin.on('end', function () { + // this process can be run as a command outside of a tty so if there was no + // data on stdin read from argv + processInputs(text.length?text:argv._.join(' '), argv) + }) +} diff --git a/node_modules/qrcode/helper/to-sjis-browser.js b/node_modules/qrcode/helper/to-sjis-browser.js new file mode 100644 index 0000000..1c9b3aa --- /dev/null +++ b/node_modules/qrcode/helper/to-sjis-browser.js @@ -0,0 +1,2 @@ +/* global QRCode */ +QRCode.toSJIS = require('./to-sjis') diff --git a/node_modules/qrcode/helper/to-sjis.js b/node_modules/qrcode/helper/to-sjis.js new file mode 100644 index 0000000..594c6f7 --- /dev/null +++ b/node_modules/qrcode/helper/to-sjis.js @@ -0,0 +1,105 @@ +const SJIS_UTF8 = [ + [0x8140, ' 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×'], + [0x8180, '÷=≠<>≦≧∞∴♂♀°′″℃'], + [0x818f, '¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼'], + [0x81a6, '※〒→←↑↓〓'], + [0x81b8, '∈∋⊆⊇⊂⊃∪∩'], + [0x81c8, '∧∨¬⇒⇔∀∃'], + [0x81da, '∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬'], + [0x81f0, 'ʼn♯♭♪†‡¶'], + [0x824f, '0123456789'], + [0x8260, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'], + [0x8281, 'abcdefghijklmnopqrstuvwxyz'], + [0x829f, 'ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん'], + [0x8340, 'ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ'], + [0x8380, 'ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ'], + [0x839f, 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ'], + [0x83bf, 'αβγδεζηθικλμνξοπρστυφχψω'], + [0x8440, 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'], + [0x8470, 'абвгдеёжзийклмн'], + [0x8480, 'опрстуфхцчшщъыьэюя'], + [0x8780, '〝〟'], + [0x889f, '亜唖娃阿哀愛挨姶逢葵茜穐悪握渥旭葦芦鯵梓圧斡扱宛姐虻飴絢綾鮎或粟袷安庵按暗案闇鞍杏以伊位依偉囲夷委威尉惟意慰易椅為畏異移維緯胃萎衣'], + [0x88e0, '謂違遺医井亥域育郁磯一壱溢逸稲茨芋鰯允印咽員因姻引飲淫胤蔭'], + [0x8940, '院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円'], + [0x8980, '園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改'], + [0x8a40, '魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫'], + [0x8a80, '橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄'], + [0x8b40, '機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救'], + [0x8b80, '朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈'], + [0x8c40, '掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨'], + [0x8c80, '劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向'], + [0x8d40, '后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降'], + [0x8d80, '項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷'], + [0x8e40, '察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止'], + [0x8e80, '死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周'], + [0x8f40, '宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳'], + [0x8f80, '準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾'], + [0x9040, '拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨'], + [0x9080, '逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線'], + [0x9140, '繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻'], + [0x9180, '操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只'], + [0x9240, '叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄'], + [0x9280, '逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓'], + [0x9340, '邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬'], + [0x9380, '凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入'], + [0x9440, '如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅'], + [0x9480, '楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美'], + [0x9540, '鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷'], + [0x9580, '斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋'], + [0x9640, '法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆'], + [0x9680, '摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒'], + [0x9740, '諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲'], + [0x9780, '沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯'], + [0x9840, '蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕'], + [0x989f, '弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲'], + [0x9940, '僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭'], + [0x9980, '凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨'], + [0x9a40, '咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸'], + [0x9a80, '噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩'], + [0x9b40, '奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀'], + [0x9b80, '它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏'], + [0x9c40, '廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠'], + [0x9c80, '怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛'], + [0x9d40, '戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫'], + [0x9d80, '捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼'], + [0x9e40, '曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎'], + [0x9e80, '梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣'], + [0x9f40, '檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯'], + [0x9f80, '麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌'], + [0xe040, '漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝'], + [0xe080, '烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱'], + [0xe140, '瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿'], + [0xe180, '痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬'], + [0xe240, '磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰'], + [0xe280, '窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆'], + [0xe340, '紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷'], + [0xe380, '縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋'], + [0xe440, '隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤'], + [0xe480, '艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈'], + [0xe540, '蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬'], + [0xe580, '蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞'], + [0xe640, '襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧'], + [0xe680, '諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊'], + [0xe740, '蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜'], + [0xe780, '轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮'], + [0xe840, '錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙'], + [0xe880, '閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰'], + [0xe940, '顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃'], + [0xe980, '騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈'], + [0xea40, '鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯'], + [0xea80, '黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙'] +] + +module.exports = function toSJIS (utf8Char) { + if (!utf8Char || utf8Char === '') return + + for (let i = 0; i < SJIS_UTF8.length; i++) { + const kanji = SJIS_UTF8[i][1] + + const posIndex = kanji.indexOf(utf8Char) + if (posIndex >= 0) { + return SJIS_UTF8[i][0] + posIndex + } + } +} diff --git a/node_modules/qrcode/lib/browser.js b/node_modules/qrcode/lib/browser.js new file mode 100644 index 0000000..dc8a999 --- /dev/null +++ b/node_modules/qrcode/lib/browser.js @@ -0,0 +1,76 @@ + +const canPromise = require('./can-promise') + +const QRCode = require('./core/qrcode') +const CanvasRenderer = require('./renderer/canvas') +const SvgRenderer = require('./renderer/svg-tag.js') + +function renderCanvas (renderFunc, canvas, text, opts, cb) { + const args = [].slice.call(arguments, 1) + const argsNum = args.length + const isLastArgCb = typeof args[argsNum - 1] === 'function' + + if (!isLastArgCb && !canPromise()) { + throw new Error('Callback required as last argument') + } + + if (isLastArgCb) { + if (argsNum < 2) { + throw new Error('Too few arguments provided') + } + + if (argsNum === 2) { + cb = text + text = canvas + canvas = opts = undefined + } else if (argsNum === 3) { + if (canvas.getContext && typeof cb === 'undefined') { + cb = opts + opts = undefined + } else { + cb = opts + opts = text + text = canvas + canvas = undefined + } + } + } else { + if (argsNum < 1) { + throw new Error('Too few arguments provided') + } + + if (argsNum === 1) { + text = canvas + canvas = opts = undefined + } else if (argsNum === 2 && !canvas.getContext) { + opts = text + text = canvas + canvas = undefined + } + + return new Promise(function (resolve, reject) { + try { + const data = QRCode.create(text, opts) + resolve(renderFunc(data, canvas, opts)) + } catch (e) { + reject(e) + } + }) + } + + try { + const data = QRCode.create(text, opts) + cb(null, renderFunc(data, canvas, opts)) + } catch (e) { + cb(e) + } +} + +exports.create = QRCode.create +exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render) +exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL) + +// only svg for now. +exports.toString = renderCanvas.bind(null, function (data, _, opts) { + return SvgRenderer.render(data, opts) +}) diff --git a/node_modules/qrcode/lib/can-promise.js b/node_modules/qrcode/lib/can-promise.js new file mode 100644 index 0000000..77267f1 --- /dev/null +++ b/node_modules/qrcode/lib/can-promise.js @@ -0,0 +1,7 @@ +// can-promise has a crash in some versions of react native that dont have +// standard global objects +// https://github.com/soldair/node-qrcode/issues/157 + +module.exports = function () { + return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then +} diff --git a/node_modules/qrcode/lib/core/alignment-pattern.js b/node_modules/qrcode/lib/core/alignment-pattern.js new file mode 100644 index 0000000..63c3154 --- /dev/null +++ b/node_modules/qrcode/lib/core/alignment-pattern.js @@ -0,0 +1,83 @@ +/** + * Alignment pattern are fixed reference pattern in defined positions + * in a matrix symbology, which enables the decode software to re-synchronise + * the coordinate mapping of the image modules in the event of moderate amounts + * of distortion of the image. + * + * Alignment patterns are present only in QR Code symbols of version 2 or larger + * and their number depends on the symbol version. + */ + +const getSymbolSize = require('./utils').getSymbolSize + +/** + * Calculate the row/column coordinates of the center module of each alignment pattern + * for the specified QR Code version. + * + * The alignment patterns are positioned symmetrically on either side of the diagonal + * running from the top left corner of the symbol to the bottom right corner. + * + * Since positions are simmetrical only half of the coordinates are returned. + * Each item of the array will represent in turn the x and y coordinate. + * @see {@link getPositions} + * + * @param {Number} version QR Code version + * @return {Array} Array of coordinate + */ +exports.getRowColCoords = function getRowColCoords (version) { + if (version === 1) return [] + + const posCount = Math.floor(version / 7) + 2 + const size = getSymbolSize(version) + const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2 + const positions = [size - 7] // Last coord is always (size - 7) + + for (let i = 1; i < posCount - 1; i++) { + positions[i] = positions[i - 1] - intervals + } + + positions.push(6) // First coord is always 6 + + return positions.reverse() +} + +/** + * Returns an array containing the positions of each alignment pattern. + * Each array's element represent the center point of the pattern as (x, y) coordinates + * + * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords} + * and filtering out the items that overlaps with finder pattern + * + * @example + * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38. + * The alignment patterns, therefore, are to be centered on (row, column) + * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38). + * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns + * and are not therefore used for alignment patterns. + * + * let pos = getPositions(7) + * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]] + * + * @param {Number} version QR Code version + * @return {Array} Array of coordinates + */ +exports.getPositions = function getPositions (version) { + const coords = [] + const pos = exports.getRowColCoords(version) + const posLength = pos.length + + for (let i = 0; i < posLength; i++) { + for (let j = 0; j < posLength; j++) { + // Skip if position is occupied by finder patterns + if ((i === 0 && j === 0) || // top-left + (i === 0 && j === posLength - 1) || // bottom-left + (i === posLength - 1 && j === 0)) { // top-right + continue + } + + coords.push([pos[i], pos[j]]) + } + } + + return coords +} diff --git a/node_modules/qrcode/lib/core/alphanumeric-data.js b/node_modules/qrcode/lib/core/alphanumeric-data.js new file mode 100644 index 0000000..29ddf50 --- /dev/null +++ b/node_modules/qrcode/lib/core/alphanumeric-data.js @@ -0,0 +1,59 @@ +const Mode = require('./mode') + +/** + * Array of characters available in alphanumeric mode + * + * As per QR Code specification, to each character + * is assigned a value from 0 to 44 which in this case coincides + * with the array index + * + * @type {Array} + */ +const ALPHA_NUM_CHARS = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', + 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', + ' ', '$', '%', '*', '+', '-', '.', '/', ':' +] + +function AlphanumericData (data) { + this.mode = Mode.ALPHANUMERIC + this.data = data +} + +AlphanumericData.getBitsLength = function getBitsLength (length) { + return 11 * Math.floor(length / 2) + 6 * (length % 2) +} + +AlphanumericData.prototype.getLength = function getLength () { + return this.data.length +} + +AlphanumericData.prototype.getBitsLength = function getBitsLength () { + return AlphanumericData.getBitsLength(this.data.length) +} + +AlphanumericData.prototype.write = function write (bitBuffer) { + let i + + // Input data characters are divided into groups of two characters + // and encoded as 11-bit binary codes. + for (i = 0; i + 2 <= this.data.length; i += 2) { + // The character value of the first character is multiplied by 45 + let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45 + + // The character value of the second digit is added to the product + value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]) + + // The sum is then stored as 11-bit binary number + bitBuffer.put(value, 11) + } + + // If the number of input data characters is not a multiple of two, + // the character value of the final character is encoded as a 6-bit binary number. + if (this.data.length % 2) { + bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6) + } +} + +module.exports = AlphanumericData diff --git a/node_modules/qrcode/lib/core/bit-buffer.js b/node_modules/qrcode/lib/core/bit-buffer.js new file mode 100644 index 0000000..5b41d3d --- /dev/null +++ b/node_modules/qrcode/lib/core/bit-buffer.js @@ -0,0 +1,37 @@ +function BitBuffer () { + this.buffer = [] + this.length = 0 +} + +BitBuffer.prototype = { + + get: function (index) { + const bufIndex = Math.floor(index / 8) + return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1 + }, + + put: function (num, length) { + for (let i = 0; i < length; i++) { + this.putBit(((num >>> (length - i - 1)) & 1) === 1) + } + }, + + getLengthInBits: function () { + return this.length + }, + + putBit: function (bit) { + const bufIndex = Math.floor(this.length / 8) + if (this.buffer.length <= bufIndex) { + this.buffer.push(0) + } + + if (bit) { + this.buffer[bufIndex] |= (0x80 >>> (this.length % 8)) + } + + this.length++ + } +} + +module.exports = BitBuffer diff --git a/node_modules/qrcode/lib/core/bit-matrix.js b/node_modules/qrcode/lib/core/bit-matrix.js new file mode 100644 index 0000000..439138b --- /dev/null +++ b/node_modules/qrcode/lib/core/bit-matrix.js @@ -0,0 +1,65 @@ +/** + * Helper class to handle QR Code symbol modules + * + * @param {Number} size Symbol size + */ +function BitMatrix (size) { + if (!size || size < 1) { + throw new Error('BitMatrix size must be defined and greater than 0') + } + + this.size = size + this.data = new Uint8Array(size * size) + this.reservedBit = new Uint8Array(size * size) +} + +/** + * Set bit value at specified location + * If reserved flag is set, this bit will be ignored during masking process + * + * @param {Number} row + * @param {Number} col + * @param {Boolean} value + * @param {Boolean} reserved + */ +BitMatrix.prototype.set = function (row, col, value, reserved) { + const index = row * this.size + col + this.data[index] = value + if (reserved) this.reservedBit[index] = true +} + +/** + * Returns bit value at specified location + * + * @param {Number} row + * @param {Number} col + * @return {Boolean} + */ +BitMatrix.prototype.get = function (row, col) { + return this.data[row * this.size + col] +} + +/** + * Applies xor operator at specified location + * (used during masking process) + * + * @param {Number} row + * @param {Number} col + * @param {Boolean} value + */ +BitMatrix.prototype.xor = function (row, col, value) { + this.data[row * this.size + col] ^= value +} + +/** + * Check if bit at specified location is reserved + * + * @param {Number} row + * @param {Number} col + * @return {Boolean} + */ +BitMatrix.prototype.isReserved = function (row, col) { + return this.reservedBit[row * this.size + col] +} + +module.exports = BitMatrix diff --git a/node_modules/qrcode/lib/core/byte-data.js b/node_modules/qrcode/lib/core/byte-data.js new file mode 100644 index 0000000..d562fcc --- /dev/null +++ b/node_modules/qrcode/lib/core/byte-data.js @@ -0,0 +1,30 @@ +const Mode = require('./mode') + +function ByteData (data) { + this.mode = Mode.BYTE + if (typeof (data) === 'string') { + this.data = new TextEncoder().encode(data) + } else { + this.data = new Uint8Array(data) + } +} + +ByteData.getBitsLength = function getBitsLength (length) { + return length * 8 +} + +ByteData.prototype.getLength = function getLength () { + return this.data.length +} + +ByteData.prototype.getBitsLength = function getBitsLength () { + return ByteData.getBitsLength(this.data.length) +} + +ByteData.prototype.write = function (bitBuffer) { + for (let i = 0, l = this.data.length; i < l; i++) { + bitBuffer.put(this.data[i], 8) + } +} + +module.exports = ByteData diff --git a/node_modules/qrcode/lib/core/error-correction-code.js b/node_modules/qrcode/lib/core/error-correction-code.js new file mode 100644 index 0000000..5f2fceb --- /dev/null +++ b/node_modules/qrcode/lib/core/error-correction-code.js @@ -0,0 +1,135 @@ +const ECLevel = require('./error-correction-level') + +const EC_BLOCKS_TABLE = [ +// L M Q H + 1, 1, 1, 1, + 1, 1, 1, 1, + 1, 1, 2, 2, + 1, 2, 2, 4, + 1, 2, 4, 4, + 2, 4, 4, 4, + 2, 4, 6, 5, + 2, 4, 6, 6, + 2, 5, 8, 8, + 4, 5, 8, 8, + 4, 5, 8, 11, + 4, 8, 10, 11, + 4, 9, 12, 16, + 4, 9, 16, 16, + 6, 10, 12, 18, + 6, 10, 17, 16, + 6, 11, 16, 19, + 6, 13, 18, 21, + 7, 14, 21, 25, + 8, 16, 20, 25, + 8, 17, 23, 25, + 9, 17, 23, 34, + 9, 18, 25, 30, + 10, 20, 27, 32, + 12, 21, 29, 35, + 12, 23, 34, 37, + 12, 25, 34, 40, + 13, 26, 35, 42, + 14, 28, 38, 45, + 15, 29, 40, 48, + 16, 31, 43, 51, + 17, 33, 45, 54, + 18, 35, 48, 57, + 19, 37, 51, 60, + 19, 38, 53, 63, + 20, 40, 56, 66, + 21, 43, 59, 70, + 22, 45, 62, 74, + 24, 47, 65, 77, + 25, 49, 68, 81 +] + +const EC_CODEWORDS_TABLE = [ +// L M Q H + 7, 10, 13, 17, + 10, 16, 22, 28, + 15, 26, 36, 44, + 20, 36, 52, 64, + 26, 48, 72, 88, + 36, 64, 96, 112, + 40, 72, 108, 130, + 48, 88, 132, 156, + 60, 110, 160, 192, + 72, 130, 192, 224, + 80, 150, 224, 264, + 96, 176, 260, 308, + 104, 198, 288, 352, + 120, 216, 320, 384, + 132, 240, 360, 432, + 144, 280, 408, 480, + 168, 308, 448, 532, + 180, 338, 504, 588, + 196, 364, 546, 650, + 224, 416, 600, 700, + 224, 442, 644, 750, + 252, 476, 690, 816, + 270, 504, 750, 900, + 300, 560, 810, 960, + 312, 588, 870, 1050, + 336, 644, 952, 1110, + 360, 700, 1020, 1200, + 390, 728, 1050, 1260, + 420, 784, 1140, 1350, + 450, 812, 1200, 1440, + 480, 868, 1290, 1530, + 510, 924, 1350, 1620, + 540, 980, 1440, 1710, + 570, 1036, 1530, 1800, + 570, 1064, 1590, 1890, + 600, 1120, 1680, 1980, + 630, 1204, 1770, 2100, + 660, 1260, 1860, 2220, + 720, 1316, 1950, 2310, + 750, 1372, 2040, 2430 +] + +/** + * Returns the number of error correction block that the QR Code should contain + * for the specified version and error correction level. + * + * @param {Number} version QR Code version + * @param {Number} errorCorrectionLevel Error correction level + * @return {Number} Number of error correction blocks + */ +exports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) { + switch (errorCorrectionLevel) { + case ECLevel.L: + return EC_BLOCKS_TABLE[(version - 1) * 4 + 0] + case ECLevel.M: + return EC_BLOCKS_TABLE[(version - 1) * 4 + 1] + case ECLevel.Q: + return EC_BLOCKS_TABLE[(version - 1) * 4 + 2] + case ECLevel.H: + return EC_BLOCKS_TABLE[(version - 1) * 4 + 3] + default: + return undefined + } +} + +/** + * Returns the number of error correction codewords to use for the specified + * version and error correction level. + * + * @param {Number} version QR Code version + * @param {Number} errorCorrectionLevel Error correction level + * @return {Number} Number of error correction codewords + */ +exports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) { + switch (errorCorrectionLevel) { + case ECLevel.L: + return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0] + case ECLevel.M: + return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1] + case ECLevel.Q: + return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2] + case ECLevel.H: + return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3] + default: + return undefined + } +} diff --git a/node_modules/qrcode/lib/core/error-correction-level.js b/node_modules/qrcode/lib/core/error-correction-level.js new file mode 100644 index 0000000..07433d6 --- /dev/null +++ b/node_modules/qrcode/lib/core/error-correction-level.js @@ -0,0 +1,50 @@ +exports.L = { bit: 1 } +exports.M = { bit: 0 } +exports.Q = { bit: 3 } +exports.H = { bit: 2 } + +function fromString (string) { + if (typeof string !== 'string') { + throw new Error('Param is not a string') + } + + const lcStr = string.toLowerCase() + + switch (lcStr) { + case 'l': + case 'low': + return exports.L + + case 'm': + case 'medium': + return exports.M + + case 'q': + case 'quartile': + return exports.Q + + case 'h': + case 'high': + return exports.H + + default: + throw new Error('Unknown EC Level: ' + string) + } +} + +exports.isValid = function isValid (level) { + return level && typeof level.bit !== 'undefined' && + level.bit >= 0 && level.bit < 4 +} + +exports.from = function from (value, defaultValue) { + if (exports.isValid(value)) { + return value + } + + try { + return fromString(value) + } catch (e) { + return defaultValue + } +} diff --git a/node_modules/qrcode/lib/core/finder-pattern.js b/node_modules/qrcode/lib/core/finder-pattern.js new file mode 100644 index 0000000..4613c04 --- /dev/null +++ b/node_modules/qrcode/lib/core/finder-pattern.js @@ -0,0 +1,22 @@ +const getSymbolSize = require('./utils').getSymbolSize +const FINDER_PATTERN_SIZE = 7 + +/** + * Returns an array containing the positions of each finder pattern. + * Each array's element represent the top-left point of the pattern as (x, y) coordinates + * + * @param {Number} version QR Code version + * @return {Array} Array of coordinates + */ +exports.getPositions = function getPositions (version) { + const size = getSymbolSize(version) + + return [ + // top-left + [0, 0], + // top-right + [size - FINDER_PATTERN_SIZE, 0], + // bottom-left + [0, size - FINDER_PATTERN_SIZE] + ] +} diff --git a/node_modules/qrcode/lib/core/format-info.js b/node_modules/qrcode/lib/core/format-info.js new file mode 100644 index 0000000..11fe9ef --- /dev/null +++ b/node_modules/qrcode/lib/core/format-info.js @@ -0,0 +1,29 @@ +const Utils = require('./utils') + +const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0) +const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1) +const G15_BCH = Utils.getBCHDigit(G15) + +/** + * Returns format information with relative error correction bits + * + * The format information is a 15-bit sequence containing 5 data bits, + * with 10 error correction bits calculated using the (15, 5) BCH code. + * + * @param {Number} errorCorrectionLevel Error correction level + * @param {Number} mask Mask pattern + * @return {Number} Encoded format information bits + */ +exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) { + const data = ((errorCorrectionLevel.bit << 3) | mask) + let d = data << 10 + + while (Utils.getBCHDigit(d) - G15_BCH >= 0) { + d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH)) + } + + // xor final data with mask pattern in order to ensure that + // no combination of Error Correction Level and data mask pattern + // will result in an all-zero data string + return ((data << 10) | d) ^ G15_MASK +} diff --git a/node_modules/qrcode/lib/core/galois-field.js b/node_modules/qrcode/lib/core/galois-field.js new file mode 100644 index 0000000..8125179 --- /dev/null +++ b/node_modules/qrcode/lib/core/galois-field.js @@ -0,0 +1,69 @@ +const EXP_TABLE = new Uint8Array(512) +const LOG_TABLE = new Uint8Array(256) +/** + * Precompute the log and anti-log tables for faster computation later + * + * For each possible value in the galois field 2^8, we will pre-compute + * the logarithm and anti-logarithm (exponential) of this value + * + * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields} + */ +;(function initTables () { + let x = 1 + for (let i = 0; i < 255; i++) { + EXP_TABLE[i] = x + LOG_TABLE[x] = i + + x <<= 1 // multiply by 2 + + // The QR code specification says to use byte-wise modulo 100011101 arithmetic. + // This means that when a number is 256 or larger, it should be XORed with 0x11D. + if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256) + x ^= 0x11D + } + } + + // Optimization: double the size of the anti-log table so that we don't need to mod 255 to + // stay inside the bounds (because we will mainly use this table for the multiplication of + // two GF numbers, no more). + // @see {@link mul} + for (let i = 255; i < 512; i++) { + EXP_TABLE[i] = EXP_TABLE[i - 255] + } +}()) + +/** + * Returns log value of n inside Galois Field + * + * @param {Number} n + * @return {Number} + */ +exports.log = function log (n) { + if (n < 1) throw new Error('log(' + n + ')') + return LOG_TABLE[n] +} + +/** + * Returns anti-log value of n inside Galois Field + * + * @param {Number} n + * @return {Number} + */ +exports.exp = function exp (n) { + return EXP_TABLE[n] +} + +/** + * Multiplies two number inside Galois Field + * + * @param {Number} x + * @param {Number} y + * @return {Number} + */ +exports.mul = function mul (x, y) { + if (x === 0 || y === 0) return 0 + + // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized + // @see {@link initTables} + return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]] +} diff --git a/node_modules/qrcode/lib/core/kanji-data.js b/node_modules/qrcode/lib/core/kanji-data.js new file mode 100644 index 0000000..a1d9a69 --- /dev/null +++ b/node_modules/qrcode/lib/core/kanji-data.js @@ -0,0 +1,54 @@ +const Mode = require('./mode') +const Utils = require('./utils') + +function KanjiData (data) { + this.mode = Mode.KANJI + this.data = data +} + +KanjiData.getBitsLength = function getBitsLength (length) { + return length * 13 +} + +KanjiData.prototype.getLength = function getLength () { + return this.data.length +} + +KanjiData.prototype.getBitsLength = function getBitsLength () { + return KanjiData.getBitsLength(this.data.length) +} + +KanjiData.prototype.write = function (bitBuffer) { + let i + + // In the Shift JIS system, Kanji characters are represented by a two byte combination. + // These byte values are shifted from the JIS X 0208 values. + // JIS X 0208 gives details of the shift coded representation. + for (i = 0; i < this.data.length; i++) { + let value = Utils.toSJIS(this.data[i]) + + // For characters with Shift JIS values from 0x8140 to 0x9FFC: + if (value >= 0x8140 && value <= 0x9FFC) { + // Subtract 0x8140 from Shift JIS value + value -= 0x8140 + + // For characters with Shift JIS values from 0xE040 to 0xEBBF + } else if (value >= 0xE040 && value <= 0xEBBF) { + // Subtract 0xC140 from Shift JIS value + value -= 0xC140 + } else { + throw new Error( + 'Invalid SJIS character: ' + this.data[i] + '\n' + + 'Make sure your charset is UTF-8') + } + + // Multiply most significant byte of result by 0xC0 + // and add least significant byte to product + value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff) + + // Convert result to a 13-bit binary string + bitBuffer.put(value, 13) + } +} + +module.exports = KanjiData diff --git a/node_modules/qrcode/lib/core/mask-pattern.js b/node_modules/qrcode/lib/core/mask-pattern.js new file mode 100644 index 0000000..f5f8900 --- /dev/null +++ b/node_modules/qrcode/lib/core/mask-pattern.js @@ -0,0 +1,234 @@ +/** + * Data mask pattern reference + * @type {Object} + */ +exports.Patterns = { + PATTERN000: 0, + PATTERN001: 1, + PATTERN010: 2, + PATTERN011: 3, + PATTERN100: 4, + PATTERN101: 5, + PATTERN110: 6, + PATTERN111: 7 +} + +/** + * Weighted penalty scores for the undesirable features + * @type {Object} + */ +const PenaltyScores = { + N1: 3, + N2: 3, + N3: 40, + N4: 10 +} + +/** + * Check if mask pattern value is valid + * + * @param {Number} mask Mask pattern + * @return {Boolean} true if valid, false otherwise + */ +exports.isValid = function isValid (mask) { + return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7 +} + +/** + * Returns mask pattern from a value. + * If value is not valid, returns undefined + * + * @param {Number|String} value Mask pattern value + * @return {Number} Valid mask pattern or undefined + */ +exports.from = function from (value) { + return exports.isValid(value) ? parseInt(value, 10) : undefined +} + +/** +* Find adjacent modules in row/column with the same color +* and assign a penalty value. +* +* Points: N1 + i +* i is the amount by which the number of adjacent modules of the same color exceeds 5 +*/ +exports.getPenaltyN1 = function getPenaltyN1 (data) { + const size = data.size + let points = 0 + let sameCountCol = 0 + let sameCountRow = 0 + let lastCol = null + let lastRow = null + + for (let row = 0; row < size; row++) { + sameCountCol = sameCountRow = 0 + lastCol = lastRow = null + + for (let col = 0; col < size; col++) { + let module = data.get(row, col) + if (module === lastCol) { + sameCountCol++ + } else { + if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5) + lastCol = module + sameCountCol = 1 + } + + module = data.get(col, row) + if (module === lastRow) { + sameCountRow++ + } else { + if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5) + lastRow = module + sameCountRow = 1 + } + } + + if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5) + if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5) + } + + return points +} + +/** + * Find 2x2 blocks with the same color and assign a penalty value + * + * Points: N2 * (m - 1) * (n - 1) + */ +exports.getPenaltyN2 = function getPenaltyN2 (data) { + const size = data.size + let points = 0 + + for (let row = 0; row < size - 1; row++) { + for (let col = 0; col < size - 1; col++) { + const last = data.get(row, col) + + data.get(row, col + 1) + + data.get(row + 1, col) + + data.get(row + 1, col + 1) + + if (last === 4 || last === 0) points++ + } + } + + return points * PenaltyScores.N2 +} + +/** + * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column, + * preceded or followed by light area 4 modules wide + * + * Points: N3 * number of pattern found + */ +exports.getPenaltyN3 = function getPenaltyN3 (data) { + const size = data.size + let points = 0 + let bitsCol = 0 + let bitsRow = 0 + + for (let row = 0; row < size; row++) { + bitsCol = bitsRow = 0 + for (let col = 0; col < size; col++) { + bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col) + if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++ + + bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row) + if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++ + } + } + + return points * PenaltyScores.N3 +} + +/** + * Calculate proportion of dark modules in entire symbol + * + * Points: N4 * k + * + * k is the rating of the deviation of the proportion of dark modules + * in the symbol from 50% in steps of 5% + */ +exports.getPenaltyN4 = function getPenaltyN4 (data) { + let darkCount = 0 + const modulesCount = data.data.length + + for (let i = 0; i < modulesCount; i++) darkCount += data.data[i] + + const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10) + + return k * PenaltyScores.N4 +} + +/** + * Return mask value at given position + * + * @param {Number} maskPattern Pattern reference value + * @param {Number} i Row + * @param {Number} j Column + * @return {Boolean} Mask value + */ +function getMaskAt (maskPattern, i, j) { + switch (maskPattern) { + case exports.Patterns.PATTERN000: return (i + j) % 2 === 0 + case exports.Patterns.PATTERN001: return i % 2 === 0 + case exports.Patterns.PATTERN010: return j % 3 === 0 + case exports.Patterns.PATTERN011: return (i + j) % 3 === 0 + case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0 + case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0 + case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0 + case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0 + + default: throw new Error('bad maskPattern:' + maskPattern) + } +} + +/** + * Apply a mask pattern to a BitMatrix + * + * @param {Number} pattern Pattern reference number + * @param {BitMatrix} data BitMatrix data + */ +exports.applyMask = function applyMask (pattern, data) { + const size = data.size + + for (let col = 0; col < size; col++) { + for (let row = 0; row < size; row++) { + if (data.isReserved(row, col)) continue + data.xor(row, col, getMaskAt(pattern, row, col)) + } + } +} + +/** + * Returns the best mask pattern for data + * + * @param {BitMatrix} data + * @return {Number} Mask pattern reference number + */ +exports.getBestMask = function getBestMask (data, setupFormatFunc) { + const numPatterns = Object.keys(exports.Patterns).length + let bestPattern = 0 + let lowerPenalty = Infinity + + for (let p = 0; p < numPatterns; p++) { + setupFormatFunc(p) + exports.applyMask(p, data) + + // Calculate penalty + const penalty = + exports.getPenaltyN1(data) + + exports.getPenaltyN2(data) + + exports.getPenaltyN3(data) + + exports.getPenaltyN4(data) + + // Undo previously applied mask + exports.applyMask(p, data) + + if (penalty < lowerPenalty) { + lowerPenalty = penalty + bestPattern = p + } + } + + return bestPattern +} diff --git a/node_modules/qrcode/lib/core/mode.js b/node_modules/qrcode/lib/core/mode.js new file mode 100644 index 0000000..fd95a6e --- /dev/null +++ b/node_modules/qrcode/lib/core/mode.js @@ -0,0 +1,167 @@ +const VersionCheck = require('./version-check') +const Regex = require('./regex') + +/** + * Numeric mode encodes data from the decimal digit set (0 - 9) + * (byte values 30HEX to 39HEX). + * Normally, 3 data characters are represented by 10 bits. + * + * @type {Object} + */ +exports.NUMERIC = { + id: 'Numeric', + bit: 1 << 0, + ccBits: [10, 12, 14] +} + +/** + * Alphanumeric mode encodes data from a set of 45 characters, + * i.e. 10 numeric digits (0 - 9), + * 26 alphabetic characters (A - Z), + * and 9 symbols (SP, $, %, *, +, -, ., /, :). + * Normally, two input characters are represented by 11 bits. + * + * @type {Object} + */ +exports.ALPHANUMERIC = { + id: 'Alphanumeric', + bit: 1 << 1, + ccBits: [9, 11, 13] +} + +/** + * In byte mode, data is encoded at 8 bits per character. + * + * @type {Object} + */ +exports.BYTE = { + id: 'Byte', + bit: 1 << 2, + ccBits: [8, 16, 16] +} + +/** + * The Kanji mode efficiently encodes Kanji characters in accordance with + * the Shift JIS system based on JIS X 0208. + * The Shift JIS values are shifted from the JIS X 0208 values. + * JIS X 0208 gives details of the shift coded representation. + * Each two-byte character value is compacted to a 13-bit binary codeword. + * + * @type {Object} + */ +exports.KANJI = { + id: 'Kanji', + bit: 1 << 3, + ccBits: [8, 10, 12] +} + +/** + * Mixed mode will contain a sequences of data in a combination of any of + * the modes described above + * + * @type {Object} + */ +exports.MIXED = { + bit: -1 +} + +/** + * Returns the number of bits needed to store the data length + * according to QR Code specifications. + * + * @param {Mode} mode Data mode + * @param {Number} version QR Code version + * @return {Number} Number of bits + */ +exports.getCharCountIndicator = function getCharCountIndicator (mode, version) { + if (!mode.ccBits) throw new Error('Invalid mode: ' + mode) + + if (!VersionCheck.isValid(version)) { + throw new Error('Invalid version: ' + version) + } + + if (version >= 1 && version < 10) return mode.ccBits[0] + else if (version < 27) return mode.ccBits[1] + return mode.ccBits[2] +} + +/** + * Returns the most efficient mode to store the specified data + * + * @param {String} dataStr Input data string + * @return {Mode} Best mode + */ +exports.getBestModeForData = function getBestModeForData (dataStr) { + if (Regex.testNumeric(dataStr)) return exports.NUMERIC + else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC + else if (Regex.testKanji(dataStr)) return exports.KANJI + else return exports.BYTE +} + +/** + * Return mode name as string + * + * @param {Mode} mode Mode object + * @returns {String} Mode name + */ +exports.toString = function toString (mode) { + if (mode && mode.id) return mode.id + throw new Error('Invalid mode') +} + +/** + * Check if input param is a valid mode object + * + * @param {Mode} mode Mode object + * @returns {Boolean} True if valid mode, false otherwise + */ +exports.isValid = function isValid (mode) { + return mode && mode.bit && mode.ccBits +} + +/** + * Get mode object from its name + * + * @param {String} string Mode name + * @returns {Mode} Mode object + */ +function fromString (string) { + if (typeof string !== 'string') { + throw new Error('Param is not a string') + } + + const lcStr = string.toLowerCase() + + switch (lcStr) { + case 'numeric': + return exports.NUMERIC + case 'alphanumeric': + return exports.ALPHANUMERIC + case 'kanji': + return exports.KANJI + case 'byte': + return exports.BYTE + default: + throw new Error('Unknown mode: ' + string) + } +} + +/** + * Returns mode from a value. + * If value is not a valid mode, returns defaultValue + * + * @param {Mode|String} value Encoding mode + * @param {Mode} defaultValue Fallback value + * @return {Mode} Encoding mode + */ +exports.from = function from (value, defaultValue) { + if (exports.isValid(value)) { + return value + } + + try { + return fromString(value) + } catch (e) { + return defaultValue + } +} diff --git a/node_modules/qrcode/lib/core/numeric-data.js b/node_modules/qrcode/lib/core/numeric-data.js new file mode 100644 index 0000000..5223991 --- /dev/null +++ b/node_modules/qrcode/lib/core/numeric-data.js @@ -0,0 +1,43 @@ +const Mode = require('./mode') + +function NumericData (data) { + this.mode = Mode.NUMERIC + this.data = data.toString() +} + +NumericData.getBitsLength = function getBitsLength (length) { + return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0) +} + +NumericData.prototype.getLength = function getLength () { + return this.data.length +} + +NumericData.prototype.getBitsLength = function getBitsLength () { + return NumericData.getBitsLength(this.data.length) +} + +NumericData.prototype.write = function write (bitBuffer) { + let i, group, value + + // The input data string is divided into groups of three digits, + // and each group is converted to its 10-bit binary equivalent. + for (i = 0; i + 3 <= this.data.length; i += 3) { + group = this.data.substr(i, 3) + value = parseInt(group, 10) + + bitBuffer.put(value, 10) + } + + // If the number of input digits is not an exact multiple of three, + // the final one or two digits are converted to 4 or 7 bits respectively. + const remainingNum = this.data.length - i + if (remainingNum > 0) { + group = this.data.substr(i) + value = parseInt(group, 10) + + bitBuffer.put(value, remainingNum * 3 + 1) + } +} + +module.exports = NumericData diff --git a/node_modules/qrcode/lib/core/polynomial.js b/node_modules/qrcode/lib/core/polynomial.js new file mode 100644 index 0000000..c6ed9c2 --- /dev/null +++ b/node_modules/qrcode/lib/core/polynomial.js @@ -0,0 +1,62 @@ +const GF = require('./galois-field') + +/** + * Multiplies two polynomials inside Galois Field + * + * @param {Uint8Array} p1 Polynomial + * @param {Uint8Array} p2 Polynomial + * @return {Uint8Array} Product of p1 and p2 + */ +exports.mul = function mul (p1, p2) { + const coeff = new Uint8Array(p1.length + p2.length - 1) + + for (let i = 0; i < p1.length; i++) { + for (let j = 0; j < p2.length; j++) { + coeff[i + j] ^= GF.mul(p1[i], p2[j]) + } + } + + return coeff +} + +/** + * Calculate the remainder of polynomials division + * + * @param {Uint8Array} divident Polynomial + * @param {Uint8Array} divisor Polynomial + * @return {Uint8Array} Remainder + */ +exports.mod = function mod (divident, divisor) { + let result = new Uint8Array(divident) + + while ((result.length - divisor.length) >= 0) { + const coeff = result[0] + + for (let i = 0; i < divisor.length; i++) { + result[i] ^= GF.mul(divisor[i], coeff) + } + + // remove all zeros from buffer head + let offset = 0 + while (offset < result.length && result[offset] === 0) offset++ + result = result.slice(offset) + } + + return result +} + +/** + * Generate an irreducible generator polynomial of specified degree + * (used by Reed-Solomon encoder) + * + * @param {Number} degree Degree of the generator polynomial + * @return {Uint8Array} Buffer containing polynomial coefficients + */ +exports.generateECPolynomial = function generateECPolynomial (degree) { + let poly = new Uint8Array([1]) + for (let i = 0; i < degree; i++) { + poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)])) + } + + return poly +} diff --git a/node_modules/qrcode/lib/core/qrcode.js b/node_modules/qrcode/lib/core/qrcode.js new file mode 100644 index 0000000..f76df54 --- /dev/null +++ b/node_modules/qrcode/lib/core/qrcode.js @@ -0,0 +1,495 @@ +const Utils = require('./utils') +const ECLevel = require('./error-correction-level') +const BitBuffer = require('./bit-buffer') +const BitMatrix = require('./bit-matrix') +const AlignmentPattern = require('./alignment-pattern') +const FinderPattern = require('./finder-pattern') +const MaskPattern = require('./mask-pattern') +const ECCode = require('./error-correction-code') +const ReedSolomonEncoder = require('./reed-solomon-encoder') +const Version = require('./version') +const FormatInfo = require('./format-info') +const Mode = require('./mode') +const Segments = require('./segments') + +/** + * QRCode for JavaScript + * + * modified by Ryan Day for nodejs support + * Copyright (c) 2011 Ryan Day + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/mit-license.php + * +//--------------------------------------------------------------------- +// QRCode for JavaScript +// +// Copyright (c) 2009 Kazuhiko Arase +// +// URL: http://www.d-project.com/ +// +// Licensed under the MIT license: +// http://www.opensource.org/licenses/mit-license.php +// +// The word "QR Code" is registered trademark of +// DENSO WAVE INCORPORATED +// http://www.denso-wave.com/qrcode/faqpatent-e.html +// +//--------------------------------------------------------------------- +*/ + +/** + * Add finder patterns bits to matrix + * + * @param {BitMatrix} matrix Modules matrix + * @param {Number} version QR Code version + */ +function setupFinderPattern (matrix, version) { + const size = matrix.size + const pos = FinderPattern.getPositions(version) + + for (let i = 0; i < pos.length; i++) { + const row = pos[i][0] + const col = pos[i][1] + + for (let r = -1; r <= 7; r++) { + if (row + r <= -1 || size <= row + r) continue + + for (let c = -1; c <= 7; c++) { + if (col + c <= -1 || size <= col + c) continue + + if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) || + (c >= 0 && c <= 6 && (r === 0 || r === 6)) || + (r >= 2 && r <= 4 && c >= 2 && c <= 4)) { + matrix.set(row + r, col + c, true, true) + } else { + matrix.set(row + r, col + c, false, true) + } + } + } + } +} + +/** + * Add timing pattern bits to matrix + * + * Note: this function must be called before {@link setupAlignmentPattern} + * + * @param {BitMatrix} matrix Modules matrix + */ +function setupTimingPattern (matrix) { + const size = matrix.size + + for (let r = 8; r < size - 8; r++) { + const value = r % 2 === 0 + matrix.set(r, 6, value, true) + matrix.set(6, r, value, true) + } +} + +/** + * Add alignment patterns bits to matrix + * + * Note: this function must be called after {@link setupTimingPattern} + * + * @param {BitMatrix} matrix Modules matrix + * @param {Number} version QR Code version + */ +function setupAlignmentPattern (matrix, version) { + const pos = AlignmentPattern.getPositions(version) + + for (let i = 0; i < pos.length; i++) { + const row = pos[i][0] + const col = pos[i][1] + + for (let r = -2; r <= 2; r++) { + for (let c = -2; c <= 2; c++) { + if (r === -2 || r === 2 || c === -2 || c === 2 || + (r === 0 && c === 0)) { + matrix.set(row + r, col + c, true, true) + } else { + matrix.set(row + r, col + c, false, true) + } + } + } + } +} + +/** + * Add version info bits to matrix + * + * @param {BitMatrix} matrix Modules matrix + * @param {Number} version QR Code version + */ +function setupVersionInfo (matrix, version) { + const size = matrix.size + const bits = Version.getEncodedBits(version) + let row, col, mod + + for (let i = 0; i < 18; i++) { + row = Math.floor(i / 3) + col = i % 3 + size - 8 - 3 + mod = ((bits >> i) & 1) === 1 + + matrix.set(row, col, mod, true) + matrix.set(col, row, mod, true) + } +} + +/** + * Add format info bits to matrix + * + * @param {BitMatrix} matrix Modules matrix + * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level + * @param {Number} maskPattern Mask pattern reference value + */ +function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) { + const size = matrix.size + const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern) + let i, mod + + for (i = 0; i < 15; i++) { + mod = ((bits >> i) & 1) === 1 + + // vertical + if (i < 6) { + matrix.set(i, 8, mod, true) + } else if (i < 8) { + matrix.set(i + 1, 8, mod, true) + } else { + matrix.set(size - 15 + i, 8, mod, true) + } + + // horizontal + if (i < 8) { + matrix.set(8, size - i - 1, mod, true) + } else if (i < 9) { + matrix.set(8, 15 - i - 1 + 1, mod, true) + } else { + matrix.set(8, 15 - i - 1, mod, true) + } + } + + // fixed module + matrix.set(size - 8, 8, 1, true) +} + +/** + * Add encoded data bits to matrix + * + * @param {BitMatrix} matrix Modules matrix + * @param {Uint8Array} data Data codewords + */ +function setupData (matrix, data) { + const size = matrix.size + let inc = -1 + let row = size - 1 + let bitIndex = 7 + let byteIndex = 0 + + for (let col = size - 1; col > 0; col -= 2) { + if (col === 6) col-- + + while (true) { + for (let c = 0; c < 2; c++) { + if (!matrix.isReserved(row, col - c)) { + let dark = false + + if (byteIndex < data.length) { + dark = (((data[byteIndex] >>> bitIndex) & 1) === 1) + } + + matrix.set(row, col - c, dark) + bitIndex-- + + if (bitIndex === -1) { + byteIndex++ + bitIndex = 7 + } + } + } + + row += inc + + if (row < 0 || size <= row) { + row -= inc + inc = -inc + break + } + } + } +} + +/** + * Create encoded codewords from data input + * + * @param {Number} version QR Code version + * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level + * @param {ByteData} data Data input + * @return {Uint8Array} Buffer containing encoded codewords + */ +function createData (version, errorCorrectionLevel, segments) { + // Prepare data buffer + const buffer = new BitBuffer() + + segments.forEach(function (data) { + // prefix data with mode indicator (4 bits) + buffer.put(data.mode.bit, 4) + + // Prefix data with character count indicator. + // The character count indicator is a string of bits that represents the + // number of characters that are being encoded. + // The character count indicator must be placed after the mode indicator + // and must be a certain number of bits long, depending on the QR version + // and data mode + // @see {@link Mode.getCharCountIndicator}. + buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version)) + + // add binary data sequence to buffer + data.write(buffer) + }) + + // Calculate required number of bits + const totalCodewords = Utils.getSymbolTotalCodewords(version) + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) + const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8 + + // Add a terminator. + // If the bit string is shorter than the total number of required bits, + // a terminator of up to four 0s must be added to the right side of the string. + // If the bit string is more than four bits shorter than the required number of bits, + // add four 0s to the end. + if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) { + buffer.put(0, 4) + } + + // If the bit string is fewer than four bits shorter, add only the number of 0s that + // are needed to reach the required number of bits. + + // After adding the terminator, if the number of bits in the string is not a multiple of 8, + // pad the string on the right with 0s to make the string's length a multiple of 8. + while (buffer.getLengthInBits() % 8 !== 0) { + buffer.putBit(0) + } + + // Add pad bytes if the string is still shorter than the total number of required bits. + // Extend the buffer to fill the data capacity of the symbol corresponding to + // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC) + // and 00010001 (0x11) alternately. + const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8 + for (let i = 0; i < remainingByte; i++) { + buffer.put(i % 2 ? 0x11 : 0xEC, 8) + } + + return createCodewords(buffer, version, errorCorrectionLevel) +} + +/** + * Encode input data with Reed-Solomon and return codewords with + * relative error correction bits + * + * @param {BitBuffer} bitBuffer Data to encode + * @param {Number} version QR Code version + * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level + * @return {Uint8Array} Buffer containing encoded codewords + */ +function createCodewords (bitBuffer, version, errorCorrectionLevel) { + // Total codewords for this QR code version (Data + Error correction) + const totalCodewords = Utils.getSymbolTotalCodewords(version) + + // Total number of error correction codewords + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) + + // Total number of data codewords + const dataTotalCodewords = totalCodewords - ecTotalCodewords + + // Total number of blocks + const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel) + + // Calculate how many blocks each group should contain + const blocksInGroup2 = totalCodewords % ecTotalBlocks + const blocksInGroup1 = ecTotalBlocks - blocksInGroup2 + + const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks) + + const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks) + const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1 + + // Number of EC codewords is the same for both groups + const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1 + + // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount + const rs = new ReedSolomonEncoder(ecCount) + + let offset = 0 + const dcData = new Array(ecTotalBlocks) + const ecData = new Array(ecTotalBlocks) + let maxDataSize = 0 + const buffer = new Uint8Array(bitBuffer.buffer) + + // Divide the buffer into the required number of blocks + for (let b = 0; b < ecTotalBlocks; b++) { + const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2 + + // extract a block of data from buffer + dcData[b] = buffer.slice(offset, offset + dataSize) + + // Calculate EC codewords for this data block + ecData[b] = rs.encode(dcData[b]) + + offset += dataSize + maxDataSize = Math.max(maxDataSize, dataSize) + } + + // Create final data + // Interleave the data and error correction codewords from each block + const data = new Uint8Array(totalCodewords) + let index = 0 + let i, r + + // Add data codewords + for (i = 0; i < maxDataSize; i++) { + for (r = 0; r < ecTotalBlocks; r++) { + if (i < dcData[r].length) { + data[index++] = dcData[r][i] + } + } + } + + // Apped EC codewords + for (i = 0; i < ecCount; i++) { + for (r = 0; r < ecTotalBlocks; r++) { + data[index++] = ecData[r][i] + } + } + + return data +} + +/** + * Build QR Code symbol + * + * @param {String} data Input string + * @param {Number} version QR Code version + * @param {ErrorCorretionLevel} errorCorrectionLevel Error level + * @param {MaskPattern} maskPattern Mask pattern + * @return {Object} Object containing symbol data + */ +function createSymbol (data, version, errorCorrectionLevel, maskPattern) { + let segments + + if (Array.isArray(data)) { + segments = Segments.fromArray(data) + } else if (typeof data === 'string') { + let estimatedVersion = version + + if (!estimatedVersion) { + const rawSegments = Segments.rawSplit(data) + + // Estimate best version that can contain raw splitted segments + estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel) + } + + // Build optimized segments + // If estimated version is undefined, try with the highest version + segments = Segments.fromString(data, estimatedVersion || 40) + } else { + throw new Error('Invalid data') + } + + // Get the min version that can contain data + const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel) + + // If no version is found, data cannot be stored + if (!bestVersion) { + throw new Error('The amount of data is too big to be stored in a QR Code') + } + + // If not specified, use min version as default + if (!version) { + version = bestVersion + + // Check if the specified version can contain the data + } else if (version < bestVersion) { + throw new Error('\n' + + 'The chosen QR Code version cannot contain this amount of data.\n' + + 'Minimum version required to store current data is: ' + bestVersion + '.\n' + ) + } + + const dataBits = createData(version, errorCorrectionLevel, segments) + + // Allocate matrix buffer + const moduleCount = Utils.getSymbolSize(version) + const modules = new BitMatrix(moduleCount) + + // Add function modules + setupFinderPattern(modules, version) + setupTimingPattern(modules) + setupAlignmentPattern(modules, version) + + // Add temporary dummy bits for format info just to set them as reserved. + // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask} + // since the masking operation must be performed only on the encoding region. + // These blocks will be replaced with correct values later in code. + setupFormatInfo(modules, errorCorrectionLevel, 0) + + if (version >= 7) { + setupVersionInfo(modules, version) + } + + // Add data codewords + setupData(modules, dataBits) + + if (isNaN(maskPattern)) { + // Find best mask pattern + maskPattern = MaskPattern.getBestMask(modules, + setupFormatInfo.bind(null, modules, errorCorrectionLevel)) + } + + // Apply mask pattern + MaskPattern.applyMask(maskPattern, modules) + + // Replace format info bits with correct values + setupFormatInfo(modules, errorCorrectionLevel, maskPattern) + + return { + modules: modules, + version: version, + errorCorrectionLevel: errorCorrectionLevel, + maskPattern: maskPattern, + segments: segments + } +} + +/** + * QR Code + * + * @param {String | Array} data Input data + * @param {Object} options Optional configurations + * @param {Number} options.version QR Code version + * @param {String} options.errorCorrectionLevel Error correction level + * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis + */ +exports.create = function create (data, options) { + if (typeof data === 'undefined' || data === '') { + throw new Error('No input text') + } + + let errorCorrectionLevel = ECLevel.M + let version + let mask + + if (typeof options !== 'undefined') { + // Use higher error correction level as default + errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M) + version = Version.from(options.version) + mask = MaskPattern.from(options.maskPattern) + + if (options.toSJISFunc) { + Utils.setToSJISFunction(options.toSJISFunc) + } + } + + return createSymbol(data, version, errorCorrectionLevel, mask) +} diff --git a/node_modules/qrcode/lib/core/reed-solomon-encoder.js b/node_modules/qrcode/lib/core/reed-solomon-encoder.js new file mode 100644 index 0000000..c198422 --- /dev/null +++ b/node_modules/qrcode/lib/core/reed-solomon-encoder.js @@ -0,0 +1,56 @@ +const Polynomial = require('./polynomial') + +function ReedSolomonEncoder (degree) { + this.genPoly = undefined + this.degree = degree + + if (this.degree) this.initialize(this.degree) +} + +/** + * Initialize the encoder. + * The input param should correspond to the number of error correction codewords. + * + * @param {Number} degree + */ +ReedSolomonEncoder.prototype.initialize = function initialize (degree) { + // create an irreducible generator polynomial + this.degree = degree + this.genPoly = Polynomial.generateECPolynomial(this.degree) +} + +/** + * Encodes a chunk of data + * + * @param {Uint8Array} data Buffer containing input data + * @return {Uint8Array} Buffer containing encoded data + */ +ReedSolomonEncoder.prototype.encode = function encode (data) { + if (!this.genPoly) { + throw new Error('Encoder not initialized') + } + + // Calculate EC for this data block + // extends data size to data+genPoly size + const paddedData = new Uint8Array(data.length + this.degree) + paddedData.set(data) + + // The error correction codewords are the remainder after dividing the data codewords + // by a generator polynomial + const remainder = Polynomial.mod(paddedData, this.genPoly) + + // return EC data blocks (last n byte, where n is the degree of genPoly) + // If coefficients number in remainder are less than genPoly degree, + // pad with 0s to the left to reach the needed number of coefficients + const start = this.degree - remainder.length + if (start > 0) { + const buff = new Uint8Array(this.degree) + buff.set(remainder, start) + + return buff + } + + return remainder +} + +module.exports = ReedSolomonEncoder diff --git a/node_modules/qrcode/lib/core/regex.js b/node_modules/qrcode/lib/core/regex.js new file mode 100644 index 0000000..9dd13a4 --- /dev/null +++ b/node_modules/qrcode/lib/core/regex.js @@ -0,0 +1,31 @@ +const numeric = '[0-9]+' +const alphanumeric = '[A-Z $%*+\\-./:]+' +let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' + + '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' + + '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' + + '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+' +kanji = kanji.replace(/u/g, '\\u') + +const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+' + +exports.KANJI = new RegExp(kanji, 'g') +exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g') +exports.BYTE = new RegExp(byte, 'g') +exports.NUMERIC = new RegExp(numeric, 'g') +exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g') + +const TEST_KANJI = new RegExp('^' + kanji + '$') +const TEST_NUMERIC = new RegExp('^' + numeric + '$') +const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$') + +exports.testKanji = function testKanji (str) { + return TEST_KANJI.test(str) +} + +exports.testNumeric = function testNumeric (str) { + return TEST_NUMERIC.test(str) +} + +exports.testAlphanumeric = function testAlphanumeric (str) { + return TEST_ALPHANUMERIC.test(str) +} diff --git a/node_modules/qrcode/lib/core/segments.js b/node_modules/qrcode/lib/core/segments.js new file mode 100644 index 0000000..ba8be17 --- /dev/null +++ b/node_modules/qrcode/lib/core/segments.js @@ -0,0 +1,330 @@ +const Mode = require('./mode') +const NumericData = require('./numeric-data') +const AlphanumericData = require('./alphanumeric-data') +const ByteData = require('./byte-data') +const KanjiData = require('./kanji-data') +const Regex = require('./regex') +const Utils = require('./utils') +const dijkstra = require('dijkstrajs') + +/** + * Returns UTF8 byte length + * + * @param {String} str Input string + * @return {Number} Number of byte + */ +function getStringByteLength (str) { + return unescape(encodeURIComponent(str)).length +} + +/** + * Get a list of segments of the specified mode + * from a string + * + * @param {Mode} mode Segment mode + * @param {String} str String to process + * @return {Array} Array of object with segments data + */ +function getSegments (regex, mode, str) { + const segments = [] + let result + + while ((result = regex.exec(str)) !== null) { + segments.push({ + data: result[0], + index: result.index, + mode: mode, + length: result[0].length + }) + } + + return segments +} + +/** + * Extracts a series of segments with the appropriate + * modes from a string + * + * @param {String} dataStr Input string + * @return {Array} Array of object with segments data + */ +function getSegmentsFromString (dataStr) { + const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr) + const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr) + let byteSegs + let kanjiSegs + + if (Utils.isKanjiModeEnabled()) { + byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr) + kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr) + } else { + byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr) + kanjiSegs = [] + } + + const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs) + + return segs + .sort(function (s1, s2) { + return s1.index - s2.index + }) + .map(function (obj) { + return { + data: obj.data, + mode: obj.mode, + length: obj.length + } + }) +} + +/** + * Returns how many bits are needed to encode a string of + * specified length with the specified mode + * + * @param {Number} length String length + * @param {Mode} mode Segment mode + * @return {Number} Bit length + */ +function getSegmentBitsLength (length, mode) { + switch (mode) { + case Mode.NUMERIC: + return NumericData.getBitsLength(length) + case Mode.ALPHANUMERIC: + return AlphanumericData.getBitsLength(length) + case Mode.KANJI: + return KanjiData.getBitsLength(length) + case Mode.BYTE: + return ByteData.getBitsLength(length) + } +} + +/** + * Merges adjacent segments which have the same mode + * + * @param {Array} segs Array of object with segments data + * @return {Array} Array of object with segments data + */ +function mergeSegments (segs) { + return segs.reduce(function (acc, curr) { + const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null + if (prevSeg && prevSeg.mode === curr.mode) { + acc[acc.length - 1].data += curr.data + return acc + } + + acc.push(curr) + return acc + }, []) +} + +/** + * Generates a list of all possible nodes combination which + * will be used to build a segments graph. + * + * Nodes are divided by groups. Each group will contain a list of all the modes + * in which is possible to encode the given text. + * + * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte. + * The group for '12345' will contain then 3 objects, one for each + * possible encoding mode. + * + * Each node represents a possible segment. + * + * @param {Array} segs Array of object with segments data + * @return {Array} Array of object with segments data + */ +function buildNodes (segs) { + const nodes = [] + for (let i = 0; i < segs.length; i++) { + const seg = segs[i] + + switch (seg.mode) { + case Mode.NUMERIC: + nodes.push([seg, + { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length }, + { data: seg.data, mode: Mode.BYTE, length: seg.length } + ]) + break + case Mode.ALPHANUMERIC: + nodes.push([seg, + { data: seg.data, mode: Mode.BYTE, length: seg.length } + ]) + break + case Mode.KANJI: + nodes.push([seg, + { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } + ]) + break + case Mode.BYTE: + nodes.push([ + { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) } + ]) + } + } + + return nodes +} + +/** + * Builds a graph from a list of nodes. + * All segments in each node group will be connected with all the segments of + * the next group and so on. + * + * At each connection will be assigned a weight depending on the + * segment's byte length. + * + * @param {Array} nodes Array of object with segments data + * @param {Number} version QR Code version + * @return {Object} Graph of all possible segments + */ +function buildGraph (nodes, version) { + const table = {} + const graph = { start: {} } + let prevNodeIds = ['start'] + + for (let i = 0; i < nodes.length; i++) { + const nodeGroup = nodes[i] + const currentNodeIds = [] + + for (let j = 0; j < nodeGroup.length; j++) { + const node = nodeGroup[j] + const key = '' + i + j + + currentNodeIds.push(key) + table[key] = { node: node, lastCount: 0 } + graph[key] = {} + + for (let n = 0; n < prevNodeIds.length; n++) { + const prevNodeId = prevNodeIds[n] + + if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) { + graph[prevNodeId][key] = + getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) - + getSegmentBitsLength(table[prevNodeId].lastCount, node.mode) + + table[prevNodeId].lastCount += node.length + } else { + if (table[prevNodeId]) table[prevNodeId].lastCount = node.length + + graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + + 4 + Mode.getCharCountIndicator(node.mode, version) // switch cost + } + } + } + + prevNodeIds = currentNodeIds + } + + for (let n = 0; n < prevNodeIds.length; n++) { + graph[prevNodeIds[n]].end = 0 + } + + return { map: graph, table: table } +} + +/** + * Builds a segment from a specified data and mode. + * If a mode is not specified, the more suitable will be used. + * + * @param {String} data Input data + * @param {Mode | String} modesHint Data mode + * @return {Segment} Segment + */ +function buildSingleSegment (data, modesHint) { + let mode + const bestMode = Mode.getBestModeForData(data) + + mode = Mode.from(modesHint, bestMode) + + // Make sure data can be encoded + if (mode !== Mode.BYTE && mode.bit < bestMode.bit) { + throw new Error('"' + data + '"' + + ' cannot be encoded with mode ' + Mode.toString(mode) + + '.\n Suggested mode is: ' + Mode.toString(bestMode)) + } + + // Use Mode.BYTE if Kanji support is disabled + if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) { + mode = Mode.BYTE + } + + switch (mode) { + case Mode.NUMERIC: + return new NumericData(data) + + case Mode.ALPHANUMERIC: + return new AlphanumericData(data) + + case Mode.KANJI: + return new KanjiData(data) + + case Mode.BYTE: + return new ByteData(data) + } +} + +/** + * Builds a list of segments from an array. + * Array can contain Strings or Objects with segment's info. + * + * For each item which is a string, will be generated a segment with the given + * string and the more appropriate encoding mode. + * + * For each item which is an object, will be generated a segment with the given + * data and mode. + * Objects must contain at least the property "data". + * If property "mode" is not present, the more suitable mode will be used. + * + * @param {Array} array Array of objects with segments data + * @return {Array} Array of Segments + */ +exports.fromArray = function fromArray (array) { + return array.reduce(function (acc, seg) { + if (typeof seg === 'string') { + acc.push(buildSingleSegment(seg, null)) + } else if (seg.data) { + acc.push(buildSingleSegment(seg.data, seg.mode)) + } + + return acc + }, []) +} + +/** + * Builds an optimized sequence of segments from a string, + * which will produce the shortest possible bitstream. + * + * @param {String} data Input string + * @param {Number} version QR Code version + * @return {Array} Array of segments + */ +exports.fromString = function fromString (data, version) { + const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled()) + + const nodes = buildNodes(segs) + const graph = buildGraph(nodes, version) + const path = dijkstra.find_path(graph.map, 'start', 'end') + + const optimizedSegs = [] + for (let i = 1; i < path.length - 1; i++) { + optimizedSegs.push(graph.table[path[i]].node) + } + + return exports.fromArray(mergeSegments(optimizedSegs)) +} + +/** + * Splits a string in various segments with the modes which + * best represent their content. + * The produced segments are far from being optimized. + * The output of this function is only used to estimate a QR Code version + * which may contain the data. + * + * @param {string} data Input string + * @return {Array} Array of segments + */ +exports.rawSplit = function rawSplit (data) { + return exports.fromArray( + getSegmentsFromString(data, Utils.isKanjiModeEnabled()) + ) +} diff --git a/node_modules/qrcode/lib/core/utils.js b/node_modules/qrcode/lib/core/utils.js new file mode 100644 index 0000000..8a0b87b --- /dev/null +++ b/node_modules/qrcode/lib/core/utils.js @@ -0,0 +1,63 @@ +let toSJISFunction +const CODEWORDS_COUNT = [ + 0, // Not used + 26, 44, 70, 100, 134, 172, 196, 242, 292, 346, + 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085, + 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185, + 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706 +] + +/** + * Returns the QR Code size for the specified version + * + * @param {Number} version QR Code version + * @return {Number} size of QR code + */ +exports.getSymbolSize = function getSymbolSize (version) { + if (!version) throw new Error('"version" cannot be null or undefined') + if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40') + return version * 4 + 17 +} + +/** + * Returns the total number of codewords used to store data and EC information. + * + * @param {Number} version QR Code version + * @return {Number} Data length in bits + */ +exports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) { + return CODEWORDS_COUNT[version] +} + +/** + * Encode data with Bose-Chaudhuri-Hocquenghem + * + * @param {Number} data Value to encode + * @return {Number} Encoded value + */ +exports.getBCHDigit = function (data) { + let digit = 0 + + while (data !== 0) { + digit++ + data >>>= 1 + } + + return digit +} + +exports.setToSJISFunction = function setToSJISFunction (f) { + if (typeof f !== 'function') { + throw new Error('"toSJISFunc" is not a valid function.') + } + + toSJISFunction = f +} + +exports.isKanjiModeEnabled = function () { + return typeof toSJISFunction !== 'undefined' +} + +exports.toSJIS = function toSJIS (kanji) { + return toSJISFunction(kanji) +} diff --git a/node_modules/qrcode/lib/core/version-check.js b/node_modules/qrcode/lib/core/version-check.js new file mode 100644 index 0000000..dd32b5a --- /dev/null +++ b/node_modules/qrcode/lib/core/version-check.js @@ -0,0 +1,9 @@ +/** + * Check if QR Code version is valid + * + * @param {Number} version QR Code version + * @return {Boolean} true if valid version, false otherwise + */ +exports.isValid = function isValid (version) { + return !isNaN(version) && version >= 1 && version <= 40 +} diff --git a/node_modules/qrcode/lib/core/version.js b/node_modules/qrcode/lib/core/version.js new file mode 100644 index 0000000..32b8466 --- /dev/null +++ b/node_modules/qrcode/lib/core/version.js @@ -0,0 +1,163 @@ +const Utils = require('./utils') +const ECCode = require('./error-correction-code') +const ECLevel = require('./error-correction-level') +const Mode = require('./mode') +const VersionCheck = require('./version-check') + +// Generator polynomial used to encode version information +const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0) +const G18_BCH = Utils.getBCHDigit(G18) + +function getBestVersionForDataLength (mode, length, errorCorrectionLevel) { + for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { + if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) { + return currentVersion + } + } + + return undefined +} + +function getReservedBitsCount (mode, version) { + // Character count indicator + mode indicator bits + return Mode.getCharCountIndicator(mode, version) + 4 +} + +function getTotalBitsFromDataArray (segments, version) { + let totalBits = 0 + + segments.forEach(function (data) { + const reservedBits = getReservedBitsCount(data.mode, version) + totalBits += reservedBits + data.getBitsLength() + }) + + return totalBits +} + +function getBestVersionForMixedData (segments, errorCorrectionLevel) { + for (let currentVersion = 1; currentVersion <= 40; currentVersion++) { + const length = getTotalBitsFromDataArray(segments, currentVersion) + if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) { + return currentVersion + } + } + + return undefined +} + +/** + * Returns version number from a value. + * If value is not a valid version, returns defaultValue + * + * @param {Number|String} value QR Code version + * @param {Number} defaultValue Fallback value + * @return {Number} QR Code version number + */ +exports.from = function from (value, defaultValue) { + if (VersionCheck.isValid(value)) { + return parseInt(value, 10) + } + + return defaultValue +} + +/** + * Returns how much data can be stored with the specified QR code version + * and error correction level + * + * @param {Number} version QR Code version (1-40) + * @param {Number} errorCorrectionLevel Error correction level + * @param {Mode} mode Data mode + * @return {Number} Quantity of storable data + */ +exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) { + if (!VersionCheck.isValid(version)) { + throw new Error('Invalid QR Code version') + } + + // Use Byte mode as default + if (typeof mode === 'undefined') mode = Mode.BYTE + + // Total codewords for this QR code version (Data + Error correction) + const totalCodewords = Utils.getSymbolTotalCodewords(version) + + // Total number of error correction codewords + const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel) + + // Total number of data codewords + const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8 + + if (mode === Mode.MIXED) return dataTotalCodewordsBits + + const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version) + + // Return max number of storable codewords + switch (mode) { + case Mode.NUMERIC: + return Math.floor((usableBits / 10) * 3) + + case Mode.ALPHANUMERIC: + return Math.floor((usableBits / 11) * 2) + + case Mode.KANJI: + return Math.floor(usableBits / 13) + + case Mode.BYTE: + default: + return Math.floor(usableBits / 8) + } +} + +/** + * Returns the minimum version needed to contain the amount of data + * + * @param {Segment} data Segment of data + * @param {Number} [errorCorrectionLevel=H] Error correction level + * @param {Mode} mode Data mode + * @return {Number} QR Code version + */ +exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) { + let seg + + const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M) + + if (Array.isArray(data)) { + if (data.length > 1) { + return getBestVersionForMixedData(data, ecl) + } + + if (data.length === 0) { + return 1 + } + + seg = data[0] + } else { + seg = data + } + + return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl) +} + +/** + * Returns version information with relative error correction bits + * + * The version information is included in QR Code symbols of version 7 or larger. + * It consists of an 18-bit sequence containing 6 data bits, + * with 12 error correction bits calculated using the (18, 6) Golay code. + * + * @param {Number} version QR Code version + * @return {Number} Encoded version info bits + */ +exports.getEncodedBits = function getEncodedBits (version) { + if (!VersionCheck.isValid(version) || version < 7) { + throw new Error('Invalid QR Code version') + } + + let d = version << 12 + + while (Utils.getBCHDigit(d) - G18_BCH >= 0) { + d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH)) + } + + return (version << 12) | d +} diff --git a/node_modules/qrcode/lib/index.js b/node_modules/qrcode/lib/index.js new file mode 100644 index 0000000..57c8f70 --- /dev/null +++ b/node_modules/qrcode/lib/index.js @@ -0,0 +1,12 @@ +/* +*copyright Ryan Day 2012 +* +* Licensed under the MIT license: +* http://www.opensource.org/licenses/mit-license.php +* +* this is the main server side application file for node-qrcode. +* these exports use serverside canvas api methods for file IO and buffers +* +*/ + +module.exports = require('./server') diff --git a/node_modules/qrcode/lib/renderer/canvas.js b/node_modules/qrcode/lib/renderer/canvas.js new file mode 100644 index 0000000..42050cf --- /dev/null +++ b/node_modules/qrcode/lib/renderer/canvas.js @@ -0,0 +1,63 @@ +const Utils = require('./utils') + +function clearCanvas (ctx, canvas, size) { + ctx.clearRect(0, 0, canvas.width, canvas.height) + + if (!canvas.style) canvas.style = {} + canvas.height = size + canvas.width = size + canvas.style.height = size + 'px' + canvas.style.width = size + 'px' +} + +function getCanvasElement () { + try { + return document.createElement('canvas') + } catch (e) { + throw new Error('You need to specify a canvas element') + } +} + +exports.render = function render (qrData, canvas, options) { + let opts = options + let canvasEl = canvas + + if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) { + opts = canvas + canvas = undefined + } + + if (!canvas) { + canvasEl = getCanvasElement() + } + + opts = Utils.getOptions(opts) + const size = Utils.getImageWidth(qrData.modules.size, opts) + + const ctx = canvasEl.getContext('2d') + const image = ctx.createImageData(size, size) + Utils.qrToImageData(image.data, qrData, opts) + + clearCanvas(ctx, canvasEl, size) + ctx.putImageData(image, 0, 0) + + return canvasEl +} + +exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) { + let opts = options + + if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) { + opts = canvas + canvas = undefined + } + + if (!opts) opts = {} + + const canvasEl = exports.render(qrData, canvas, opts) + + const type = opts.type || 'image/png' + const rendererOpts = opts.rendererOpts || {} + + return canvasEl.toDataURL(type, rendererOpts.quality) +} diff --git a/node_modules/qrcode/lib/renderer/png.js b/node_modules/qrcode/lib/renderer/png.js new file mode 100644 index 0000000..2742160 --- /dev/null +++ b/node_modules/qrcode/lib/renderer/png.js @@ -0,0 +1,78 @@ +const fs = require('fs') +const PNG = require('pngjs').PNG +const Utils = require('./utils') + +exports.render = function render (qrData, options) { + const opts = Utils.getOptions(options) + const pngOpts = opts.rendererOpts + const size = Utils.getImageWidth(qrData.modules.size, opts) + + pngOpts.width = size + pngOpts.height = size + + const pngImage = new PNG(pngOpts) + Utils.qrToImageData(pngImage.data, qrData, opts) + + return pngImage +} + +exports.renderToDataURL = function renderToDataURL (qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } + + exports.renderToBuffer(qrData, options, function (err, output) { + if (err) cb(err) + let url = 'data:image/png;base64,' + url += output.toString('base64') + cb(null, url) + }) +} + +exports.renderToBuffer = function renderToBuffer (qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } + + const png = exports.render(qrData, options) + const buffer = [] + + png.on('error', cb) + + png.on('data', function (data) { + buffer.push(data) + }) + + png.on('end', function () { + cb(null, Buffer.concat(buffer)) + }) + + png.pack() +} + +exports.renderToFile = function renderToFile (path, qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } + + let called = false + const done = (...args) => { + if (called) return + called = true + cb.apply(null, args) + } + const stream = fs.createWriteStream(path) + + stream.on('error', done) + stream.on('close', done) + + exports.renderToFileStream(stream, qrData, options) +} + +exports.renderToFileStream = function renderToFileStream (stream, qrData, options) { + const png = exports.render(qrData, options) + png.pack().pipe(stream) +} diff --git a/node_modules/qrcode/lib/renderer/svg-tag.js b/node_modules/qrcode/lib/renderer/svg-tag.js new file mode 100644 index 0000000..d0839fe --- /dev/null +++ b/node_modules/qrcode/lib/renderer/svg-tag.js @@ -0,0 +1,81 @@ +const Utils = require('./utils') + +function getColorAttrib (color, attrib) { + const alpha = color.a / 255 + const str = attrib + '="' + color.hex + '"' + + return alpha < 1 + ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"' + : str +} + +function svgCmd (cmd, x, y) { + let str = cmd + x + if (typeof y !== 'undefined') str += ' ' + y + + return str +} + +function qrToPath (data, size, margin) { + let path = '' + let moveBy = 0 + let newRow = false + let lineLength = 0 + + for (let i = 0; i < data.length; i++) { + const col = Math.floor(i % size) + const row = Math.floor(i / size) + + if (!col && !newRow) newRow = true + + if (data[i]) { + lineLength++ + + if (!(i > 0 && col > 0 && data[i - 1])) { + path += newRow + ? svgCmd('M', col + margin, 0.5 + row + margin) + : svgCmd('m', moveBy, 0) + + moveBy = 0 + newRow = false + } + + if (!(col + 1 < size && data[i + 1])) { + path += svgCmd('h', lineLength) + lineLength = 0 + } + } else { + moveBy++ + } + } + + return path +} + +exports.render = function render (qrData, options, cb) { + const opts = Utils.getOptions(options) + const size = qrData.modules.size + const data = qrData.modules.data + const qrcodesize = size + opts.margin * 2 + + const bg = !opts.color.light.a + ? '' + : '' + + const path = + '' + + const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"' + + const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ' + + const svgTag = '' + bg + path + '\n' + + if (typeof cb === 'function') { + cb(null, svgTag) + } + + return svgTag +} diff --git a/node_modules/qrcode/lib/renderer/svg.js b/node_modules/qrcode/lib/renderer/svg.js new file mode 100644 index 0000000..ba99d14 --- /dev/null +++ b/node_modules/qrcode/lib/renderer/svg.js @@ -0,0 +1,19 @@ +const svgTagRenderer = require('./svg-tag') + +exports.render = svgTagRenderer.render + +exports.renderToFile = function renderToFile (path, qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } + + const fs = require('fs') + const svgTag = exports.render(qrData, options) + + const xmlStr = '' + + '' + + svgTag + + fs.writeFile(path, xmlStr, cb) +} diff --git a/node_modules/qrcode/lib/renderer/terminal.js b/node_modules/qrcode/lib/renderer/terminal.js new file mode 100644 index 0000000..36ddfde --- /dev/null +++ b/node_modules/qrcode/lib/renderer/terminal.js @@ -0,0 +1,9 @@ +const big = require('./terminal/terminal') +const small = require('./terminal/terminal-small') + +exports.render = function (qrData, options, cb) { + if (options && options.small) { + return small.render(qrData, options, cb) + } + return big.render(qrData, options, cb) +} diff --git a/node_modules/qrcode/lib/renderer/terminal/terminal-small.js b/node_modules/qrcode/lib/renderer/terminal/terminal-small.js new file mode 100644 index 0000000..9810d4e --- /dev/null +++ b/node_modules/qrcode/lib/renderer/terminal/terminal-small.js @@ -0,0 +1,85 @@ +const backgroundWhite = '\x1b[47m' +const backgroundBlack = '\x1b[40m' +const foregroundWhite = '\x1b[37m' +const foregroundBlack = '\x1b[30m' +const reset = '\x1b[0m' +const lineSetupNormal = backgroundWhite + foregroundBlack // setup colors +const lineSetupInverse = backgroundBlack + foregroundWhite // setup colors + +const createPalette = function (lineSetup, foregroundWhite, foregroundBlack) { + return { + // 1 ... white, 2 ... black, 0 ... transparent (default) + + '00': reset + ' ' + lineSetup, + '01': reset + foregroundWhite + '▄' + lineSetup, + '02': reset + foregroundBlack + '▄' + lineSetup, + 10: reset + foregroundWhite + '▀' + lineSetup, + 11: ' ', + 12: '▄', + 20: reset + foregroundBlack + '▀' + lineSetup, + 21: '▀', + 22: '█' + } +} + +/** + * Returns code for QR pixel + * @param {boolean[][]} modules + * @param {number} size + * @param {number} x + * @param {number} y + * @return {'0' | '1' | '2'} + */ +const mkCodePixel = function (modules, size, x, y) { + const sizePlus = size + 1 + if ((x >= sizePlus) || (y >= sizePlus) || (y < -1) || (x < -1)) return '0' + if ((x >= size) || (y >= size) || (y < 0) || (x < 0)) return '1' + const idx = (y * size) + x + return modules[idx] ? '2' : '1' +} + +/** + * Returns code for four QR pixels. Suitable as key in palette. + * @param {boolean[][]} modules + * @param {number} size + * @param {number} x + * @param {number} y + * @return {keyof palette} + */ +const mkCode = function (modules, size, x, y) { + return ( + mkCodePixel(modules, size, x, y) + + mkCodePixel(modules, size, x, y + 1) + ) +} + +exports.render = function (qrData, options, cb) { + const size = qrData.modules.size + const data = qrData.modules.data + + const inverse = !!(options && options.inverse) + const lineSetup = options && options.inverse ? lineSetupInverse : lineSetupNormal + const white = inverse ? foregroundBlack : foregroundWhite + const black = inverse ? foregroundWhite : foregroundBlack + + const palette = createPalette(lineSetup, white, black) + const newLine = reset + '\n' + lineSetup + + let output = lineSetup // setup colors + + for (let y = -1; y < size + 1; y += 2) { + for (let x = -1; x < size; x++) { + output += palette[mkCode(data, size, x, y)] + } + + output += palette[mkCode(data, size, size, y)] + newLine + } + + output += reset + + if (typeof cb === 'function') { + cb(null, output) + } + + return output +} diff --git a/node_modules/qrcode/lib/renderer/terminal/terminal.js b/node_modules/qrcode/lib/renderer/terminal/terminal.js new file mode 100644 index 0000000..f15610b --- /dev/null +++ b/node_modules/qrcode/lib/renderer/terminal/terminal.js @@ -0,0 +1,49 @@ +// let Utils = require('./utils') + +exports.render = function (qrData, options, cb) { + const size = qrData.modules.size + const data = qrData.modules.data + + // let opts = Utils.getOptions(options) + + // use same scheme as https://github.com/gtanner/qrcode-terminal because it actually works! =) + const black = '\x1b[40m \x1b[0m' + const white = '\x1b[47m \x1b[0m' + + let output = '' + const hMargin = Array(size + 3).join(white) + const vMargin = Array(2).join(white) + + output += hMargin + '\n' + for (let i = 0; i < size; ++i) { + output += white + for (let j = 0; j < size; j++) { + // let topModule = data[i * size + j] + // let bottomModule = data[(i + 1) * size + j] + + output += data[i * size + j] ? black : white// getBlockChar(topModule, bottomModule) + } + // output += white+'\n' + output += vMargin + '\n' + } + + output += hMargin + '\n' + + if (typeof cb === 'function') { + cb(null, output) + } + + return output +} +/* +exports.renderToFile = function renderToFile (path, qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } + + let fs = require('fs') + let utf8 = exports.render(qrData, options) + fs.writeFile(path, utf8, cb) +} +*/ diff --git a/node_modules/qrcode/lib/renderer/utf8.js b/node_modules/qrcode/lib/renderer/utf8.js new file mode 100644 index 0000000..d76116e --- /dev/null +++ b/node_modules/qrcode/lib/renderer/utf8.js @@ -0,0 +1,71 @@ +const Utils = require('./utils') + +const BLOCK_CHAR = { + WW: ' ', + WB: '▄', + BB: '█', + BW: '▀' +} + +const INVERTED_BLOCK_CHAR = { + BB: ' ', + BW: '▄', + WW: '█', + WB: '▀' +} + +function getBlockChar (top, bottom, blocks) { + if (top && bottom) return blocks.BB + if (top && !bottom) return blocks.BW + if (!top && bottom) return blocks.WB + return blocks.WW +} + +exports.render = function (qrData, options, cb) { + const opts = Utils.getOptions(options) + let blocks = BLOCK_CHAR + if (opts.color.dark.hex === '#ffffff' || opts.color.light.hex === '#000000') { + blocks = INVERTED_BLOCK_CHAR + } + + const size = qrData.modules.size + const data = qrData.modules.data + + let output = '' + let hMargin = Array(size + (opts.margin * 2) + 1).join(blocks.WW) + hMargin = Array((opts.margin / 2) + 1).join(hMargin + '\n') + + const vMargin = Array(opts.margin + 1).join(blocks.WW) + + output += hMargin + for (let i = 0; i < size; i += 2) { + output += vMargin + for (let j = 0; j < size; j++) { + const topModule = data[i * size + j] + const bottomModule = data[(i + 1) * size + j] + + output += getBlockChar(topModule, bottomModule, blocks) + } + + output += vMargin + '\n' + } + + output += hMargin.slice(0, -1) + + if (typeof cb === 'function') { + cb(null, output) + } + + return output +} + +exports.renderToFile = function renderToFile (path, qrData, options, cb) { + if (typeof cb === 'undefined') { + cb = options + options = undefined + } + + const fs = require('fs') + const utf8 = exports.render(qrData, options) + fs.writeFile(path, utf8, cb) +} diff --git a/node_modules/qrcode/lib/renderer/utils.js b/node_modules/qrcode/lib/renderer/utils.js new file mode 100644 index 0000000..87239dc --- /dev/null +++ b/node_modules/qrcode/lib/renderer/utils.js @@ -0,0 +1,99 @@ +function hex2rgba (hex) { + if (typeof hex === 'number') { + hex = hex.toString() + } + + if (typeof hex !== 'string') { + throw new Error('Color should be defined as hex string') + } + + let hexCode = hex.slice().replace('#', '').split('') + if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) { + throw new Error('Invalid hex color: ' + hex) + } + + // Convert from short to long form (fff -> ffffff) + if (hexCode.length === 3 || hexCode.length === 4) { + hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) { + return [c, c] + })) + } + + // Add default alpha value + if (hexCode.length === 6) hexCode.push('F', 'F') + + const hexValue = parseInt(hexCode.join(''), 16) + + return { + r: (hexValue >> 24) & 255, + g: (hexValue >> 16) & 255, + b: (hexValue >> 8) & 255, + a: hexValue & 255, + hex: '#' + hexCode.slice(0, 6).join('') + } +} + +exports.getOptions = function getOptions (options) { + if (!options) options = {} + if (!options.color) options.color = {} + + const margin = typeof options.margin === 'undefined' || + options.margin === null || + options.margin < 0 + ? 4 + : options.margin + + const width = options.width && options.width >= 21 ? options.width : undefined + const scale = options.scale || 4 + + return { + width: width, + scale: width ? 4 : scale, + margin: margin, + color: { + dark: hex2rgba(options.color.dark || '#000000ff'), + light: hex2rgba(options.color.light || '#ffffffff') + }, + type: options.type, + rendererOpts: options.rendererOpts || {} + } +} + +exports.getScale = function getScale (qrSize, opts) { + return opts.width && opts.width >= qrSize + opts.margin * 2 + ? opts.width / (qrSize + opts.margin * 2) + : opts.scale +} + +exports.getImageWidth = function getImageWidth (qrSize, opts) { + const scale = exports.getScale(qrSize, opts) + return Math.floor((qrSize + opts.margin * 2) * scale) +} + +exports.qrToImageData = function qrToImageData (imgData, qr, opts) { + const size = qr.modules.size + const data = qr.modules.data + const scale = exports.getScale(size, opts) + const symbolSize = Math.floor((size + opts.margin * 2) * scale) + const scaledMargin = opts.margin * scale + const palette = [opts.color.light, opts.color.dark] + + for (let i = 0; i < symbolSize; i++) { + for (let j = 0; j < symbolSize; j++) { + let posDst = (i * symbolSize + j) * 4 + let pxColor = opts.color.light + + if (i >= scaledMargin && j >= scaledMargin && + i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) { + const iSrc = Math.floor((i - scaledMargin) / scale) + const jSrc = Math.floor((j - scaledMargin) / scale) + pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0] + } + + imgData[posDst++] = pxColor.r + imgData[posDst++] = pxColor.g + imgData[posDst++] = pxColor.b + imgData[posDst] = pxColor.a + } + } +} diff --git a/node_modules/qrcode/lib/server.js b/node_modules/qrcode/lib/server.js new file mode 100644 index 0000000..619e398 --- /dev/null +++ b/node_modules/qrcode/lib/server.js @@ -0,0 +1,138 @@ +const canPromise = require('./can-promise') +const QRCode = require('./core/qrcode') +const PngRenderer = require('./renderer/png') +const Utf8Renderer = require('./renderer/utf8') +const TerminalRenderer = require('./renderer/terminal') +const SvgRenderer = require('./renderer/svg') + +function checkParams (text, opts, cb) { + if (typeof text === 'undefined') { + throw new Error('String required as first argument') + } + + if (typeof cb === 'undefined') { + cb = opts + opts = {} + } + + if (typeof cb !== 'function') { + if (!canPromise()) { + throw new Error('Callback required as last argument') + } else { + opts = cb || {} + cb = null + } + } + + return { + opts: opts, + cb: cb + } +} + +function getTypeFromFilename (path) { + return path.slice((path.lastIndexOf('.') - 1 >>> 0) + 2).toLowerCase() +} + +function getRendererFromType (type) { + switch (type) { + case 'svg': + return SvgRenderer + + case 'txt': + case 'utf8': + return Utf8Renderer + + case 'png': + case 'image/png': + default: + return PngRenderer + } +} + +function getStringRendererFromType (type) { + switch (type) { + case 'svg': + return SvgRenderer + + case 'terminal': + return TerminalRenderer + + case 'utf8': + default: + return Utf8Renderer + } +} + +function render (renderFunc, text, params) { + if (!params.cb) { + return new Promise(function (resolve, reject) { + try { + const data = QRCode.create(text, params.opts) + return renderFunc(data, params.opts, function (err, data) { + return err ? reject(err) : resolve(data) + }) + } catch (e) { + reject(e) + } + }) + } + + try { + const data = QRCode.create(text, params.opts) + return renderFunc(data, params.opts, params.cb) + } catch (e) { + params.cb(e) + } +} + +exports.create = QRCode.create + +exports.toCanvas = require('./browser').toCanvas + +exports.toString = function toString (text, opts, cb) { + const params = checkParams(text, opts, cb) + const type = params.opts ? params.opts.type : undefined + const renderer = getStringRendererFromType(type) + return render(renderer.render, text, params) +} + +exports.toDataURL = function toDataURL (text, opts, cb) { + const params = checkParams(text, opts, cb) + const renderer = getRendererFromType(params.opts.type) + return render(renderer.renderToDataURL, text, params) +} + +exports.toBuffer = function toBuffer (text, opts, cb) { + const params = checkParams(text, opts, cb) + const renderer = getRendererFromType(params.opts.type) + return render(renderer.renderToBuffer, text, params) +} + +exports.toFile = function toFile (path, text, opts, cb) { + if (typeof path !== 'string' || !(typeof text === 'string' || typeof text === 'object')) { + throw new Error('Invalid argument') + } + + if ((arguments.length < 3) && !canPromise()) { + throw new Error('Too few arguments provided') + } + + const params = checkParams(text, opts, cb) + const type = params.opts.type || getTypeFromFilename(path) + const renderer = getRendererFromType(type) + const renderToFile = renderer.renderToFile.bind(null, path) + + return render(renderToFile, text, params) +} + +exports.toFileStream = function toFileStream (stream, text, opts) { + if (arguments.length < 2) { + throw new Error('Too few arguments provided') + } + + const params = checkParams(text, opts, stream.emit.bind(stream, 'error')) + const renderer = getRendererFromType('png') // Only png support for now + const renderToFileStream = renderer.renderToFileStream.bind(null, stream) + render(renderToFileStream, text, params) +} diff --git a/node_modules/qrcode/license b/node_modules/qrcode/license new file mode 100644 index 0000000..4e2b3b9 --- /dev/null +++ b/node_modules/qrcode/license @@ -0,0 +1,10 @@ +The MIT License (MIT) + +Copyright (c) 2012 Ryan Day + +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/node_modules/qrcode/package.json b/node_modules/qrcode/package.json new file mode 100644 index 0000000..6c9ab00 --- /dev/null +++ b/node_modules/qrcode/package.json @@ -0,0 +1,77 @@ +{ + "name": "qrcode", + "description": "QRCode / 2d Barcode api with both server side and client side support using canvas", + "version": "1.5.4", + "author": "Ryan Day ", + "contributors": [ + "Vincenzo Greco ", + "Linus Unnebäck " + ], + "keywords": [ + "qr", + "code", + "canvas", + "qrcode" + ], + "main": "./lib/index.js", + "browser": { + "./lib/index.js": "./lib/browser.js", + "fs": false + }, + "files": [ + "bin", + "build", + "lib", + "helper" + ], + "homepage": "http://github.com/soldair/node-qrcode", + "license": "MIT", + "scripts": { + "lint": "standard", + "pretest": "npm run lint", + "test": "node --throw-deprecation test.js", + "build": "rollup -c", + "prepublish": "npm run build", + "browser": "node examples/clientsideserver.js" + }, + "bin": { + "qrcode": "./bin/qrcode" + }, + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "devDependencies": { + "@babel/core": "^7.9.0", + "@babel/preset-env": "^7.9.5", + "@rollup/plugin-commonjs": "^11.1.0", + "@rollup/plugin-node-resolve": "^7.1.3", + "browserify": "^16.5.1", + "canvas": "^2.8.0", + "canvasutil": "0.0.4", + "colors": "^1.4.0", + "express": "^4.17.1", + "htmlparser2": "^4.1.0", + "rollup": "^2.6.1", + "rollup-plugin-babel": "^4.4.0", + "rollup-plugin-terser": "^5.3.0", + "sinon": "^9.0.2", + "standard": "^16.0.4", + "tap": "^16.2.0" + }, + "repository": { + "type": "git", + "url": "git://github.com/soldair/node-qrcode.git" + }, + "engines": { + "node": ">=10.13.0" + }, + "standard": { + "ignore": [ + "build/", + "examples/vendors/", + "lib/core/regex.js" + ] + } +} diff --git a/node_modules/require-directory/.jshintrc b/node_modules/require-directory/.jshintrc new file mode 100644 index 0000000..e14e4dc --- /dev/null +++ b/node_modules/require-directory/.jshintrc @@ -0,0 +1,67 @@ +{ + "maxerr" : 50, + "bitwise" : true, + "camelcase" : true, + "curly" : true, + "eqeqeq" : true, + "forin" : true, + "immed" : true, + "indent" : 2, + "latedef" : true, + "newcap" : true, + "noarg" : true, + "noempty" : true, + "nonew" : true, + "plusplus" : true, + "quotmark" : true, + "undef" : true, + "unused" : true, + "strict" : true, + "trailing" : true, + "maxparams" : false, + "maxdepth" : false, + "maxstatements" : false, + "maxcomplexity" : false, + "maxlen" : false, + "asi" : false, + "boss" : false, + "debug" : false, + "eqnull" : true, + "es5" : false, + "esnext" : false, + "moz" : false, + "evil" : false, + "expr" : true, + "funcscope" : true, + "globalstrict" : true, + "iterator" : true, + "lastsemic" : false, + "laxbreak" : false, + "laxcomma" : false, + "loopfunc" : false, + "multistr" : false, + "proto" : false, + "scripturl" : false, + "smarttabs" : false, + "shadow" : false, + "sub" : false, + "supernew" : false, + "validthis" : false, + "browser" : true, + "couch" : false, + "devel" : true, + "dojo" : false, + "jquery" : false, + "mootools" : false, + "node" : true, + "nonstandard" : false, + "prototypejs" : false, + "rhino" : false, + "worker" : false, + "wsh" : false, + "yui" : false, + "nomen" : true, + "onevar" : true, + "passfail" : false, + "white" : true +} diff --git a/node_modules/require-directory/.npmignore b/node_modules/require-directory/.npmignore new file mode 100644 index 0000000..47cf365 --- /dev/null +++ b/node_modules/require-directory/.npmignore @@ -0,0 +1 @@ +test/** diff --git a/node_modules/require-directory/.travis.yml b/node_modules/require-directory/.travis.yml new file mode 100644 index 0000000..20fd86b --- /dev/null +++ b/node_modules/require-directory/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 0.10 diff --git a/node_modules/require-directory/LICENSE b/node_modules/require-directory/LICENSE new file mode 100644 index 0000000..a70f253 --- /dev/null +++ b/node_modules/require-directory/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2011 Troy Goode + +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/node_modules/require-directory/README.markdown b/node_modules/require-directory/README.markdown new file mode 100644 index 0000000..926a063 --- /dev/null +++ b/node_modules/require-directory/README.markdown @@ -0,0 +1,184 @@ +# require-directory + +Recursively iterates over specified directory, `require()`'ing each file, and returning a nested hash structure containing those modules. + +**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)** + +[![NPM](https://nodei.co/npm/require-directory.png?downloads=true&stars=true)](https://nodei.co/npm/require-directory/) + +[![build status](https://secure.travis-ci.org/troygoode/node-require-directory.png)](http://travis-ci.org/troygoode/node-require-directory) + +## How To Use + +### Installation (via [npm](https://npmjs.org/package/require-directory)) + +```bash +$ npm install require-directory +``` + +### Usage + +A common pattern in node.js is to include an index file which creates a hash of the files in its current directory. Given a directory structure like so: + +* app.js +* routes/ + * index.js + * home.js + * auth/ + * login.js + * logout.js + * register.js + +`routes/index.js` uses `require-directory` to build the hash (rather than doing so manually) like so: + +```javascript +var requireDirectory = require('require-directory'); +module.exports = requireDirectory(module); +``` + +`app.js` references `routes/index.js` like any other module, but it now has a hash/tree of the exports from the `./routes/` directory: + +```javascript +var routes = require('./routes'); + +// snip + +app.get('/', routes.home); +app.get('/register', routes.auth.register); +app.get('/login', routes.auth.login); +app.get('/logout', routes.auth.logout); +``` + +The `routes` variable above is the equivalent of this: + +```javascript +var routes = { + home: require('routes/home.js'), + auth: { + login: require('routes/auth/login.js'), + logout: require('routes/auth/logout.js'), + register: require('routes/auth/register.js') + } +}; +``` + +*Note that `routes.index` will be `undefined` as you would hope.* + +### Specifying Another Directory + +You can specify which directory you want to build a tree of (if it isn't the current directory for whatever reason) by passing it as the second parameter. Not specifying the path (`requireDirectory(module)`) is the equivelant of `requireDirectory(module, __dirname)`: + +```javascript +var requireDirectory = require('require-directory'); +module.exports = requireDirectory(module, './some/subdirectory'); +``` + +For example, in the [example in the Usage section](#usage) we could have avoided creating `routes/index.js` and instead changed the first lines of `app.js` to: + +```javascript +var requireDirectory = require('require-directory'); +var routes = requireDirectory(module, './routes'); +``` + +## Options + +You can pass an options hash to `require-directory` as the 2nd parameter (or 3rd if you're passing the path to another directory as the 2nd parameter already). Here are the available options: + +### Whitelisting + +Whitelisting (either via RegExp or function) allows you to specify that only certain files be loaded. + +```javascript +var requireDirectory = require('require-directory'), + whitelist = /onlyinclude.js$/, + hash = requireDirectory(module, {include: whitelist}); +``` + +```javascript +var requireDirectory = require('require-directory'), + check = function(path){ + if(/onlyinclude.js$/.test(path)){ + return true; // don't include + }else{ + return false; // go ahead and include + } + }, + hash = requireDirectory(module, {include: check}); +``` + +### Blacklisting + +Blacklisting (either via RegExp or function) allows you to specify that all but certain files should be loaded. + +```javascript +var requireDirectory = require('require-directory'), + blacklist = /dontinclude\.js$/, + hash = requireDirectory(module, {exclude: blacklist}); +``` + +```javascript +var requireDirectory = require('require-directory'), + check = function(path){ + if(/dontinclude\.js$/.test(path)){ + return false; // don't include + }else{ + return true; // go ahead and include + } + }, + hash = requireDirectory(module, {exclude: check}); +``` + +### Visiting Objects As They're Loaded + +`require-directory` takes a function as the `visit` option that will be called for each module that is added to module.exports. + +```javascript +var requireDirectory = require('require-directory'), + visitor = function(obj) { + console.log(obj); // will be called for every module that is loaded + }, + hash = requireDirectory(module, {visit: visitor}); +``` + +The visitor can also transform the objects by returning a value: + +```javascript +var requireDirectory = require('require-directory'), + visitor = function(obj) { + return obj(new Date()); + }, + hash = requireDirectory(module, {visit: visitor}); +``` + +### Renaming Keys + +```javascript +var requireDirectory = require('require-directory'), + renamer = function(name) { + return name.toUpperCase(); + }, + hash = requireDirectory(module, {rename: renamer}); +``` + +### No Recursion + +```javascript +var requireDirectory = require('require-directory'), + hash = requireDirectory(module, {recurse: false}); +``` + +## Run Unit Tests + +```bash +$ npm run lint +$ npm test +``` + +## License + +[MIT License](http://www.opensource.org/licenses/mit-license.php) + +## Author + +[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com)) + diff --git a/node_modules/require-directory/index.js b/node_modules/require-directory/index.js new file mode 100644 index 0000000..cd37da7 --- /dev/null +++ b/node_modules/require-directory/index.js @@ -0,0 +1,86 @@ +'use strict'; + +var fs = require('fs'), + join = require('path').join, + resolve = require('path').resolve, + dirname = require('path').dirname, + defaultOptions = { + extensions: ['js', 'json', 'coffee'], + recurse: true, + rename: function (name) { + return name; + }, + visit: function (obj) { + return obj; + } + }; + +function checkFileInclusion(path, filename, options) { + return ( + // verify file has valid extension + (new RegExp('\\.(' + options.extensions.join('|') + ')$', 'i').test(filename)) && + + // if options.include is a RegExp, evaluate it and make sure the path passes + !(options.include && options.include instanceof RegExp && !options.include.test(path)) && + + // if options.include is a function, evaluate it and make sure the path passes + !(options.include && typeof options.include === 'function' && !options.include(path, filename)) && + + // if options.exclude is a RegExp, evaluate it and make sure the path doesn't pass + !(options.exclude && options.exclude instanceof RegExp && options.exclude.test(path)) && + + // if options.exclude is a function, evaluate it and make sure the path doesn't pass + !(options.exclude && typeof options.exclude === 'function' && options.exclude(path, filename)) + ); +} + +function requireDirectory(m, path, options) { + var retval = {}; + + // path is optional + if (path && !options && typeof path !== 'string') { + options = path; + path = null; + } + + // default options + options = options || {}; + for (var prop in defaultOptions) { + if (typeof options[prop] === 'undefined') { + options[prop] = defaultOptions[prop]; + } + } + + // if no path was passed in, assume the equivelant of __dirname from caller + // otherwise, resolve path relative to the equivalent of __dirname + path = !path ? dirname(m.filename) : resolve(dirname(m.filename), path); + + // get the path of each file in specified directory, append to current tree node, recurse + fs.readdirSync(path).forEach(function (filename) { + var joined = join(path, filename), + files, + key, + obj; + + if (fs.statSync(joined).isDirectory() && options.recurse) { + // this node is a directory; recurse + files = requireDirectory(m, joined, options); + // exclude empty directories + if (Object.keys(files).length) { + retval[options.rename(filename, joined, filename)] = files; + } + } else { + if (joined !== m.filename && checkFileInclusion(joined, filename, options)) { + // hash node key shouldn't include file extension + key = filename.substring(0, filename.lastIndexOf('.')); + obj = m.require(joined); + retval[options.rename(key, joined, filename)] = options.visit(obj, joined, filename) || obj; + } + } + }); + + return retval; +} + +module.exports = requireDirectory; +module.exports.defaults = defaultOptions; diff --git a/node_modules/require-directory/package.json b/node_modules/require-directory/package.json new file mode 100644 index 0000000..25ece4b --- /dev/null +++ b/node_modules/require-directory/package.json @@ -0,0 +1,40 @@ +{ + "author": "Troy Goode (http://github.com/troygoode/)", + "name": "require-directory", + "version": "2.1.1", + "description": "Recursively iterates over specified directory, require()'ing each file, and returning a nested hash structure containing those modules.", + "keywords": [ + "require", + "directory", + "library", + "recursive" + ], + "homepage": "https://github.com/troygoode/node-require-directory/", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/troygoode/node-require-directory.git" + }, + "contributors": [ + { + "name": "Troy Goode", + "email": "troygoode@gmail.com", + "web": "http://github.com/troygoode/" + } + ], + "license": "MIT", + "bugs": { + "url": "http://github.com/troygoode/node-require-directory/issues/" + }, + "engines": { + "node": ">=0.10.0" + }, + "devDependencies": { + "jshint": "^2.6.0", + "mocha": "^2.1.0" + }, + "scripts": { + "test": "mocha", + "lint": "jshint index.js test/test.js" + } +} diff --git a/node_modules/require-main-filename/CHANGELOG.md b/node_modules/require-main-filename/CHANGELOG.md new file mode 100644 index 0000000..717d59e --- /dev/null +++ b/node_modules/require-main-filename/CHANGELOG.md @@ -0,0 +1,26 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +# [2.0.0](https://github.com/yargs/require-main-filename/compare/v1.0.2...v2.0.0) (2019-01-28) + + +### Chores + +* drop support for Node 0.10 ([#11](https://github.com/yargs/require-main-filename/issues/11)) ([87f4e13](https://github.com/yargs/require-main-filename/commit/87f4e13)) + + +### BREAKING CHANGES + +* drop support for Node 0.10/0.12 + + + + +## [1.0.2](https://github.com/yargs/require-main-filename/compare/v1.0.1...v1.0.2) (2017-06-16) + + +### Bug Fixes + +* add files to package.json ([#4](https://github.com/yargs/require-main-filename/issues/4)) ([fa29988](https://github.com/yargs/require-main-filename/commit/fa29988)) diff --git a/node_modules/require-main-filename/LICENSE.txt b/node_modules/require-main-filename/LICENSE.txt new file mode 100644 index 0000000..836440b --- /dev/null +++ b/node_modules/require-main-filename/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/require-main-filename/README.md b/node_modules/require-main-filename/README.md new file mode 100644 index 0000000..820d9f5 --- /dev/null +++ b/node_modules/require-main-filename/README.md @@ -0,0 +1,26 @@ +# require-main-filename + +[![Build Status](https://travis-ci.org/yargs/require-main-filename.png)](https://travis-ci.org/yargs/require-main-filename) +[![Coverage Status](https://coveralls.io/repos/yargs/require-main-filename/badge.svg?branch=master)](https://coveralls.io/r/yargs/require-main-filename?branch=master) +[![NPM version](https://img.shields.io/npm/v/require-main-filename.svg)](https://www.npmjs.com/package/require-main-filename) + +`require.main.filename` is great for figuring out the entry +point for the current application. This can be combined with a module like +[pkg-conf](https://www.npmjs.com/package/pkg-conf) to, _as if by magic_, load +top-level configuration. + +Unfortunately, `require.main.filename` sometimes fails when an application is +executed with an alternative process manager, e.g., [iisnode](https://github.com/tjanczuk/iisnode). + +`require-main-filename` is a shim that addresses this problem. + +## Usage + +```js +var main = require('require-main-filename')() +// use main as an alternative to require.main.filename. +``` + +## License + +ISC diff --git a/node_modules/require-main-filename/index.js b/node_modules/require-main-filename/index.js new file mode 100644 index 0000000..dca7f0c --- /dev/null +++ b/node_modules/require-main-filename/index.js @@ -0,0 +1,18 @@ +module.exports = function (_require) { + _require = _require || require + var main = _require.main + if (main && isIISNode(main)) return handleIISNode(main) + else return main ? main.filename : process.cwd() +} + +function isIISNode (main) { + return /\\iisnode\\/.test(main.filename) +} + +function handleIISNode (main) { + if (!main.children.length) { + return main.filename + } else { + return main.children[0].filename + } +} diff --git a/node_modules/require-main-filename/package.json b/node_modules/require-main-filename/package.json new file mode 100644 index 0000000..a549822 --- /dev/null +++ b/node_modules/require-main-filename/package.json @@ -0,0 +1,35 @@ +{ + "name": "require-main-filename", + "version": "2.0.0", + "description": "shim for require.main.filename() that works in as many environments as possible", + "main": "index.js", + "scripts": { + "pretest": "standard", + "test": "tap --coverage test.js", + "release": "standard-version" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/yargs/require-main-filename.git" + }, + "keywords": [ + "require", + "shim", + "iisnode" + ], + "files": [ + "index.js" + ], + "author": "Ben Coe ", + "license": "ISC", + "bugs": { + "url": "https://github.com/yargs/require-main-filename/issues" + }, + "homepage": "https://github.com/yargs/require-main-filename#readme", + "devDependencies": { + "chai": "^4.0.0", + "standard": "^10.0.3", + "standard-version": "^4.0.0", + "tap": "^11.0.0" + } +} diff --git a/node_modules/set-blocking/CHANGELOG.md b/node_modules/set-blocking/CHANGELOG.md new file mode 100644 index 0000000..03bf591 --- /dev/null +++ b/node_modules/set-blocking/CHANGELOG.md @@ -0,0 +1,26 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +# [2.0.0](https://github.com/yargs/set-blocking/compare/v1.0.0...v2.0.0) (2016-05-17) + + +### Features + +* add an isTTY check ([#3](https://github.com/yargs/set-blocking/issues/3)) ([66ce277](https://github.com/yargs/set-blocking/commit/66ce277)) + + +### BREAKING CHANGES + +* stdio/stderr will not be set to blocking if isTTY === false + + + + +# 1.0.0 (2016-05-14) + + +### Features + +* implemented shim for stream._handle.setBlocking ([6bde0c0](https://github.com/yargs/set-blocking/commit/6bde0c0)) diff --git a/node_modules/set-blocking/LICENSE.txt b/node_modules/set-blocking/LICENSE.txt new file mode 100644 index 0000000..836440b --- /dev/null +++ b/node_modules/set-blocking/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/set-blocking/README.md b/node_modules/set-blocking/README.md new file mode 100644 index 0000000..e93b420 --- /dev/null +++ b/node_modules/set-blocking/README.md @@ -0,0 +1,31 @@ +# set-blocking + +[![Build Status](https://travis-ci.org/yargs/set-blocking.svg)](https://travis-ci.org/yargs/set-blocking) +[![NPM version](https://img.shields.io/npm/v/set-blocking.svg)](https://www.npmjs.com/package/set-blocking) +[![Coverage Status](https://coveralls.io/repos/yargs/set-blocking/badge.svg?branch=)](https://coveralls.io/r/yargs/set-blocking?branch=master) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + +set blocking `stdio` and `stderr` ensuring that terminal output does not truncate. + +```js +const setBlocking = require('set-blocking') +setBlocking(true) +console.log(someLargeStringToOutput) +``` + +## Historical Context/Word of Warning + +This was created as a shim to address the bug discussed in [node #6456](https://github.com/nodejs/node/issues/6456). This bug crops up on +newer versions of Node.js (`0.12+`), truncating terminal output. + +You should be mindful of the side-effects caused by using `set-blocking`: + +* if your module sets blocking to `true`, it will effect other modules + consuming your library. In [yargs](https://github.com/yargs/yargs/blob/master/yargs.js#L653) we only call + `setBlocking(true)` once we already know we are about to call `process.exit(code)`. +* this patch will not apply to subprocesses spawned with `isTTY = true`, this is + the [default `spawn()` behavior](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options). + +## License + +ISC diff --git a/node_modules/set-blocking/index.js b/node_modules/set-blocking/index.js new file mode 100644 index 0000000..6f78774 --- /dev/null +++ b/node_modules/set-blocking/index.js @@ -0,0 +1,7 @@ +module.exports = function (blocking) { + [process.stdout, process.stderr].forEach(function (stream) { + if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking) + } + }) +} diff --git a/node_modules/set-blocking/package.json b/node_modules/set-blocking/package.json new file mode 100644 index 0000000..c082db7 --- /dev/null +++ b/node_modules/set-blocking/package.json @@ -0,0 +1,42 @@ +{ + "name": "set-blocking", + "version": "2.0.0", + "description": "set blocking stdio and stderr ensuring that terminal output does not truncate", + "main": "index.js", + "scripts": { + "pretest": "standard", + "test": "nyc mocha ./test/*.js", + "coverage": "nyc report --reporter=text-lcov | coveralls", + "version": "standard-version" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/yargs/set-blocking.git" + }, + "keywords": [ + "flush", + "terminal", + "blocking", + "shim", + "stdio", + "stderr" + ], + "author": "Ben Coe ", + "license": "ISC", + "bugs": { + "url": "https://github.com/yargs/set-blocking/issues" + }, + "homepage": "https://github.com/yargs/set-blocking#readme", + "devDependencies": { + "chai": "^3.5.0", + "coveralls": "^2.11.9", + "mocha": "^2.4.5", + "nyc": "^6.4.4", + "standard": "^7.0.1", + "standard-version": "^2.2.1" + }, + "files": [ + "index.js", + "LICENSE.txt" + ] +} \ No newline at end of file diff --git a/node_modules/split2/LICENSE b/node_modules/split2/LICENSE new file mode 100644 index 0000000..a91afe5 --- /dev/null +++ b/node_modules/split2/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2014-2018, Matteo Collina + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/split2/README.md b/node_modules/split2/README.md new file mode 100644 index 0000000..36f03ab --- /dev/null +++ b/node_modules/split2/README.md @@ -0,0 +1,85 @@ +# Split2(matcher, mapper, options) + +![ci](https://github.com/mcollina/split2/workflows/ci/badge.svg) + +Break up a stream and reassemble it so that each line is a chunk. +`split2` is inspired by [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) module, +and it is totally API compatible with it. +However, it is based on Node.js core [`Transform`](https://nodejs.org/api/stream.html#stream_new_stream_transform_options). + +`matcher` may be a `String`, or a `RegExp`. Example, read every line in a file ... + +``` js + fs.createReadStream(file) + .pipe(split2()) + .on('data', function (line) { + //each chunk now is a separate line! + }) + +``` + +`split` takes the same arguments as `string.split` except it defaults to '/\r?\n/', and the optional `limit` paremeter is ignored. +[String#split](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split) + +`split` takes an optional options object on it's third argument, which +is directly passed as a +[Transform](https://nodejs.org/api/stream.html#stream_new_stream_transform_options) +option. + +Additionally, the `.maxLength` and `.skipOverflow` options are implemented, which set limits on the internal +buffer size and the stream's behavior when the limit is exceeded. There is no limit unless `maxLength` is set. When +the internal buffer size exceeds `maxLength`, the stream emits an error by default. You may also set `skipOverflow` to +true to suppress the error and instead skip past any lines that cause the internal buffer to exceed `maxLength`. + +Calling `.destroy` will make the stream emit `close`. Use this to perform cleanup logic + +``` js +var splitFile = function(filename) { + var file = fs.createReadStream(filename) + + return file + .pipe(split2()) + .on('close', function() { + // destroy the file stream in case the split stream was destroyed + file.destroy() + }) +} + +var stream = splitFile('my-file.txt') + +stream.destroy() // will destroy the input file stream +``` + +# NDJ - Newline Delimited Json + +`split2` accepts a function which transforms each line. + +``` js +fs.createReadStream(file) + .pipe(split2(JSON.parse)) + .on('data', function (obj) { + //each chunk now is a js object + }) + .on("error", function(error) { + //handling parsing errors + }) +``` + +However, in [@dominictarr](https://github.com/dominictarr) [`split`](https://github.com/dominictarr/split) the mapper +is wrapped in a try-catch, while here it is not: if your parsing logic can throw, wrap it yourself. Otherwise, you can also use the stream error handling when mapper function throw. + +# License + +Copyright (c) 2014-2021, Matteo Collina + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/split2/bench.js b/node_modules/split2/bench.js new file mode 100644 index 0000000..15ec5df --- /dev/null +++ b/node_modules/split2/bench.js @@ -0,0 +1,27 @@ +'use strict' + +const split = require('./') +const bench = require('fastbench') +const binarySplit = require('binary-split') +const fs = require('fs') + +function benchSplit (cb) { + fs.createReadStream('package.json') + .pipe(split()) + .on('end', cb) + .resume() +} + +function benchBinarySplit (cb) { + fs.createReadStream('package.json') + .pipe(binarySplit()) + .on('end', cb) + .resume() +} + +const run = bench([ + benchSplit, + benchBinarySplit +], 10000) + +run(run) diff --git a/node_modules/split2/index.js b/node_modules/split2/index.js new file mode 100644 index 0000000..9b59f6c --- /dev/null +++ b/node_modules/split2/index.js @@ -0,0 +1,141 @@ +/* +Copyright (c) 2014-2021, Matteo Collina + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +*/ + +'use strict' + +const { Transform } = require('stream') +const { StringDecoder } = require('string_decoder') +const kLast = Symbol('last') +const kDecoder = Symbol('decoder') + +function transform (chunk, enc, cb) { + let list + if (this.overflow) { // Line buffer is full. Skip to start of next line. + const buf = this[kDecoder].write(chunk) + list = buf.split(this.matcher) + + if (list.length === 1) return cb() // Line ending not found. Discard entire chunk. + + // Line ending found. Discard trailing fragment of previous line and reset overflow state. + list.shift() + this.overflow = false + } else { + this[kLast] += this[kDecoder].write(chunk) + list = this[kLast].split(this.matcher) + } + + this[kLast] = list.pop() + + for (let i = 0; i < list.length; i++) { + try { + push(this, this.mapper(list[i])) + } catch (error) { + return cb(error) + } + } + + this.overflow = this[kLast].length > this.maxLength + if (this.overflow && !this.skipOverflow) { + cb(new Error('maximum buffer reached')) + return + } + + cb() +} + +function flush (cb) { + // forward any gibberish left in there + this[kLast] += this[kDecoder].end() + + if (this[kLast]) { + try { + push(this, this.mapper(this[kLast])) + } catch (error) { + return cb(error) + } + } + + cb() +} + +function push (self, val) { + if (val !== undefined) { + self.push(val) + } +} + +function noop (incoming) { + return incoming +} + +function split (matcher, mapper, options) { + // Set defaults for any arguments not supplied. + matcher = matcher || /\r?\n/ + mapper = mapper || noop + options = options || {} + + // Test arguments explicitly. + switch (arguments.length) { + case 1: + // If mapper is only argument. + if (typeof matcher === 'function') { + mapper = matcher + matcher = /\r?\n/ + // If options is only argument. + } else if (typeof matcher === 'object' && !(matcher instanceof RegExp) && !matcher[Symbol.split]) { + options = matcher + matcher = /\r?\n/ + } + break + + case 2: + // If mapper and options are arguments. + if (typeof matcher === 'function') { + options = mapper + mapper = matcher + matcher = /\r?\n/ + // If matcher and options are arguments. + } else if (typeof mapper === 'object') { + options = mapper + mapper = noop + } + } + + options = Object.assign({}, options) + options.autoDestroy = true + options.transform = transform + options.flush = flush + options.readableObjectMode = true + + const stream = new Transform(options) + + stream[kLast] = '' + stream[kDecoder] = new StringDecoder('utf8') + stream.matcher = matcher + stream.mapper = mapper + stream.maxLength = options.maxLength + stream.skipOverflow = options.skipOverflow || false + stream.overflow = false + stream._destroy = function (err, cb) { + // Weird Node v12 bug that we need to work around + this._writableState.errorEmitted = false + cb(err) + } + + return stream +} + +module.exports = split diff --git a/node_modules/split2/package.json b/node_modules/split2/package.json new file mode 100644 index 0000000..e04bcc8 --- /dev/null +++ b/node_modules/split2/package.json @@ -0,0 +1,39 @@ +{ + "name": "split2", + "version": "4.2.0", + "description": "split a Text Stream into a Line Stream, using Stream 3", + "main": "index.js", + "scripts": { + "lint": "standard --verbose", + "unit": "nyc --lines 100 --branches 100 --functions 100 --check-coverage --reporter=text tape test.js", + "coverage": "nyc --reporter=html --reporter=cobertura --reporter=text tape test/test.js", + "test:report": "npm run lint && npm run unit:report", + "test": "npm run lint && npm run unit", + "legacy": "tape test.js" + }, + "pre-commit": [ + "test" + ], + "website": "https://github.com/mcollina/split2", + "repository": { + "type": "git", + "url": "https://github.com/mcollina/split2.git" + }, + "bugs": { + "url": "http://github.com/mcollina/split2/issues" + }, + "engines": { + "node": ">= 10.x" + }, + "author": "Matteo Collina ", + "license": "ISC", + "devDependencies": { + "binary-split": "^1.0.3", + "callback-stream": "^1.1.0", + "fastbench": "^1.0.0", + "nyc": "^15.0.1", + "pre-commit": "^1.1.2", + "standard": "^17.0.0", + "tape": "^5.0.0" + } +} diff --git a/node_modules/split2/test.js b/node_modules/split2/test.js new file mode 100644 index 0000000..a7f9838 --- /dev/null +++ b/node_modules/split2/test.js @@ -0,0 +1,409 @@ +'use strict' + +const test = require('tape') +const split = require('./') +const callback = require('callback-stream') +const strcb = callback.bind(null, { decodeStrings: false }) +const objcb = callback.bind(null, { objectMode: true }) + +test('split two lines on end', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.end('hello\nworld') +}) + +test('split two lines on two writes', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.write('hello') + input.write('\nworld') + input.end() +}) + +test('split four lines on three writes', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world', 'bye', 'world']) + })) + + input.write('hello\nwor') + input.write('ld\nbye\nwo') + input.write('rld') + input.end() +}) + +test('accumulate multiple writes', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['helloworld']) + })) + + input.write('hello') + input.write('world') + input.end() +}) + +test('split using a custom string matcher', function (t) { + t.plan(2) + + const input = split('~') + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.end('hello~world') +}) + +test('split using a custom regexp matcher', function (t) { + t.plan(2) + + const input = split(/~/) + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.end('hello~world') +}) + +test('support an option argument', function (t) { + t.plan(2) + + const input = split({ highWaterMark: 2 }) + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.end('hello\nworld') +}) + +test('support a mapper function', function (t) { + t.plan(2) + + const a = { a: '42' } + const b = { b: '24' } + + const input = split(JSON.parse) + + input.pipe(objcb(function (err, list) { + t.error(err) + t.deepEqual(list, [a, b]) + })) + + input.write(JSON.stringify(a)) + input.write('\n') + input.end(JSON.stringify(b)) +}) + +test('split lines windows-style', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.end('hello\r\nworld') +}) + +test('splits a buffer', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.end(Buffer.from('hello\nworld')) +}) + +test('do not end on undefined', function (t) { + t.plan(2) + + const input = split(function (line) { }) + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, []) + })) + + input.end(Buffer.from('hello\nworld')) +}) + +test('has destroy method', function (t) { + t.plan(1) + + const input = split(function (line) { }) + + input.on('close', function () { + t.ok(true, 'close emitted') + t.end() + }) + + input.destroy() +}) + +test('support custom matcher and mapper', function (t) { + t.plan(4) + + const a = { a: '42' } + const b = { b: '24' } + const input = split('~', JSON.parse) + + t.equal(input.matcher, '~') + t.equal(typeof input.mapper, 'function') + + input.pipe(objcb(function (err, list) { + t.notOk(err, 'no errors') + t.deepEqual(list, [a, b]) + })) + + input.write(JSON.stringify(a)) + input.write('~') + input.end(JSON.stringify(b)) +}) + +test('support custom matcher and options', function (t) { + t.plan(6) + + const input = split('~', { highWaterMark: 1024 }) + + t.equal(input.matcher, '~') + t.equal(typeof input.mapper, 'function') + t.equal(input._readableState.highWaterMark, 1024) + t.equal(input._writableState.highWaterMark, 1024) + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.end('hello~world') +}) + +test('support mapper and options', function (t) { + t.plan(6) + + const a = { a: '42' } + const b = { b: '24' } + const input = split(JSON.parse, { highWaterMark: 1024 }) + + t.ok(input.matcher instanceof RegExp, 'matcher is RegExp') + t.equal(typeof input.mapper, 'function') + t.equal(input._readableState.highWaterMark, 1024) + t.equal(input._writableState.highWaterMark, 1024) + + input.pipe(objcb(function (err, list) { + t.error(err) + t.deepEqual(list, [a, b]) + })) + + input.write(JSON.stringify(a)) + input.write('\n') + input.end(JSON.stringify(b)) +}) + +test('split utf8 chars', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['烫烫烫', '锟斤拷']) + })) + + const buf = Buffer.from('烫烫烫\r\n锟斤拷', 'utf8') + for (let i = 0; i < buf.length; ++i) { + input.write(buf.slice(i, i + 1)) + } + input.end() +}) + +test('split utf8 chars 2by2', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['烫烫烫', '烫烫烫']) + })) + + const str = '烫烫烫\r\n烫烫烫' + const buf = Buffer.from(str, 'utf8') + for (let i = 0; i < buf.length; i += 2) { + input.write(buf.slice(i, i + 2)) + } + input.end() +}) + +test('split lines when the \n comes at the end of a chunk', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.write('hello\n') + input.end('world') +}) + +test('truncated utf-8 char', function (t) { + t.plan(2) + + const input = split() + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['烫' + Buffer.from('e7', 'hex').toString()]) + })) + + const str = '烫烫' + const buf = Buffer.from(str, 'utf8') + + input.write(buf.slice(0, 3)) + input.end(buf.slice(3, 4)) +}) + +test('maximum buffer limit', function (t) { + t.plan(1) + + const input = split({ maxLength: 2 }) + input.on('error', function (err) { + t.ok(err) + }) + + input.resume() + + input.write('hey') +}) + +test('readable highWaterMark', function (t) { + const input = split() + t.equal(input._readableState.highWaterMark, 16) + t.end() +}) + +test('maxLength < chunk size', function (t) { + t.plan(2) + + const input = split({ maxLength: 2 }) + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['a', 'b']) + })) + + input.end('a\nb') +}) + +test('maximum buffer limit w/skip', function (t) { + t.plan(2) + + const input = split({ maxLength: 2, skipOverflow: true }) + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['a', 'b', 'c']) + })) + + input.write('a\n123') + input.write('456') + input.write('789\nb\nc') + input.end() +}) + +test("don't modify the options object", function (t) { + t.plan(2) + + const options = {} + const input = split(options) + + input.pipe(strcb(function (err, list) { + t.error(err) + t.same(options, {}) + })) + + input.end() +}) + +test('mapper throws flush', function (t) { + t.plan(1) + const error = new Error() + const input = split(function () { + throw error + }) + + input.on('error', (err, list) => { + t.same(err, error) + }) + input.end('hello') +}) + +test('mapper throws on transform', function (t) { + t.plan(1) + + const error = new Error() + const input = split(function (l) { + throw error + }) + + input.on('error', (err) => { + t.same(err, error) + }) + input.write('a') + input.write('\n') + input.end('b') +}) + +test('supports Symbol.split', function (t) { + t.plan(2) + + const input = split({ + [Symbol.split] (str) { + return str.split('~') + } + }) + + input.pipe(strcb(function (err, list) { + t.error(err) + t.deepEqual(list, ['hello', 'world']) + })) + + input.end('hello~world') +}) diff --git a/node_modules/string-width/index.d.ts b/node_modules/string-width/index.d.ts new file mode 100644 index 0000000..12b5309 --- /dev/null +++ b/node_modules/string-width/index.d.ts @@ -0,0 +1,29 @@ +declare const stringWidth: { + /** + Get the visual width of a string - the number of columns required to display it. + + Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + + @example + ``` + import stringWidth = require('string-width'); + + stringWidth('a'); + //=> 1 + + stringWidth('古'); + //=> 2 + + stringWidth('\u001B[1m古\u001B[22m'); + //=> 2 + ``` + */ + (string: string): number; + + // TODO: remove this in the next major version, refactor the whole definition to: + // declare function stringWidth(string: string): number; + // export = stringWidth; + default: typeof stringWidth; +} + +export = stringWidth; diff --git a/node_modules/string-width/index.js b/node_modules/string-width/index.js new file mode 100644 index 0000000..f4d261a --- /dev/null +++ b/node_modules/string-width/index.js @@ -0,0 +1,47 @@ +'use strict'; +const stripAnsi = require('strip-ansi'); +const isFullwidthCodePoint = require('is-fullwidth-code-point'); +const emojiRegex = require('emoji-regex'); + +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint(code) ? 2 : 1; + } + + return width; +}; + +module.exports = stringWidth; +// TODO: remove this in the next major version +module.exports.default = stringWidth; diff --git a/node_modules/string-width/license b/node_modules/string-width/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/string-width/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/string-width/package.json b/node_modules/string-width/package.json new file mode 100644 index 0000000..28ba7b4 --- /dev/null +++ b/node_modules/string-width/package.json @@ -0,0 +1,56 @@ +{ + "name": "string-width", + "version": "4.2.3", + "description": "Get the visual width of a string - the number of columns required to display it", + "license": "MIT", + "repository": "sindresorhus/string-width", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "string", + "character", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/string-width/readme.md b/node_modules/string-width/readme.md new file mode 100644 index 0000000..bdd3141 --- /dev/null +++ b/node_modules/string-width/readme.md @@ -0,0 +1,50 @@ +# string-width + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + + +## Install + +``` +$ npm install string-width +``` + + +## Usage + +```js +const stringWidth = require('string-width'); + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` + + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000..907fccc --- /dev/null +++ b/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,17 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +declare function stripAnsi(string: string): string; + +export = stripAnsi; diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js new file mode 100644 index 0000000..9a593df --- /dev/null +++ b/node_modules/strip-ansi/index.js @@ -0,0 +1,4 @@ +'use strict'; +const ansiRegex = require('ansi-regex'); + +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json new file mode 100644 index 0000000..1a41108 --- /dev/null +++ b/node_modules/strip-ansi/package.json @@ -0,0 +1,54 @@ +{ + "name": "strip-ansi", + "version": "6.0.1", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.10.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000..7c4b56d --- /dev/null +++ b/node_modules/strip-ansi/readme.md @@ -0,0 +1,46 @@ +# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + + +## Install + +``` +$ npm install strip-ansi +``` + + +## Usage + +```js +const stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + + +## strip-ansi for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + diff --git a/node_modules/which-module/LICENSE b/node_modules/which-module/LICENSE new file mode 100644 index 0000000..ab601b6 --- /dev/null +++ b/node_modules/which-module/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/which-module/README.md b/node_modules/which-module/README.md new file mode 100644 index 0000000..008a1ae --- /dev/null +++ b/node_modules/which-module/README.md @@ -0,0 +1,58 @@ +# which-module + +> Find the module object for something that was require()d + +[![Build Status](https://travis-ci.org/nexdrew/which-module.svg?branch=master)](https://travis-ci.org/nexdrew/which-module) +[![Coverage Status](https://coveralls.io/repos/github/nexdrew/which-module/badge.svg?branch=master)](https://coveralls.io/github/nexdrew/which-module?branch=master) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) +[![Greenkeeper badge](https://badges.greenkeeper.io/nexdrew/which-module.svg)](https://greenkeeper.io/) + +Find the `module` object in `require.cache` for something that was `require()`d +or `import`ed - essentially a reverse `require()` lookup. + +Useful for libs that want to e.g. lookup a filename for a module or submodule +that it did not `require()` itself. + +## Install and Usage + +``` +npm install --save which-module +``` + +```js +const whichModule = require('which-module') + +console.log(whichModule(require('something'))) +// Module { +// id: '/path/to/project/node_modules/something/index.js', +// exports: [Function], +// parent: ..., +// filename: '/path/to/project/node_modules/something/index.js', +// loaded: true, +// children: [], +// paths: [ '/path/to/project/node_modules/something/node_modules', +// '/path/to/project/node_modules', +// '/path/to/node_modules', +// '/path/node_modules', +// '/node_modules' ] } +``` + +## API + +### `whichModule(exported)` + +Return the [`module` object](https://nodejs.org/api/modules.html#modules_the_module_object), +if any, that represents the given argument in the `require.cache`. + +`exported` can be anything that was previously `require()`d or `import`ed as a +module, submodule, or dependency - which means `exported` is identical to the +`module.exports` returned by this method. + +If `exported` did not come from the `exports` of a `module` in `require.cache`, +then this method returns `null`. + +## License + +ISC © Contributors + +[opensourceregistry_package_id]: # (458260416784685e5ef3091fee54001785dd4360406aa3000315ff256eef6878) diff --git a/node_modules/which-module/index.js b/node_modules/which-module/index.js new file mode 100644 index 0000000..45559b7 --- /dev/null +++ b/node_modules/which-module/index.js @@ -0,0 +1,9 @@ +'use strict' + +module.exports = function whichModule (exported) { + for (var i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { + mod = require.cache[files[i]] + if (mod.exports === exported) return mod + } + return null +} diff --git a/node_modules/which-module/package.json b/node_modules/which-module/package.json new file mode 100644 index 0000000..6553575 --- /dev/null +++ b/node_modules/which-module/package.json @@ -0,0 +1,41 @@ +{ + "name": "which-module", + "version": "2.0.1", + "description": "Find the module object for something that was require()d", + "main": "index.js", + "scripts": { + "pretest": "standard", + "test": "nyc ava", + "coverage": "nyc report --reporter=text-lcov | coveralls", + "release": "standard-version" + }, + "files": [ + "index.js" + ], + "repository": { + "type": "git", + "url": "git+https://github.com/nexdrew/which-module.git" + }, + "keywords": [ + "which", + "module", + "exports", + "filename", + "require", + "reverse", + "lookup" + ], + "author": "nexdrew", + "license": "ISC", + "bugs": { + "url": "https://github.com/nexdrew/which-module/issues" + }, + "homepage": "https://github.com/nexdrew/which-module#readme", + "devDependencies": { + "ava": "^2.0.0", + "coveralls": "^3.0.3", + "nyc": "^14.0.0", + "standard": "^14.0.0", + "standard-version": "^7.0.0" + } +} diff --git a/node_modules/wrap-ansi/index.js b/node_modules/wrap-ansi/index.js new file mode 100644 index 0000000..a6e5443 --- /dev/null +++ b/node_modules/wrap-ansi/index.js @@ -0,0 +1,186 @@ +'use strict'; +const stringWidth = require('string-width'); +const stripAnsi = require('strip-ansi'); +const ansiStyles = require('ansi-styles'); + +const ESCAPES = new Set([ + '\u001B', + '\u009B' +]); + +const END_CODE = 39; + +const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, columns) => { + const characters = [...word]; + + let isInsideEscape = false; + let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES.has(character)) { + isInsideEscape = true; + } else if (isInsideEscape && character === 'm') { + isInsideEscape = false; + continue; + } + + if (isInsideEscape) { + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = str => { + const words = str.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return str; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more than columns characters +// +// 'soft' allows long words to expand past the column length +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let pre = ''; + let ret = ''; + let escapeCode; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimLeft(); + } + + let rowLength = stringWidth(rows[rows.length - 1]); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(stringVisibleTrimSpacesRight); + } + + pre = rows.join('\n'); + + for (const [index, character] of [...pre].entries()) { + ret += character; + + if (ESCAPES.has(character)) { + const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4))); + escapeCode = code === END_CODE ? null : code; + } + + const code = ansiStyles.codes.get(Number(escapeCode)); + + if (escapeCode && code) { + if (pre[index + 1] === '\n') { + ret += wrapAnsi(code); + } else if (character === '\n') { + ret += wrapAnsi(escapeCode); + } + } + } + + return ret; +}; + +// For each newline, invoke the method separately +module.exports = (string, columns, options) => { + return String(string) + .normalize() + .replace(/\r\n/g, '\n') + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +}; diff --git a/node_modules/wrap-ansi/license b/node_modules/wrap-ansi/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/wrap-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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/node_modules/wrap-ansi/package.json b/node_modules/wrap-ansi/package.json new file mode 100644 index 0000000..1d57c9f --- /dev/null +++ b/node_modules/wrap-ansi/package.json @@ -0,0 +1,61 @@ +{ + "name": "wrap-ansi", + "version": "6.2.0", + "description": "Wordwrap a string with ANSI escape codes", + "license": "MIT", + "repository": "chalk/wrap-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && nyc ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "wrap", + "break", + "wordwrap", + "wordbreak", + "linewrap", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "devDependencies": { + "ava": "^2.1.0", + "chalk": "^2.4.2", + "coveralls": "^3.0.3", + "has-ansi": "^3.0.0", + "nyc": "^14.1.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/wrap-ansi/readme.md b/node_modules/wrap-ansi/readme.md new file mode 100644 index 0000000..d81a4d5 --- /dev/null +++ b/node_modules/wrap-ansi/readme.md @@ -0,0 +1,97 @@ +# wrap-ansi [![Build Status](https://travis-ci.org/chalk/wrap-ansi.svg?branch=master)](https://travis-ci.org/chalk/wrap-ansi) [![Coverage Status](https://coveralls.io/repos/github/chalk/wrap-ansi/badge.svg?branch=master)](https://coveralls.io/github/chalk/wrap-ansi?branch=master) + +> Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) + + +## Install + +``` +$ npm install wrap-ansi +``` + + +## Usage + +```js +const chalk = require('chalk'); +const wrapAnsi = require('wrap-ansi'); + +const input = 'The quick brown ' + chalk.red('fox jumped over ') + + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); + +console.log(wrapAnsi(input, 20)); +``` + + + + +## API + +### wrapAnsi(string, columns, options?) + +Wrap words to the specified column width. + +#### string + +Type: `string` + +String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. + +#### columns + +Type: `number` + +Number of columns to wrap the text to. + +#### options + +Type: `object` + +##### hard + +Type: `boolean`
+Default: `false` + +By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. + +##### wordWrap + +Type: `boolean`
+Default: `true` + +By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. + +##### trim + +Type: `boolean`
+Default: `true` + +Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. + + +## Related + +- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes +- [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right +- [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures. + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) +- [Benjamin Coe](https://github.com/bcoe) + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/xtend/.jshintrc b/node_modules/xtend/.jshintrc new file mode 100644 index 0000000..77887b5 --- /dev/null +++ b/node_modules/xtend/.jshintrc @@ -0,0 +1,30 @@ +{ + "maxdepth": 4, + "maxstatements": 200, + "maxcomplexity": 12, + "maxlen": 80, + "maxparams": 5, + + "curly": true, + "eqeqeq": true, + "immed": true, + "latedef": false, + "noarg": true, + "noempty": true, + "nonew": true, + "undef": true, + "unused": "vars", + "trailing": true, + + "quotmark": true, + "expr": true, + "asi": true, + + "browser": false, + "esnext": true, + "devel": false, + "node": false, + "nonstandard": false, + + "predef": ["require", "module", "__dirname", "__filename"] +} diff --git a/node_modules/xtend/LICENSE b/node_modules/xtend/LICENSE new file mode 100644 index 0000000..0099f4f --- /dev/null +++ b/node_modules/xtend/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) +Copyright (c) 2012-2014 Raynos. + +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/node_modules/xtend/README.md b/node_modules/xtend/README.md new file mode 100644 index 0000000..4a2703c --- /dev/null +++ b/node_modules/xtend/README.md @@ -0,0 +1,32 @@ +# xtend + +[![browser support][3]][4] + +[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges) + +Extend like a boss + +xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence. + +## Examples + +```js +var extend = require("xtend") + +// extend returns a new object. Does not mutate arguments +var combination = extend({ + a: "a", + b: "c" +}, { + b: "b" +}) +// { a: "a", b: "b" } +``` + +## Stability status: Locked + +## MIT Licensed + + + [3]: http://ci.testling.com/Raynos/xtend.png + [4]: http://ci.testling.com/Raynos/xtend diff --git a/node_modules/xtend/immutable.js b/node_modules/xtend/immutable.js new file mode 100644 index 0000000..94889c9 --- /dev/null +++ b/node_modules/xtend/immutable.js @@ -0,0 +1,19 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend() { + var target = {} + + for (var i = 0; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/node_modules/xtend/mutable.js b/node_modules/xtend/mutable.js new file mode 100644 index 0000000..72debed --- /dev/null +++ b/node_modules/xtend/mutable.js @@ -0,0 +1,17 @@ +module.exports = extend + +var hasOwnProperty = Object.prototype.hasOwnProperty; + +function extend(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] + + for (var key in source) { + if (hasOwnProperty.call(source, key)) { + target[key] = source[key] + } + } + } + + return target +} diff --git a/node_modules/xtend/package.json b/node_modules/xtend/package.json new file mode 100644 index 0000000..f7a39d1 --- /dev/null +++ b/node_modules/xtend/package.json @@ -0,0 +1,55 @@ +{ + "name": "xtend", + "version": "4.0.2", + "description": "extend like a boss", + "keywords": [ + "extend", + "merge", + "options", + "opts", + "object", + "array" + ], + "author": "Raynos ", + "repository": "git://github.com/Raynos/xtend.git", + "main": "immutable", + "scripts": { + "test": "node test" + }, + "dependencies": {}, + "devDependencies": { + "tape": "~1.1.0" + }, + "homepage": "https://github.com/Raynos/xtend", + "contributors": [ + { + "name": "Jake Verbaten" + }, + { + "name": "Matt Esch" + } + ], + "bugs": { + "url": "https://github.com/Raynos/xtend/issues", + "email": "raynos2@gmail.com" + }, + "license": "MIT", + "testling": { + "files": "test.js", + "browsers": [ + "ie/7..latest", + "firefox/16..latest", + "firefox/nightly", + "chrome/22..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest" + ] + }, + "engines": { + "node": ">=0.4" + } +} diff --git a/node_modules/xtend/test.js b/node_modules/xtend/test.js new file mode 100644 index 0000000..b895b42 --- /dev/null +++ b/node_modules/xtend/test.js @@ -0,0 +1,103 @@ +var test = require("tape") +var extend = require("./") +var mutableExtend = require("./mutable") + +test("merge", function(assert) { + var a = { a: "foo" } + var b = { b: "bar" } + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("replace", function(assert) { + var a = { a: "foo" } + var b = { a: "bar" } + + assert.deepEqual(extend(a, b), { a: "bar" }) + assert.end() +}) + +test("undefined", function(assert) { + var a = { a: undefined } + var b = { b: "foo" } + + assert.deepEqual(extend(a, b), { a: undefined, b: "foo" }) + assert.deepEqual(extend(b, a), { a: undefined, b: "foo" }) + assert.end() +}) + +test("handle 0", function(assert) { + var a = { a: "default" } + var b = { a: 0 } + + assert.deepEqual(extend(a, b), { a: 0 }) + assert.deepEqual(extend(b, a), { a: "default" }) + assert.end() +}) + +test("is immutable", function (assert) { + var record = {} + + extend(record, { foo: "bar" }) + assert.equal(record.foo, undefined) + assert.end() +}) + +test("null as argument", function (assert) { + var a = { foo: "bar" } + var b = null + var c = void 0 + + assert.deepEqual(extend(b, a, c), { foo: "bar" }) + assert.end() +}) + +test("mutable", function (assert) { + var a = { foo: "bar" } + + mutableExtend(a, { bar: "baz" }) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("null prototype", function(assert) { + var a = { a: "foo" } + var b = Object.create(null) + b.b = "bar"; + + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" }) + assert.end() +}) + +test("null prototype mutable", function (assert) { + var a = { foo: "bar" } + var b = Object.create(null) + b.bar = "baz"; + + mutableExtend(a, b) + + assert.equal(a.bar, "baz") + assert.end() +}) + +test("prototype pollution", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + extend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) + +test("prototype pollution mutable", function (assert) { + var a = {} + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}' + + assert.strictEqual(a.oops, undefined) + mutableExtend({}, maliciousPayload) + assert.strictEqual(a.oops, undefined) + assert.end() +}) diff --git a/node_modules/y18n/CHANGELOG.md b/node_modules/y18n/CHANGELOG.md new file mode 100644 index 0000000..b7e86e9 --- /dev/null +++ b/node_modules/y18n/CHANGELOG.md @@ -0,0 +1,35 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + + +### [4.0.3](https://www.github.com/yargs/y18n/compare/y18n-v4.0.2...y18n-v4.0.3) (2021-04-07) + + +### Bug Fixes + +* **release:** 4.x.x should not enforce Node 10 ([#126](https://www.github.com/yargs/y18n/issues/126)) ([1e21a53](https://www.github.com/yargs/y18n/commit/1e21a536e9135d8403a47be88922157a706b7cde)) + +### 4.0.1 (2020-11-30) + +### Bug Fixes + +* address prototype pollution issue ([#108](https://www.github.com/yargs/y18n/issues/108)) ([a9ac604](https://www.github.com/yargs/y18n/commit/a9ac604abf756dec9687be3843e2c93bfe581f25)) + + +# [4.0.0](https://github.com/yargs/y18n/compare/v3.2.1...v4.0.0) (2017-10-10) + + +### Bug Fixes + +* allow support for falsy values like 0 in tagged literal ([#45](https://github.com/yargs/y18n/issues/45)) ([c926123](https://github.com/yargs/y18n/commit/c926123)) + + +### Features + +* **__:** added tagged template literal support ([#44](https://github.com/yargs/y18n/issues/44)) ([0598daf](https://github.com/yargs/y18n/commit/0598daf)) + + +### BREAKING CHANGES + +* **__:** dropping Node 0.10/Node 0.12 support diff --git a/node_modules/y18n/LICENSE b/node_modules/y18n/LICENSE new file mode 100644 index 0000000..3c157f0 --- /dev/null +++ b/node_modules/y18n/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, Contributors + +Permission to use, copy, modify, and/or distribute this software for any purpose +with or without fee is hereby granted, provided that the above copyright notice +and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS +OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER +TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF +THIS SOFTWARE. diff --git a/node_modules/y18n/README.md b/node_modules/y18n/README.md new file mode 100644 index 0000000..826474f --- /dev/null +++ b/node_modules/y18n/README.md @@ -0,0 +1,109 @@ +# y18n + +[![Build Status][travis-image]][travis-url] +[![Coverage Status][coveralls-image]][coveralls-url] +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) + +The bare-bones internationalization library used by yargs. + +Inspired by [i18n](https://www.npmjs.com/package/i18n). + +## Examples + +_simple string translation:_ + +```js +var __ = require('y18n').__ + +console.log(__('my awesome string %s', 'foo')) +``` + +output: + +`my awesome string foo` + +_using tagged template literals_ + +```js +var __ = require('y18n').__ +var str = 'foo' + +console.log(__`my awesome string ${str}`) +``` + +output: + +`my awesome string foo` + +_pluralization support:_ + +```js +var __n = require('y18n').__n + +console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')) +``` + +output: + +`2 fishes foo` + +## JSON Language Files + +The JSON language files should be stored in a `./locales` folder. +File names correspond to locales, e.g., `en.json`, `pirate.json`. + +When strings are observed for the first time they will be +added to the JSON file corresponding to the current locale. + +## Methods + +### require('y18n')(config) + +Create an instance of y18n with the config provided, options include: + +* `directory`: the locale directory, default `./locales`. +* `updateFiles`: should newly observed strings be updated in file, default `true`. +* `locale`: what locale should be used. +* `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) + be allowed if a file matching the locale does not exist (e.g. `en_US.json`), + default `true`. + +### y18n.\_\_(str, arg, arg, arg) + +Print a localized string, `%s` will be replaced with `arg`s. + +This function can also be used as a tag for a template literal. You can use it +like this: __`hello ${'world'}`. This will be equivalent to +`__('hello %s', 'world')`. + +### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) + +Print a localized string with appropriate pluralization. If `%d` is provided +in the string, the `count` will replace this placeholder. + +### y18n.setLocale(str) + +Set the current locale being used. + +### y18n.getLocale() + +What locale is currently being used? + +### y18n.updateLocale(obj) + +Update the current locale with the key value pairs in `obj`. + +## License + +ISC + +[travis-url]: https://travis-ci.org/yargs/y18n +[travis-image]: https://img.shields.io/travis/yargs/y18n.svg +[coveralls-url]: https://coveralls.io/github/yargs/y18n +[coveralls-image]: https://img.shields.io/coveralls/yargs/y18n.svg +[npm-url]: https://npmjs.org/package/y18n +[npm-image]: https://img.shields.io/npm/v/y18n.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: https://github.com/feross/standard diff --git a/node_modules/y18n/index.js b/node_modules/y18n/index.js new file mode 100644 index 0000000..727362a --- /dev/null +++ b/node_modules/y18n/index.js @@ -0,0 +1,188 @@ +var fs = require('fs') +var path = require('path') +var util = require('util') + +function Y18N (opts) { + // configurable options. + opts = opts || {} + this.directory = opts.directory || './locales' + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true + this.locale = opts.locale || 'en' + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true + + // internal stuff. + this.cache = Object.create(null) + this.writeQueue = [] +} + +Y18N.prototype.__ = function () { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral.apply(this, arguments) + } + var args = Array.prototype.slice.call(arguments) + var str = args.shift() + var cb = function () {} // start with noop. + + if (typeof args[args.length - 1] === 'function') cb = args.pop() + cb = cb || function () {} // noop. + + if (!this.cache[this.locale]) this._readLocaleFile() + + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str + + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite([this.directory, this.locale, cb]) + } else { + cb() + } + + return util.format.apply(util, [this.cache[this.locale][str] || str].concat(args)) +} + +Y18N.prototype._taggedLiteral = function (parts) { + var args = arguments + var str = '' + parts.forEach(function (part, i) { + var arg = args[i + 1] + str += part + if (typeof arg !== 'undefined') { + str += '%s' + } + }) + return this.__.apply(null, [str].concat([].slice.call(arguments, 1))) +} + +Y18N.prototype._enqueueWrite = function (work) { + this.writeQueue.push(work) + if (this.writeQueue.length === 1) this._processWriteQueue() +} + +Y18N.prototype._processWriteQueue = function () { + var _this = this + var work = this.writeQueue[0] + + // destructure the enqueued work. + var directory = work[0] + var locale = work[1] + var cb = work[2] + + var languageFile = this._resolveLocaleFile(directory, locale) + var serializedLocale = JSON.stringify(this.cache[locale], null, 2) + + fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift() + if (_this.writeQueue.length > 0) _this._processWriteQueue() + cb(err) + }) +} + +Y18N.prototype._readLocaleFile = function () { + var localeLookup = {} + var languageFile = this._resolveLocaleFile(this.directory, this.locale) + + try { + localeLookup = JSON.parse(fs.readFileSync(languageFile, 'utf-8')) + } catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile + } + + if (err.code === 'ENOENT') localeLookup = {} + else throw err + } + + this.cache[this.locale] = localeLookup +} + +Y18N.prototype._resolveLocaleFile = function (directory, locale) { + var file = path.resolve(directory, './', locale + '.json') + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + var languageFile = path.resolve(directory, './', locale.split('_')[0] + '.json') + if (this._fileExistsSync(languageFile)) file = languageFile + } + return file +} + +// this only exists because fs.existsSync() "will be deprecated" +// see https://nodejs.org/api/fs.html#fs_fs_existssync_path +Y18N.prototype._fileExistsSync = function (file) { + try { + return fs.statSync(file).isFile() + } catch (err) { + return false + } +} + +Y18N.prototype.__n = function () { + var args = Array.prototype.slice.call(arguments) + var singular = args.shift() + var plural = args.shift() + var quantity = args.shift() + + var cb = function () {} // start with noop. + if (typeof args[args.length - 1] === 'function') cb = args.pop() + + if (!this.cache[this.locale]) this._readLocaleFile() + + var str = quantity === 1 ? singular : plural + if (this.cache[this.locale][singular]) { + str = this.cache[this.locale][singular][quantity === 1 ? 'one' : 'other'] + } + + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + } + + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite([this.directory, this.locale, cb]) + } else { + cb() + } + + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + var values = [str] + if (~str.indexOf('%d')) values.push(quantity) + + return util.format.apply(util, values.concat(args)) +} + +Y18N.prototype.setLocale = function (locale) { + this.locale = locale +} + +Y18N.prototype.getLocale = function () { + return this.locale +} + +Y18N.prototype.updateLocale = function (obj) { + if (!this.cache[this.locale]) this._readLocaleFile() + + for (var key in obj) { + this.cache[this.locale][key] = obj[key] + } +} + +module.exports = function (opts) { + var y18n = new Y18N(opts) + + // bind all functions to y18n, so that + // they can be used in isolation. + for (var key in y18n) { + if (typeof y18n[key] === 'function') { + y18n[key] = y18n[key].bind(y18n) + } + } + + return y18n +} diff --git a/node_modules/y18n/package.json b/node_modules/y18n/package.json new file mode 100644 index 0000000..6f08863 --- /dev/null +++ b/node_modules/y18n/package.json @@ -0,0 +1,39 @@ +{ + "name": "y18n", + "version": "4.0.3", + "description": "the bare-bones internationalization library used by yargs", + "main": "index.js", + "scripts": { + "pretest": "standard", + "test": "nyc mocha", + "coverage": "nyc report --reporter=text-lcov | coveralls", + "release": "standard-version" + }, + "repository": { + "type": "git", + "url": "git@github.com:yargs/y18n.git" + }, + "files": [ + "index.js" + ], + "keywords": [ + "i18n", + "internationalization", + "yargs" + ], + "author": "Ben Coe ", + "license": "ISC", + "bugs": { + "url": "https://github.com/yargs/y18n/issues" + }, + "homepage": "https://github.com/yargs/y18n", + "devDependencies": { + "chai": "^4.0.1", + "coveralls": "^3.0.0", + "mocha": "^4.0.1", + "nyc": "^11.0.1", + "rimraf": "^2.5.0", + "standard": "^10.0.0-beta.0", + "standard-version": "^4.2.0" + } +} diff --git a/node_modules/yargs-parser/CHANGELOG.md b/node_modules/yargs-parser/CHANGELOG.md new file mode 100644 index 0000000..d91dc51 --- /dev/null +++ b/node_modules/yargs-parser/CHANGELOG.md @@ -0,0 +1,601 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [18.1.3](https://www.github.com/yargs/yargs-parser/compare/v18.1.2...v18.1.3) (2020-04-16) + + +### Bug Fixes + +* **setArg:** options using camel-case and dot-notation populated twice ([#268](https://www.github.com/yargs/yargs-parser/issues/268)) ([f7e15b9](https://www.github.com/yargs/yargs-parser/commit/f7e15b9800900b9856acac1a830a5f35847be73e)) + +### [18.1.2](https://www.github.com/yargs/yargs-parser/compare/v18.1.1...v18.1.2) (2020-03-26) + + +### Bug Fixes + +* **array, nargs:** support -o=--value and --option=--value format ([#262](https://www.github.com/yargs/yargs-parser/issues/262)) ([41d3f81](https://www.github.com/yargs/yargs-parser/commit/41d3f8139e116706b28de9b0de3433feb08d2f13)) + +### [18.1.1](https://www.github.com/yargs/yargs-parser/compare/v18.1.0...v18.1.1) (2020-03-16) + + +### Bug Fixes + +* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential +prototype pollution vulnerability. This was reported by the Snyk Security Research Team.([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2)) + +## [18.1.0](https://www.github.com/yargs/yargs-parser/compare/v18.0.0...v18.1.0) (2020-03-07) + + +### Features + +* introduce single-digit boolean aliases ([#255](https://www.github.com/yargs/yargs-parser/issues/255)) ([9c60265](https://www.github.com/yargs/yargs-parser/commit/9c60265fd7a03cb98e6df3e32c8c5e7508d9f56f)) + +## [18.0.0](https://www.github.com/yargs/yargs-parser/compare/v17.1.0...v18.0.0) (2020-03-02) + + +### ⚠ BREAKING CHANGES + +* the narg count is now enforced when parsing arrays. + +### Features + +* NaN can now be provided as a value for nargs, indicating "at least" one value is expected for array ([#251](https://www.github.com/yargs/yargs-parser/issues/251)) ([9db4be8](https://www.github.com/yargs/yargs-parser/commit/9db4be81417a2c7097128db34d86fe70ef4af70c)) + +## [17.1.0](https://www.github.com/yargs/yargs-parser/compare/v17.0.1...v17.1.0) (2020-03-01) + + +### Features + +* introduce greedy-arrays config, for specifying whether arrays consume multiple positionals ([#249](https://www.github.com/yargs/yargs-parser/issues/249)) ([60e880a](https://www.github.com/yargs/yargs-parser/commit/60e880a837046314d89fa4725f923837fd33a9eb)) + +### [17.0.1](https://www.github.com/yargs/yargs-parser/compare/v17.0.0...v17.0.1) (2020-02-29) + + +### Bug Fixes + +* normalized keys were not enumerable ([#247](https://www.github.com/yargs/yargs-parser/issues/247)) ([57119f9](https://www.github.com/yargs/yargs-parser/commit/57119f9f17cf27499bd95e61c2f72d18314f11ba)) + +## [17.0.0](https://www.github.com/yargs/yargs-parser/compare/v16.1.0...v17.0.0) (2020-02-10) + + +### ⚠ BREAKING CHANGES + +* this reverts parsing behavior of booleans to that of yargs@14 +* objects used during parsing are now created with a null +prototype. There may be some scenarios where this change in behavior +leaks externally. + +### Features + +* boolean arguments will not be collected into an implicit array ([#236](https://www.github.com/yargs/yargs-parser/issues/236)) ([34c4e19](https://www.github.com/yargs/yargs-parser/commit/34c4e19bae4e7af63e3cb6fa654a97ed476e5eb5)) +* introduce nargs-eats-options config option ([#246](https://www.github.com/yargs/yargs-parser/issues/246)) ([d50822a](https://www.github.com/yargs/yargs-parser/commit/d50822ac10e1b05f2e9643671ca131ac251b6732)) + + +### Bug Fixes + +* address bugs with "uknown-options-as-args" ([bc023e3](https://www.github.com/yargs/yargs-parser/commit/bc023e3b13e20a118353f9507d1c999bf388a346)) +* array should take precedence over nargs, but enforce nargs ([#243](https://www.github.com/yargs/yargs-parser/issues/243)) ([4cbc188](https://www.github.com/yargs/yargs-parser/commit/4cbc188b7abb2249529a19c090338debdad2fe6c)) +* support keys that collide with object prototypes ([#234](https://www.github.com/yargs/yargs-parser/issues/234)) ([1587b6d](https://www.github.com/yargs/yargs-parser/commit/1587b6d91db853a9109f1be6b209077993fee4de)) +* unknown options terminated with digits now handled by unknown-options-as-args ([#238](https://www.github.com/yargs/yargs-parser/issues/238)) ([d36cdfa](https://www.github.com/yargs/yargs-parser/commit/d36cdfa854254d7c7e0fe1d583818332ac46c2a5)) + +## [16.1.0](https://www.github.com/yargs/yargs-parser/compare/v16.0.0...v16.1.0) (2019-11-01) + + +### ⚠ BREAKING CHANGES + +* populate error if incompatible narg/count or array/count options are used (#191) + +### Features + +* options that have had their default value used are now tracked ([#211](https://www.github.com/yargs/yargs-parser/issues/211)) ([a525234](https://www.github.com/yargs/yargs-parser/commit/a525234558c847deedd73f8792e0a3b77b26e2c0)) +* populate error if incompatible narg/count or array/count options are used ([#191](https://www.github.com/yargs/yargs-parser/issues/191)) ([84a401f](https://www.github.com/yargs/yargs-parser/commit/84a401f0fa3095e0a19661670d1570d0c3b9d3c9)) + + +### Reverts + +* revert 16.0.0 CHANGELOG entry ([920320a](https://www.github.com/yargs/yargs-parser/commit/920320ad9861bbfd58eda39221ae211540fc1daf)) + +## [15.0.0](https://github.com/yargs/yargs-parser/compare/v14.0.0...v15.0.0) (2019-10-07) + + +### Features + +* rework `collect-unknown-options` into `unknown-options-as-args`, providing more comprehensive functionality ([ef771ca](https://github.com/yargs/yargs-parser/commit/ef771ca)) + + +### BREAKING CHANGES + +* rework `collect-unknown-options` into `unknown-options-as-args`, providing more comprehensive functionality + + + +## [14.0.0](https://github.com/yargs/yargs-parser/compare/v13.1.1...v14.0.0) (2019-09-06) + + +### Bug Fixes + +* boolean arrays with default values ([#185](https://github.com/yargs/yargs-parser/issues/185)) ([7d42572](https://github.com/yargs/yargs-parser/commit/7d42572)) +* boolean now behaves the same as other array types ([#184](https://github.com/yargs/yargs-parser/issues/184)) ([17ca3bd](https://github.com/yargs/yargs-parser/commit/17ca3bd)) +* eatNargs() for 'opt.narg === 0' and boolean typed options ([#188](https://github.com/yargs/yargs-parser/issues/188)) ([c5a1db0](https://github.com/yargs/yargs-parser/commit/c5a1db0)) +* maybeCoerceNumber now takes precedence over coerce return value ([#182](https://github.com/yargs/yargs-parser/issues/182)) ([2f26436](https://github.com/yargs/yargs-parser/commit/2f26436)) +* take into account aliases when appending arrays from config object ([#199](https://github.com/yargs/yargs-parser/issues/199)) ([f8a2d3f](https://github.com/yargs/yargs-parser/commit/f8a2d3f)) + + +### Features + +* add configuration option to "collect-unknown-options" ([#181](https://github.com/yargs/yargs-parser/issues/181)) ([7909cc4](https://github.com/yargs/yargs-parser/commit/7909cc4)) +* maybeCoerceNumber() now takes into account arrays ([#187](https://github.com/yargs/yargs-parser/issues/187)) ([31c204b](https://github.com/yargs/yargs-parser/commit/31c204b)) + + +### BREAKING CHANGES + +* unless "parse-numbers" is set to "false", arrays of numeric strings are now parsed as numbers, rather than strings. +* we have dropped the broken "defaulted" functionality; we would like to revisit adding this in the future. +* maybeCoerceNumber now takes precedence over coerce return value (#182) + + + +### [13.1.1](https://www.github.com/yargs/yargs-parser/compare/v13.1.0...v13.1.1) (2019-06-10) + + +### Bug Fixes + +* convert values to strings when tokenizing ([#167](https://www.github.com/yargs/yargs-parser/issues/167)) ([57b7883](https://www.github.com/yargs/yargs-parser/commit/57b7883)) +* nargs should allow duplicates when duplicate-arguments-array=false ([#164](https://www.github.com/yargs/yargs-parser/issues/164)) ([47ccb0b](https://www.github.com/yargs/yargs-parser/commit/47ccb0b)) +* should populate "_" when given config with "short-option-groups" false ([#179](https://www.github.com/yargs/yargs-parser/issues/179)) ([6055974](https://www.github.com/yargs/yargs-parser/commit/6055974)) + +## [13.1.0](https://github.com/yargs/yargs-parser/compare/v13.0.0...v13.1.0) (2019-05-05) + + +### Features + +* add `strip-aliased` and `strip-dashed` configuration options. ([#172](https://github.com/yargs/yargs-parser/issues/172)) ([a3936aa](https://github.com/yargs/yargs-parser/commit/a3936aa)) +* support boolean which do not consume next argument. ([#171](https://github.com/yargs/yargs-parser/issues/171)) ([0ae7fcb](https://github.com/yargs/yargs-parser/commit/0ae7fcb)) + + + + +# [13.0.0](https://github.com/yargs/yargs-parser/compare/v12.0.0...v13.0.0) (2019-02-02) + + +### Features + +* don't coerce number from string with leading '0' or '+' ([#158](https://github.com/yargs/yargs-parser/issues/158)) ([18d0fd5](https://github.com/yargs/yargs-parser/commit/18d0fd5)) + + +### BREAKING CHANGES + +* options with leading '+' or '0' now parse as strings + + + + +# [12.0.0](https://github.com/yargs/yargs-parser/compare/v11.1.1...v12.0.0) (2019-01-29) + + +### Bug Fixes + +* better handling of quoted strings ([#153](https://github.com/yargs/yargs-parser/issues/153)) ([2fb71b2](https://github.com/yargs/yargs-parser/commit/2fb71b2)) + + +### Features + +* default value is now used if no right-hand value provided for numbers/strings ([#156](https://github.com/yargs/yargs-parser/issues/156)) ([5a7c46a](https://github.com/yargs/yargs-parser/commit/5a7c46a)) + + +### BREAKING CHANGES + +* a flag with no right-hand value no longer populates defaulted options with `undefined`. +* quotes at beginning and endings of strings are not removed during parsing. + + + + +## [11.1.1](https://github.com/yargs/yargs-parser/compare/v11.1.0...v11.1.1) (2018-11-19) + + +### Bug Fixes + +* ensure empty string is added into argv._ ([#140](https://github.com/yargs/yargs-parser/issues/140)) ([79cda98](https://github.com/yargs/yargs-parser/commit/79cda98)) + + +### Reverts + +* make requiresArg work in conjunction with arrays ([#136](https://github.com/yargs/yargs-parser/issues/136)) ([f4a3063](https://github.com/yargs/yargs-parser/commit/f4a3063)) + + + + +# [11.1.0](https://github.com/yargs/yargs-parser/compare/v11.0.0...v11.1.0) (2018-11-10) + + +### Bug Fixes + +* handling of one char alias ([#139](https://github.com/yargs/yargs-parser/issues/139)) ([ee56e31](https://github.com/yargs/yargs-parser/commit/ee56e31)) + + +### Features + +* add halt-at-non-option configuration option ([#130](https://github.com/yargs/yargs-parser/issues/130)) ([a849fce](https://github.com/yargs/yargs-parser/commit/a849fce)) + + + + +# [11.0.0](https://github.com/yargs/yargs-parser/compare/v10.1.0...v11.0.0) (2018-10-06) + + +### Bug Fixes + +* flatten-duplicate-arrays:false for more than 2 arrays ([#128](https://github.com/yargs/yargs-parser/issues/128)) ([2bc395f](https://github.com/yargs/yargs-parser/commit/2bc395f)) +* hyphenated flags combined with dot notation broke parsing ([#131](https://github.com/yargs/yargs-parser/issues/131)) ([dc788da](https://github.com/yargs/yargs-parser/commit/dc788da)) +* make requiresArg work in conjunction with arrays ([#136](https://github.com/yargs/yargs-parser/issues/136)) ([77ae1d4](https://github.com/yargs/yargs-parser/commit/77ae1d4)) + + +### Chores + +* update dependencies ([6dc42a1](https://github.com/yargs/yargs-parser/commit/6dc42a1)) + + +### Features + +* also add camelCase array options ([#125](https://github.com/yargs/yargs-parser/issues/125)) ([08c0117](https://github.com/yargs/yargs-parser/commit/08c0117)) +* array.type can now be provided, supporting coercion ([#132](https://github.com/yargs/yargs-parser/issues/132)) ([4b8cfce](https://github.com/yargs/yargs-parser/commit/4b8cfce)) + + +### BREAKING CHANGES + +* drops Node 4 support +* the argv object is now populated differently (correctly) when hyphens and dot notation are used in conjunction. + + + + +# [10.1.0](https://github.com/yargs/yargs-parser/compare/v10.0.0...v10.1.0) (2018-06-29) + + +### Features + +* add `set-placeholder-key` configuration ([#123](https://github.com/yargs/yargs-parser/issues/123)) ([19386ee](https://github.com/yargs/yargs-parser/commit/19386ee)) + + + + +# [10.0.0](https://github.com/yargs/yargs-parser/compare/v9.0.2...v10.0.0) (2018-04-04) + + +### Bug Fixes + +* do not set boolean flags if not defined in `argv` ([#119](https://github.com/yargs/yargs-parser/issues/119)) ([f6e6599](https://github.com/yargs/yargs-parser/commit/f6e6599)) + + +### BREAKING CHANGES + +* `boolean` flags defined without a `default` value will now behave like other option type and won't be set in the parsed results when the user doesn't set the corresponding CLI arg. + +Previous behavior: +```js +var parse = require('yargs-parser'); + +parse('--flag', {boolean: ['flag']}); +// => { _: [], flag: true } + +parse('--no-flag', {boolean: ['flag']}); +// => { _: [], flag: false } + +parse('', {boolean: ['flag']}); +// => { _: [], flag: false } +``` + +New behavior: +```js +var parse = require('yargs-parser'); + +parse('--flag', {boolean: ['flag']}); +// => { _: [], flag: true } + +parse('--no-flag', {boolean: ['flag']}); +// => { _: [], flag: false } + +parse('', {boolean: ['flag']}); +// => { _: [] } => flag not set similarly to other option type +``` + + + + +## [9.0.2](https://github.com/yargs/yargs-parser/compare/v9.0.1...v9.0.2) (2018-01-20) + + +### Bug Fixes + +* nargs was still aggressively consuming too many arguments ([9b28aad](https://github.com/yargs/yargs-parser/commit/9b28aad)) + + + + +## [9.0.1](https://github.com/yargs/yargs-parser/compare/v9.0.0...v9.0.1) (2018-01-20) + + +### Bug Fixes + +* nargs was consuming too many arguments ([4fef206](https://github.com/yargs/yargs-parser/commit/4fef206)) + + + + +# [9.0.0](https://github.com/yargs/yargs-parser/compare/v8.1.0...v9.0.0) (2018-01-20) + + +### Features + +* narg arguments no longer consume flag arguments ([#114](https://github.com/yargs/yargs-parser/issues/114)) ([60bb9b3](https://github.com/yargs/yargs-parser/commit/60bb9b3)) + + +### BREAKING CHANGES + +* arguments of form --foo, -abc, will no longer be consumed by nargs + + + + +# [8.1.0](https://github.com/yargs/yargs-parser/compare/v8.0.0...v8.1.0) (2017-12-20) + + +### Bug Fixes + +* allow null config values ([#108](https://github.com/yargs/yargs-parser/issues/108)) ([d8b14f9](https://github.com/yargs/yargs-parser/commit/d8b14f9)) +* ensure consistent parsing of dot-notation arguments ([#102](https://github.com/yargs/yargs-parser/issues/102)) ([c9bd79c](https://github.com/yargs/yargs-parser/commit/c9bd79c)) +* implement [@antoniom](https://github.com/antoniom)'s fix for camel-case expansion ([3087e1d](https://github.com/yargs/yargs-parser/commit/3087e1d)) +* only run coercion functions once, despite aliases. ([#76](https://github.com/yargs/yargs-parser/issues/76)) ([#103](https://github.com/yargs/yargs-parser/issues/103)) ([507aaef](https://github.com/yargs/yargs-parser/commit/507aaef)) +* scientific notation circumvented bounds check ([#110](https://github.com/yargs/yargs-parser/issues/110)) ([3571f57](https://github.com/yargs/yargs-parser/commit/3571f57)) +* tokenizer should ignore spaces at the beginning of the argString ([#106](https://github.com/yargs/yargs-parser/issues/106)) ([f34ead9](https://github.com/yargs/yargs-parser/commit/f34ead9)) + + +### Features + +* make combining arrays a configurable option ([#111](https://github.com/yargs/yargs-parser/issues/111)) ([c8bf536](https://github.com/yargs/yargs-parser/commit/c8bf536)) +* merge array from arguments with array from config ([#83](https://github.com/yargs/yargs-parser/issues/83)) ([806ddd6](https://github.com/yargs/yargs-parser/commit/806ddd6)) + + + + +# [8.0.0](https://github.com/yargs/yargs-parser/compare/v7.0.0...v8.0.0) (2017-10-05) + + +### Bug Fixes + +* Ignore multiple spaces between arguments. ([#100](https://github.com/yargs/yargs-parser/issues/100)) ([d137227](https://github.com/yargs/yargs-parser/commit/d137227)) + + +### Features + +* allow configuration of prefix for boolean negation ([#94](https://github.com/yargs/yargs-parser/issues/94)) ([00bde7d](https://github.com/yargs/yargs-parser/commit/00bde7d)) +* reworking how numbers are parsed ([#104](https://github.com/yargs/yargs-parser/issues/104)) ([fba00eb](https://github.com/yargs/yargs-parser/commit/fba00eb)) + + +### BREAKING CHANGES + +* strings that fail `Number.isSafeInteger()` are no longer coerced into numbers. + + + + +# [7.0.0](https://github.com/yargs/yargs-parser/compare/v6.0.1...v7.0.0) (2017-05-02) + + +### Chores + +* revert populate-- logic ([#91](https://github.com/yargs/yargs-parser/issues/91)) ([6003e6d](https://github.com/yargs/yargs-parser/commit/6003e6d)) + + +### BREAKING CHANGES + +* populate-- now defaults to false. + + + + +## [6.0.1](https://github.com/yargs/yargs-parser/compare/v6.0.0...v6.0.1) (2017-05-01) + + +### Bug Fixes + +* default '--' to undefined when not provided; this is closer to the array API ([#90](https://github.com/yargs/yargs-parser/issues/90)) ([4e739cc](https://github.com/yargs/yargs-parser/commit/4e739cc)) + + + + +# [6.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v6.0.0) (2017-05-01) + + +### Bug Fixes + +* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f)) +* parsing hints should apply for dot notation keys ([#86](https://github.com/yargs/yargs-parser/issues/86)) ([3e47d62](https://github.com/yargs/yargs-parser/commit/3e47d62)) + + +### Chores + +* upgrade to newest version of camelcase ([#87](https://github.com/yargs/yargs-parser/issues/87)) ([f1903aa](https://github.com/yargs/yargs-parser/commit/f1903aa)) + + +### Features + +* add -- option which allows arguments after the -- flag to be returned separated from positional arguments ([#84](https://github.com/yargs/yargs-parser/issues/84)) ([2572ca8](https://github.com/yargs/yargs-parser/commit/2572ca8)) +* when parsing stops, we now populate "--" by default ([#88](https://github.com/yargs/yargs-parser/issues/88)) ([cd666db](https://github.com/yargs/yargs-parser/commit/cd666db)) + + +### BREAKING CHANGES + +* rather than placing arguments in "_", when parsing is stopped via "--"; we now populate an array called "--" by default. +* camelcase now requires Node 4+. +* environment variables will now override config files (args, env, config-file, config-object) + + + + +# [5.0.0](https://github.com/yargs/yargs-parser/compare/v4.2.1...v5.0.0) (2017-02-18) + + +### Bug Fixes + +* environment variables should take precedence over config file ([#81](https://github.com/yargs/yargs-parser/issues/81)) ([76cee1f](https://github.com/yargs/yargs-parser/commit/76cee1f)) + + +### BREAKING CHANGES + +* environment variables will now override config files (args, env, config-file, config-object) + + + + +## [4.2.1](https://github.com/yargs/yargs-parser/compare/v4.2.0...v4.2.1) (2017-01-02) + + +### Bug Fixes + +* flatten/duplicate regression ([#75](https://github.com/yargs/yargs-parser/issues/75)) ([68d68a0](https://github.com/yargs/yargs-parser/commit/68d68a0)) + + + + +# [4.2.0](https://github.com/yargs/yargs-parser/compare/v4.1.0...v4.2.0) (2016-12-01) + + +### Bug Fixes + +* inner objects in configs had their keys appended to top-level key when dot-notation was disabled ([#72](https://github.com/yargs/yargs-parser/issues/72)) ([0b1b5f9](https://github.com/yargs/yargs-parser/commit/0b1b5f9)) + + +### Features + +* allow multiple arrays to be provided, rather than always combining ([#71](https://github.com/yargs/yargs-parser/issues/71)) ([0f0fb2d](https://github.com/yargs/yargs-parser/commit/0f0fb2d)) + + + + +# [4.1.0](https://github.com/yargs/yargs-parser/compare/v4.0.2...v4.1.0) (2016-11-07) + + +### Features + +* apply coercions to default options ([#65](https://github.com/yargs/yargs-parser/issues/65)) ([c79052b](https://github.com/yargs/yargs-parser/commit/c79052b)) +* handle dot notation boolean options ([#63](https://github.com/yargs/yargs-parser/issues/63)) ([02c3545](https://github.com/yargs/yargs-parser/commit/02c3545)) + + + + +## [4.0.2](https://github.com/yargs/yargs-parser/compare/v4.0.1...v4.0.2) (2016-09-30) + + +### Bug Fixes + +* whoops, let's make the assign not change the Object key order ([29d069a](https://github.com/yargs/yargs-parser/commit/29d069a)) + + + + +## [4.0.1](https://github.com/yargs/yargs-parser/compare/v4.0.0...v4.0.1) (2016-09-30) + + +### Bug Fixes + +* lodash.assign was deprecated ([#59](https://github.com/yargs/yargs-parser/issues/59)) ([5e7eb11](https://github.com/yargs/yargs-parser/commit/5e7eb11)) + + + + +# [4.0.0](https://github.com/yargs/yargs-parser/compare/v3.2.0...v4.0.0) (2016-09-26) + + +### Bug Fixes + +* coerce should be applied to the final objects and arrays created ([#57](https://github.com/yargs/yargs-parser/issues/57)) ([4ca69da](https://github.com/yargs/yargs-parser/commit/4ca69da)) + + +### BREAKING CHANGES + +* coerce is no longer applied to individual arguments in an implicit array. + + + + +# [3.2.0](https://github.com/yargs/yargs-parser/compare/v3.1.0...v3.2.0) (2016-08-13) + + +### Features + +* coerce full array instead of each element ([#51](https://github.com/yargs/yargs-parser/issues/51)) ([cc4dc56](https://github.com/yargs/yargs-parser/commit/cc4dc56)) + + + + +# [3.1.0](https://github.com/yargs/yargs-parser/compare/v3.0.0...v3.1.0) (2016-08-09) + + +### Bug Fixes + +* address pkgConf parsing bug outlined in [#37](https://github.com/yargs/yargs-parser/issues/37) ([#45](https://github.com/yargs/yargs-parser/issues/45)) ([be76ee6](https://github.com/yargs/yargs-parser/commit/be76ee6)) +* better parsing of negative values ([#44](https://github.com/yargs/yargs-parser/issues/44)) ([2e43692](https://github.com/yargs/yargs-parser/commit/2e43692)) +* check aliases when guessing defaults for arguments fixes [#41](https://github.com/yargs/yargs-parser/issues/41) ([#43](https://github.com/yargs/yargs-parser/issues/43)) ([f3e4616](https://github.com/yargs/yargs-parser/commit/f3e4616)) + + +### Features + +* added coerce option, for providing specialized argument parsing ([#42](https://github.com/yargs/yargs-parser/issues/42)) ([7b49cd2](https://github.com/yargs/yargs-parser/commit/7b49cd2)) + + + + +# [3.0.0](https://github.com/yargs/yargs-parser/compare/v2.4.1...v3.0.0) (2016-08-07) + + +### Bug Fixes + +* parsing issue with numeric character in group of options ([#19](https://github.com/yargs/yargs-parser/issues/19)) ([f743236](https://github.com/yargs/yargs-parser/commit/f743236)) +* upgraded lodash.assign ([5d7fdf4](https://github.com/yargs/yargs-parser/commit/5d7fdf4)) + +### BREAKING CHANGES + +* subtle change to how values are parsed in a group of single-character arguments. +* _first released in 3.1.0, better handling of negative values should be considered a breaking change._ + + + + +## [2.4.1](https://github.com/yargs/yargs-parser/compare/v2.4.0...v2.4.1) (2016-07-16) + + +### Bug Fixes + +* **count:** do not increment a default value ([#39](https://github.com/yargs/yargs-parser/issues/39)) ([b04a189](https://github.com/yargs/yargs-parser/commit/b04a189)) + + + + +# [2.4.0](https://github.com/yargs/yargs-parser/compare/v2.3.0...v2.4.0) (2016-04-11) + + +### Features + +* **environment:** Support nested options in environment variables ([#26](https://github.com/yargs/yargs-parser/issues/26)) thanks [@elas7](https://github.com/elas7) \o/ ([020778b](https://github.com/yargs/yargs-parser/commit/020778b)) + + + + +# [2.3.0](https://github.com/yargs/yargs-parser/compare/v2.2.0...v2.3.0) (2016-04-09) + + +### Bug Fixes + +* **boolean:** fix for boolean options with non boolean defaults (#20) ([2dbe86b](https://github.com/yargs/yargs-parser/commit/2dbe86b)), closes [(#20](https://github.com/(/issues/20) +* **package:** remove tests from tarball ([0353c0d](https://github.com/yargs/yargs-parser/commit/0353c0d)) +* **parsing:** handle calling short option with an empty string as the next value. ([a867165](https://github.com/yargs/yargs-parser/commit/a867165)) +* boolean flag when next value contains the strings 'true' or 'false'. ([69941a6](https://github.com/yargs/yargs-parser/commit/69941a6)) +* update dependencies; add standard-version bin for next release (#24) ([822d9d5](https://github.com/yargs/yargs-parser/commit/822d9d5)) + +### Features + +* **configuration:** Allow to pass configuration objects to yargs-parser ([0780900](https://github.com/yargs/yargs-parser/commit/0780900)) +* **normalize:** allow normalize to work with arrays ([e0eaa1a](https://github.com/yargs/yargs-parser/commit/e0eaa1a)) diff --git a/node_modules/yargs-parser/LICENSE.txt b/node_modules/yargs-parser/LICENSE.txt new file mode 100644 index 0000000..836440b --- /dev/null +++ b/node_modules/yargs-parser/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2016, Contributors + +Permission to use, copy, modify, and/or distribute this software +for any purpose with or without fee is hereby granted, provided +that the above copyright notice and this permission notice +appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES +OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE +LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/yargs-parser/README.md b/node_modules/yargs-parser/README.md new file mode 100644 index 0000000..bae61c2 --- /dev/null +++ b/node_modules/yargs-parser/README.md @@ -0,0 +1,449 @@ +# yargs-parser + +[![Build Status](https://travis-ci.org/yargs/yargs-parser.svg)](https://travis-ci.org/yargs/yargs-parser) +[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) +[![Standard Version](https://img.shields.io/badge/release-standard%20version-brightgreen.svg)](https://github.com/conventional-changelog/standard-version) + + +The mighty option parser used by [yargs](https://github.com/yargs/yargs). + +visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. + + + +## Example + +```sh +npm i yargs-parser --save +``` + +```js +var argv = require('yargs-parser')(process.argv.slice(2)) +console.log(argv) +``` + +```sh +node example.js --foo=33 --bar hello +{ _: [], foo: 33, bar: 'hello' } +``` + +_or parse a string!_ + +```js +var argv = require('yargs-parser')('--foo=99 --bar=33') +console.log(argv) +``` + +```sh +{ _: [], foo: 99, bar: 33 } +``` + +Convert an array of mixed types before passing to `yargs-parser`: + +```js +var parse = require('yargs-parser') +parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string +parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings +``` + +## API + +### require('yargs-parser')(args, opts={}) + +Parses command line arguments returning a simple mapping of keys and values. + +**expects:** + +* `args`: a string or array of strings representing the options to parse. +* `opts`: provide a set of hints indicating how `args` should be parsed: + * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. + * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.
+ Indicate that keys should be parsed as an array and coerced to booleans / numbers:
+ `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. + * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. + * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided + (or throws an error). For arrays the function is called only once for the entire array:
+ `{coerce: {foo: function (arg) {return modifiedArg}}}`. + * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). + * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:
+ `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. + * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). + * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. + * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. + * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. + * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. + * `opts.normalize`: `path.normalize()` will be applied to values set to this key. + * `opts.number`: keys should be treated as numbers. + * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). + +**returns:** + +* `obj`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. + +### require('yargs-parser').detailed(args, opts={}) + +Parses a command line string, returning detailed information required by the +yargs engine. + +**expects:** + +* `args`: a string or array of strings representing options to parse. +* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. + +**returns:** + +* `argv`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. +* `error`: populated with an error object if an exception occurred during parsing. +* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. +* `newAliases`: any new aliases added via camel-case expansion: + * `boolean`: `{ fooBar: true }` +* `defaulted`: any new argument created by `opts.default`, no aliases included. + * `boolean`: `{ foo: true }` +* `configuration`: given by default settings and `opts.configuration`. + + + +### Configuration + +The yargs-parser applies several automated transformations on the keys provided +in `args`. These features can be turned on and off using the `configuration` field +of `opts`. + +```js +var parsed = parser(['--no-dice'], { + configuration: { + 'boolean-negation': false + } +}) +``` + +### short option groups + +* default: `true`. +* key: `short-option-groups`. + +Should a group of short-options be treated as boolean flags? + +```sh +node example.js -abc +{ _: [], a: true, b: true, c: true } +``` + +_if disabled:_ + +```sh +node example.js -abc +{ _: [], abc: true } +``` + +### camel-case expansion + +* default: `true`. +* key: `camel-case-expansion`. + +Should hyphenated arguments be expanded into camel-case aliases? + +```sh +node example.js --foo-bar +{ _: [], 'foo-bar': true, fooBar: true } +``` + +_if disabled:_ + +```sh +node example.js --foo-bar +{ _: [], 'foo-bar': true } +``` + +### dot-notation + +* default: `true` +* key: `dot-notation` + +Should keys that contain `.` be treated as objects? + +```sh +node example.js --foo.bar +{ _: [], foo: { bar: true } } +``` + +_if disabled:_ + +```sh +node example.js --foo.bar +{ _: [], "foo.bar": true } +``` + +### parse numbers + +* default: `true` +* key: `parse-numbers` + +Should keys that look like numbers be treated as such? + +```sh +node example.js --foo=99.3 +{ _: [], foo: 99.3 } +``` + +_if disabled:_ + +```sh +node example.js --foo=99.3 +{ _: [], foo: "99.3" } +``` + +### boolean negation + +* default: `true` +* key: `boolean-negation` + +Should variables prefixed with `--no` be treated as negations? + +```sh +node example.js --no-foo +{ _: [], foo: false } +``` + +_if disabled:_ + +```sh +node example.js --no-foo +{ _: [], "no-foo": true } +``` + +### combine arrays + +* default: `false` +* key: `combine-arrays` + +Should arrays be combined when provided by both command line arguments and +a configuration file. + +### duplicate arguments array + +* default: `true` +* key: `duplicate-arguments-array` + +Should arguments be coerced into an array when duplicated: + +```sh +node example.js -x 1 -x 2 +{ _: [], x: [1, 2] } +``` + +_if disabled:_ + +```sh +node example.js -x 1 -x 2 +{ _: [], x: 2 } +``` + +### flatten duplicate arrays + +* default: `true` +* key: `flatten-duplicate-arrays` + +Should array arguments be coerced into a single array when duplicated: + +```sh +node example.js -x 1 2 -x 3 4 +{ _: [], x: [1, 2, 3, 4] } +``` + +_if disabled:_ + +```sh +node example.js -x 1 2 -x 3 4 +{ _: [], x: [[1, 2], [3, 4]] } +``` + +### greedy arrays + +* default: `true` +* key: `greedy-arrays` + +Should arrays consume more than one positional argument following their flag. + +```sh +node example --arr 1 2 +{ _[], arr: [1, 2] } +``` + +_if disabled:_ + +```sh +node example --arr 1 2 +{ _[2], arr: [1] } +``` + +**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** + +### nargs eats options + +* default: `false` +* key: `nargs-eats-options` + +Should nargs consume dash options as well as positional arguments. + +### negation prefix + +* default: `no-` +* key: `negation-prefix` + +The prefix to use for negated boolean variables. + +```sh +node example.js --no-foo +{ _: [], foo: false } +``` + +_if set to `quux`:_ + +```sh +node example.js --quuxfoo +{ _: [], foo: false } +``` + +### populate -- + +* default: `false`. +* key: `populate--` + +Should unparsed flags be stored in `--` or `_`. + +_If disabled:_ + +```sh +node example.js a -b -- x y +{ _: [ 'a', 'x', 'y' ], b: true } +``` + +_If enabled:_ + +```sh +node example.js a -b -- x y +{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true } +``` + +### set placeholder key + +* default: `false`. +* key: `set-placeholder-key`. + +Should a placeholder be added for keys not set via the corresponding CLI argument? + +_If disabled:_ + +```sh +node example.js -a 1 -c 2 +{ _: [], a: 1, c: 2 } +``` + +_If enabled:_ + +```sh +node example.js -a 1 -c 2 +{ _: [], a: 1, b: undefined, c: 2 } +``` + +### halt at non-option + +* default: `false`. +* key: `halt-at-non-option`. + +Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. + +_If disabled:_ + +```sh +node example.js -a run b -x y +{ _: [ 'b' ], a: 'run', x: 'y' } +``` + +_If enabled:_ + +```sh +node example.js -a run b -x y +{ _: [ 'b', '-x', 'y' ], a: 'run' } +``` + +### strip aliased + +* default: `false` +* key: `strip-aliased` + +Should aliases be removed before returning results? + +_If disabled:_ + +```sh +node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } +``` + +_If enabled:_ + +```sh +node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +### strip dashed + +* default: `false` +* key: `strip-dashed` + +Should dashed keys be removed before returning results? This option has no effect if +`camel-case-expansion` is disabled. + +_If disabled:_ + +```sh +node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +_If enabled:_ + +```sh +node example.js --test-field 1 +{ _: [], testField: 1 } +``` + +### unknown options as args + +* default: `false` +* key: `unknown-options-as-args` + +Should unknown options be treated like regular arguments? An unknown option is one that is not +configured in `opts`. + +_If disabled_ + +```sh +node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } +``` + +_If enabled_ + +```sh +node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } +``` + +## Special Thanks + +The yargs project evolves from optimist and minimist. It owes its +existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ + +## License + +ISC diff --git a/node_modules/yargs-parser/index.js b/node_modules/yargs-parser/index.js new file mode 100644 index 0000000..c14c1fc --- /dev/null +++ b/node_modules/yargs-parser/index.js @@ -0,0 +1,1032 @@ +const camelCase = require('camelcase') +const decamelize = require('decamelize') +const path = require('path') +const tokenizeArgString = require('./lib/tokenize-arg-string') +const util = require('util') + +function parse (args, opts) { + opts = Object.assign(Object.create(null), opts) + // allow a string argument to be passed in rather + // than an argv array. + args = tokenizeArgString(args) + + // aliases might have transitive relationships, normalize this. + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)) + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration) + const defaults = Object.assign(Object.create(null), opts.default) + const configObjects = opts.configObjects || [] + const envPrefix = opts.envPrefix + const notFlagsOption = configuration['populate--'] + const notFlagsArgv = notFlagsOption ? '--' : '_' + const newAliases = Object.create(null) + const defaulted = Object.create(null) + // allow a i18n handler to be passed in, default to a fake one (util.format). + const __ = opts.__ || util.format + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + } + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/ + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)') + + ;[].concat(opts.array).filter(Boolean).forEach(function (opt) { + const key = opt.key || opt + + // assign to flags[bools|strings|numbers] + const assignment = Object.keys(opt).map(function (key) { + return ({ + boolean: 'bools', + string: 'strings', + number: 'numbers' + })[key] + }).filter(Boolean).pop() + + // assign key to be coerced + if (assignment) { + flags[assignment][key] = true + } + + flags.arrays[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.boolean).filter(Boolean).forEach(function (key) { + flags.bools[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.number).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.count).filter(Boolean).forEach(function (key) { + flags.counts[key] = true + flags.keys.push(key) + }) + + ;[].concat(opts.normalize).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true + flags.keys.push(key) + }) + + Object.keys(opts.narg || {}).forEach(function (k) { + flags.nargs[k] = opts.narg[k] + flags.keys.push(k) + }) + + Object.keys(opts.coerce || {}).forEach(function (k) { + flags.coercions[k] = opts.coerce[k] + flags.keys.push(k) + }) + + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + ;[].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true + }) + } else { + Object.keys(opts.config || {}).forEach(function (k) { + flags.configs[k] = opts.config[k] + }) + } + + // create a lookup table that takes into account all + // combinations of aliases: {f: ['foo'], foo: ['f']} + extendAliases(opts.key, aliases, opts.default, flags.arrays) + + // apply default values to all aliases. + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key] + }) + }) + + let error = null + checkConfiguration() + + let notFlags = [] + + const argv = Object.assign(Object.create(null), { _: [] }) + // TODO(bcoe): for the first pass at removing object prototype we didn't + // remove all prototypes from objects returned by this API, we might want + // to gradually move towards doing so. + const argvReturn = {} + + for (let i = 0; i < args.length; i++) { + const arg = args[i] + let broken + let key + let letters + let m + let next + let value + + // any unknown option (except for end-of-options, "--") + if (arg !== '--' && isUnknownOptionAsArg(arg)) { + argv._.push(arg) + // -- separated by = + } else if (arg.match(/^--.+=/) || ( + !configuration['short-option-groups'] && arg.match(/^-.+=/) + )) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + m = arg.match(/^--?([^=]+)=([\s\S]*)$/) + + // arrays format = '--f=a b c' + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]) + } else if (checkAllAliases(m[1], flags.nargs) !== false) { + // nargs format = '--f=monkey washing cat' + i = eatNargs(i, m[1], args, m[2]) + } else { + setArg(m[1], m[2]) + } + } else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + key = arg.match(negatedBoolean)[1] + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false) + + // -- separated by space. + } else if (arg.match(/^--.+/) || ( + !configuration['short-option-groups'] && arg.match(/^-[^-]+/) + )) { + key = arg.match(/^--?(.+)/)[1] + + if (checkAllAliases(key, flags.arrays)) { + // array format = '--foo a b c' + i = eatArray(i, key, args) + } else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '--foo a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args) + } else { + next = args[i + 1] + + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next) + i++ + } else if (/^(true|false)$/.test(next)) { + setArg(key, next) + i++ + } else { + setArg(key, defaultValue(key)) + } + } + + // dot-notation flag separated by '='. + } else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/) + setArg(m[1], m[2]) + + // dot-notation flag separated by space. + } else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1] + key = arg.match(/^-(.\..+)/)[1] + + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next) + i++ + } else { + setArg(key, defaultValue(key)) + } + } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split('') + broken = false + + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2) + + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3) + key = letters[j] + + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f=a b c' + i = eatArray(i, key, args, value) + } else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f=monkey washing cat' + i = eatNargs(i, key, args, value) + } else { + setArg(key, value) + } + + broken = true + break + } + + if (next === '-') { + setArg(letters[j], next) + continue + } + + // current letter is an alphabetic character and next value is a number + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next) + broken = true + break + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next) + broken = true + break + } else { + setArg(letters[j], defaultValue(letters[j])) + } + } + + key = arg.slice(-1)[0] + + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f a b c' + i = eatArray(i, key, args) + } else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args) + } else { + next = args[i + 1] + + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next) + i++ + } else if (/^(true|false)$/.test(next)) { + setArg(key, next) + i++ + } else { + setArg(key, defaultValue(key)) + } + } + } + } else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + // single-digit boolean alias, e.g: xargs -0 + key = arg.slice(1) + setArg(key, defaultValue(key)) + } else if (arg === '--') { + notFlags = args.slice(i + 1) + break + } else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i) + break + } else { + argv._.push(maybeCoerceNumber('_', arg)) + } + } + + // order of precedence: + // 1. command line arg + // 2. value from env var + // 3. value from config file + // 4. value from config objects + // 5. configured default value + applyEnvVars(argv, true) // special case: check env vars that point to config file + applyEnvVars(argv, false) + setConfig(argv) + setConfigObjects() + applyDefaultsAndAliases(argv, flags.aliases, defaults, true) + applyCoercions(argv) + if (configuration['set-placeholder-key']) setPlaceholderKeys(argv) + + // for any counts either not in args or without an explicit default, set to 0 + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) setArg(key, 0) + }) + + // '--' defaults to undefined. + if (notFlagsOption && notFlags.length) argv[notFlagsArgv] = [] + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key) + }) + + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key] + }) + } + + if (configuration['strip-aliased']) { + ;[].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion']) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')] + } + + delete argv[alias] + }) + } + + // how many arguments should we consume, based + // on the nargs option? + function eatNargs (i, key, args, argAfterEqualSign) { + let ii + let toEat = checkAllAliases(key, flags.nargs) + // NaN has a special meaning for the array type, indicating that one or + // more values are expected. + toEat = isNaN(toEat) ? 1 : toEat + + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)) + } + setArg(key, defaultValue(key)) + return i + } + + let available = isUndefined(argAfterEqualSign) ? 0 : 1 + if (configuration['nargs-eats-options']) { + // classic behavior, yargs eats positional and dash arguments. + if (args.length - (i + 1) + available < toEat) { + error = Error(__('Not enough arguments following: %s', key)) + } + available = toEat + } else { + // nargs will not consume flag arguments, e.g., -abc, --foo, + // and terminates when one is observed. + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) available++ + else break + } + if (available < toEat) error = Error(__('Not enough arguments following: %s', key)) + } + + let consumed = Math.min(available, toEat) + if (!isUndefined(argAfterEqualSign) && consumed > 0) { + setArg(key, argAfterEqualSign) + consumed-- + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]) + } + + return (i + consumed) + } + + // if an option is an array, eat all non-hyphenated arguments + // following it... YUM! + // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] + function eatArray (i, key, args, argAfterEqualSign) { + let argsToSet = [] + let next = argAfterEqualSign || args[i + 1] + // If both array and nargs are configured, enforce the nargs count: + const nargsCount = checkAllAliases(key, flags.nargs) + + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true) + } else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + // for keys without value ==> argsToSet remains an empty [] + // set user default value, if available + if (defaults[key] !== undefined) { + const defVal = defaults[key] + argsToSet = Array.isArray(defVal) ? defVal : [defVal] + } + } else { + // value in --option=value is eaten as is + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign)) + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && argsToSet.length >= nargsCount)) break + next = args[ii] + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) break + i = ii + argsToSet.push(processValue(key, next)) + } + } + + // If both array and nargs are configured, create an error if less than + // nargs positionals were found. NaN has special meaning, indicating + // that at least one value is required (more are okay). + if ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0)) { + error = Error(__('Not enough arguments following: %s', key)) + } + + setArg(key, argsToSet) + return i + } + + function setArg (key, val) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop) + }).join('.') + addNewAlias(key, alias) + } + + const value = processValue(key, val) + const splitKey = key.split('.') + setKey(argv, splitKey, value) + + // handle populating aliases of the full key + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + x = x.split('.') + setKey(argv, x, value) + }) + } + + // handle populating aliases of the first element of the dot-notation key + if (splitKey.length > 1 && configuration['dot-notation']) { + ;(flags.aliases[splitKey[0]] || []).forEach(function (x) { + x = x.split('.') + + // expand alias with nested objects in key + const a = [].concat(splitKey) + a.shift() // nuke the old key. + x = x.concat(a) + + // populate alias only if is not already an alias of the full key + // (already populated above) + if (!(flags.aliases[key] || []).includes(x.join('.'))) { + setKey(argv, x, value) + } + }) + } + + // Set normalize getter and setter when key is in 'normalize' but isn't an array + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []) + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get () { + return val + }, + set (value) { + val = typeof value === 'string' ? path.normalize(value) : value + } + }) + }) + } + } + + function addNewAlias (key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias] + newAliases[alias] = true + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key) + } + } + + function processValue (key, val) { + // strings may be quoted, clean this up as we assign values. + if (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0] + ) { + val = val.substring(1, val.length - 1) + } + + // handle parsing boolean arguments --foo=true --bar false. + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') val = val === 'true' + } + + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v) }) + : maybeCoerceNumber(key, val) + + // increment a count given as arg (either no value or value parsed as boolean) + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment + } + + // Set normalized value when key is in 'normalize' and in 'arrays' + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) value = val.map(path.normalize) + else value = path.normalize(val) + } + return value + } + + function maybeCoerceNumber (key, value) { + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = isNumber(value) && configuration['parse-numbers'] && ( + Number.isSafeInteger(Math.floor(value)) + ) + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) value = Number(value) + } + return value + } + + // set args from config.json file, this should be + // applied last so that defaults can be applied. + function setConfig (argv) { + const configLookup = Object.create(null) + + // expand defaults/aliases, in-case any happen to reference + // the config.json file. + applyDefaultsAndAliases(configLookup, flags.aliases, defaults) + + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey] + if (configPath) { + try { + let config = null + const resolvedConfigPath = path.resolve(process.cwd(), configPath) + + if (typeof flags.configs[configKey] === 'function') { + try { + config = flags.configs[configKey](resolvedConfigPath) + } catch (e) { + config = e + } + if (config instanceof Error) { + error = config + return + } + } else { + config = require(resolvedConfigPath) + } + + setConfigObject(config) + } catch (ex) { + if (argv[configKey]) error = Error(__('Invalid JSON config file: %s', configPath)) + } + } + }) + } + + // set args from config object. + // it recursively checks nested objects. + function setConfigObject (config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key] + const fullKey = prev ? prev + '.' + key : key + + // if the value is an inner object and we have dot-notation + // enabled, treat inner objects in config the same as + // heavily nested dot notations (foo.bar.apple). + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + // if the value is an object but not an array, check nested object + setConfigObject(value, fullKey) + } else { + // setting arguments via CLI takes precedence over + // values within the config file. + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value) + } + } + }) + } + + // set all config objects passed in opts + function setConfigObjects () { + if (typeof configObjects === 'undefined') return + configObjects.forEach(function (configObject) { + setConfigObject(configObject) + }) + } + + function applyEnvVars (argv, configOnly) { + if (typeof envPrefix === 'undefined') return + + const prefix = typeof envPrefix === 'string' ? envPrefix : '' + Object.keys(process.env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + // get array of nested keys and convert them to camel case + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length) + } + return camelCase(key) + }) + + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), process.env[envVar]) + } + } + }) + } + + function applyCoercions (argv) { + let coerce + const applied = new Set() + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases + coerce = checkAllAliases(key, flags.coercions) + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])) + ;([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali) + argv[ali] = value + }) + } catch (err) { + error = err + } + } + } + }) + } + + function setPlaceholderKeys (argv) { + flags.keys.forEach((key) => { + // don't set placeholder keys for dot notation options 'foo.bar'. + if (~key.indexOf('.')) return + if (typeof argv[key] === 'undefined') argv[key] = undefined + }) + return argv + } + + function applyDefaultsAndAliases (obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]) + if (canLog) defaulted[key] = true + + ;(aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) return + setKey(obj, x.split('.'), defaults[key]) + }) + } + }) + } + + function hasKey (obj, keys) { + let o = obj + + if (!configuration['dot-notation']) keys = [keys.join('.')] + + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}) + }) + + const key = keys[keys.length - 1] + + if (typeof o !== 'object') return false + else return key in o + } + + function setKey (obj, keys, value) { + let o = obj + + if (!configuration['dot-notation']) keys = [keys.join('.')] + + keys.slice(0, -1).forEach(function (key, index) { + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + key = sanitizeKey(key) + + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {} + } + + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + // ensure that o[key] is an array, and that the last item is an empty object. + if (Array.isArray(o[key])) { + o[key].push({}) + } else { + o[key] = [o[key], {}] + } + + // we want to update the empty object at the end of the o[key] array, so set o to that object + o = o[key][o[key].length - 1] + } else { + o = o[key] + } + }) + + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + const key = sanitizeKey(keys[keys.length - 1]) + + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays) + const isValueArray = Array.isArray(value) + let duplicate = configuration['duplicate-arguments-array'] + + // nargs has higher priority than duplicate + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined + } + } + + if (value === increment) { + o[key] = increment(o[key]) + } else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]) + } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value + } else { + o[key] = o[key].concat([value]) + } + } else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value] + } else if (duplicate && !( + o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools) + )) { + o[key] = [o[key], value] + } else { + o[key] = value + } + } + + // extend the aliases list with inferred aliases. + function extendAliases (...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + // short-circuit if we've already added a key + // to the aliases array, for example it might + // exist in both 'opts.default' and 'opts.key'. + if (flags.aliases[key]) return + + flags.aliases[key] = [].concat(aliases[key] || []) + // For "--option-name", also set argv.optionName + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x) + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c) + newAliases[c] = true + } + } + }) + // For "--optionName", also set argv['option-name'] + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-') + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c) + newAliases[c] = true + } + } + }) + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y + })) + }) + }) + }) + } + + // return the 1st set flag for any of a key's aliases (or false if no flag set) + function checkAllAliases (key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key) + const keys = Object.keys(flag) + const setAlias = toCheck.find(key => keys.includes(key)) + return setAlias ? flag[setAlias] : false + } + + function hasAnyFlag (key) { + const toCheck = [].concat(Object.keys(flags).map(k => flags[k])) + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key] + }) + } + + function hasFlagsMatching (arg, ...patterns) { + const toCheck = [].concat(...patterns) + return toCheck.some(function (pattern) { + const match = arg.match(pattern) + return match && hasAnyFlag(match[1]) + }) + } + + // based on a simplified version of the short flag group parsing logic + function hasAllShortFlags (arg) { + // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { return false } + let hasAllFlags = true + let next + const letters = arg.slice(1).split('') + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2) + + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false + break + } + + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break + } + } + return hasAllFlags + } + + function isUnknownOptionAsArg (arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg) + } + + function isUnknownOption (arg) { + // ignore negative numbers + if (arg.match(negative)) { return false } + // if this is a short option group and all of them are configured, it isn't unknown + if (hasAllShortFlags(arg)) { return false } + // e.g. '--count=2' + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/ + // e.g. '-a' or '--arg' + const normalFlag = /^-+([^=]+?)$/ + // e.g. '-a-' + const flagEndingInHyphen = /^-+([^=]+?)-$/ + // e.g. '-abc123' + const flagEndingInDigits = /^-+([^=]+?\d+)$/ + // e.g. '-a/usr/local' + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/ + // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters) + } + + // make a best effor to pick a default value + // for an option based on name and type. + function defaultValue (key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key] + } else { + return defaultForType(guessType(key)) + } + } + + // return a default value, given the type of a flag., + // e.g., key of type 'string' will default to '', rather than 'true'. + function defaultForType (type) { + const def = { + boolean: true, + string: '', + number: undefined, + array: [] + } + + return def[type] + } + + // given a flag, enforce a default type. + function guessType (key) { + let type = 'boolean' + if (checkAllAliases(key, flags.strings)) type = 'string' + else if (checkAllAliases(key, flags.numbers)) type = 'number' + else if (checkAllAliases(key, flags.bools)) type = 'boolean' + else if (checkAllAliases(key, flags.arrays)) type = 'array' + return type + } + + function isNumber (x) { + if (x === null || x === undefined) return false + // if loaded from config, may already be a number. + if (typeof x === 'number') return true + // hexadecimal. + if (/^0x[0-9a-f]+$/i.test(x)) return true + // don't treat 0123 as a number; as it drops the leading '0'. + if (x.length > 1 && x[0] === '0') return false + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x) + } + + function isUndefined (num) { + return num === undefined + } + + // check user configuration settings for inconsistencies + function checkConfiguration () { + // count keys should not be set as array/narg + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)) + return true + } else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)) + return true + } + }) + } + + return { + argv: Object.assign(argvReturn, argv), + error: error, + aliases: Object.assign({}, flags.aliases), + newAliases: Object.assign({}, newAliases), + defaulted: Object.assign({}, defaulted), + configuration: configuration + } +} + +// if any aliases reference each other, we should +// merge them together. +function combineAliases (aliases) { + const aliasArrays = [] + const combined = Object.create(null) + let change = true + + // turn alias lookup hash {key: ['alias1', 'alias2']} into + // a simple array ['key', 'alias1', 'alias2'] + Object.keys(aliases).forEach(function (key) { + aliasArrays.push( + [].concat(aliases[key], key) + ) + }) + + // combine arrays until zero changes are + // made in an iteration. + while (change) { + change = false + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1 + }) + + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]) + aliasArrays.splice(ii, 1) + change = true + break + } + } + } + } + + // map arrays back to the hash-lookup (de-dupe while + // we're at it). + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i + }) + combined[aliasArray.pop()] = aliasArray + }) + + return combined +} + +// this function should only be called when a count is given as an arg +// it is NOT called to set a default value +// thus we can start the count at 1 instead of 0 +function increment (orig) { + return orig !== undefined ? orig + 1 : 1 +} + +function Parser (args, opts) { + const result = parse(args.slice(), opts) + return result.argv +} + +// parse arguments and return detailed +// meta information, aliases, etc. +Parser.detailed = function (args, opts) { + return parse(args.slice(), opts) +} + +// TODO(bcoe): in the next major version of yargs, switch to +// Object.create(null) for dot notation: +function sanitizeKey (key) { + if (key === '__proto__') return '___proto___' + return key +} + +module.exports = Parser diff --git a/node_modules/yargs-parser/lib/tokenize-arg-string.js b/node_modules/yargs-parser/lib/tokenize-arg-string.js new file mode 100644 index 0000000..260c67c --- /dev/null +++ b/node_modules/yargs-parser/lib/tokenize-arg-string.js @@ -0,0 +1,40 @@ +// take an un-split argv string and tokenize it. +module.exports = function (argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e) + } + + argString = argString.trim() + + let i = 0 + let prevC = null + let c = null + let opening = null + const args = [] + + for (let ii = 0; ii < argString.length; ii++) { + prevC = c + c = argString.charAt(ii) + + // split on spaces unless we're in quotes. + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++ + } + continue + } + + // don't split the string if we're in matching + // opening or closing single and double quotes. + if (c === opening) { + opening = null + } else if ((c === "'" || c === '"') && !opening) { + opening = c + } + + if (!args[i]) args[i] = '' + args[i] += c + } + + return args +} diff --git a/node_modules/yargs-parser/package.json b/node_modules/yargs-parser/package.json new file mode 100644 index 0000000..636ff17 --- /dev/null +++ b/node_modules/yargs-parser/package.json @@ -0,0 +1,46 @@ +{ + "name": "yargs-parser", + "version": "18.1.3", + "description": "the mighty option parser used by yargs", + "main": "index.js", + "scripts": { + "fix": "standard --fix", + "test": "c8 --reporter=text --reporter=html mocha test/*.js", + "posttest": "standard", + "coverage": "c8 report --check-coverage check-coverage --lines=100 --branches=97 --statements=100" + }, + "repository": { + "type": "git", + "url": "https://github.com/yargs/yargs-parser.git" + }, + "keywords": [ + "argument", + "parser", + "yargs", + "command", + "cli", + "parsing", + "option", + "args", + "argument" + ], + "author": "Ben Coe ", + "license": "ISC", + "devDependencies": { + "c8": "^7.0.1", + "chai": "^4.2.0", + "mocha": "^7.0.0", + "standard": "^14.3.1" + }, + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "files": [ + "lib", + "index.js" + ], + "engines": { + "node": ">=6" + } +} diff --git a/node_modules/yargs/CHANGELOG.md b/node_modules/yargs/CHANGELOG.md new file mode 100644 index 0000000..a010cf3 --- /dev/null +++ b/node_modules/yargs/CHANGELOG.md @@ -0,0 +1,420 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [15.4.0](https://www.github.com/yargs/yargs/compare/v15.3.1...v15.4.0) (2020-06-30) + + +### Features + +* adds deprecation option for commands ([027a636](https://www.github.com/yargs/yargs/commit/027a6365b737e13116811a8ef43670196e1fa00a)) +* support array of examples ([#1682](https://www.github.com/yargs/yargs/issues/1682)) ([225ab82](https://www.github.com/yargs/yargs/commit/225ab8271938bed3a48d23175f3d580ce8cd1306)) + + +### Bug Fixes + +* **docs:** describe usage of `.check()` in more detail ([932cd11](https://www.github.com/yargs/yargs/commit/932cd1177e93f5cc99edfe57a4028e30717bf8fb)) +* **i18n:** Japanese translation phrasing ([#1619](https://www.github.com/yargs/yargs/issues/1619)) ([0894175](https://www.github.com/yargs/yargs/commit/089417550ef5a5b8ce3578dd2a989191300b64cd)) +* **strict mode:** report default command unknown arguments ([#1626](https://www.github.com/yargs/yargs/issues/1626)) ([69f29a9](https://www.github.com/yargs/yargs/commit/69f29a9cd429d4bb99481238305390107ac75b02)) +* **usage:** translate 'options' group only when displaying help ([#1600](https://www.github.com/yargs/yargs/issues/1600)) ([e60b39b](https://www.github.com/yargs/yargs/commit/e60b39b9d3a912c06db43f87c86ba894142b6c1c)) + + +### Reverts + +* Revert "chore(deps): update dependency eslint to v7 (#1656)" (#1673) ([34949f8](https://www.github.com/yargs/yargs/commit/34949f89ee7cdf88f7b315659df4b5f62f714842)), closes [#1656](https://www.github.com/yargs/yargs/issues/1656) [#1673](https://www.github.com/yargs/yargs/issues/1673) + +### [15.3.1](https://www.github.com/yargs/yargs/compare/v15.3.0...v15.3.1) (2020-03-16) + + +### Bug Fixes + +* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential +prototype pollution vulnerability. This was reported by the Snyk Security Research Team. ([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2)) + +## [15.3.0](https://www.github.com/yargs/yargs/compare/v15.2.0...v15.3.0) (2020-03-08) + + +### Features + +* **yargs-parser:** introduce single-digit boolean aliases ([#1576](https://www.github.com/yargs/yargs/issues/1576)) ([3af7f04](https://www.github.com/yargs/yargs/commit/3af7f04cdbfcbd4b3f432aca5144d43f21958c39)) +* add usage for single-digit boolean aliases ([#1580](https://www.github.com/yargs/yargs/issues/1580)) ([6014e39](https://www.github.com/yargs/yargs/commit/6014e39bca3a1e8445aa0fb2a435f6181e344c45)) + + +### Bug Fixes + +* address ambiguity between nargs of 1 and requiresArg ([#1572](https://www.github.com/yargs/yargs/issues/1572)) ([a5edc32](https://www.github.com/yargs/yargs/commit/a5edc328ecb3f90d1ba09cfe70a0040f68adf50a)) + +## [15.2.0](https://www.github.com/yargs/yargs/compare/v15.1.0...v15.2.0) (2020-03-01) + + +### ⚠ BREAKING CHANGES + +* **deps:** yargs-parser@17.0.0 no longer implicitly creates arrays out of boolean +arguments when duplicates are provided + +### Features + +* **completion:** takes negated flags into account when boolean-negation is set ([#1509](https://www.github.com/yargs/yargs/issues/1509)) ([7293ad5](https://www.github.com/yargs/yargs/commit/7293ad50d20ea0fb7dd1ac9b925e90e1bd95dea8)) +* **deps:** pull in yargs-parser@17.0.0 ([#1553](https://www.github.com/yargs/yargs/issues/1553)) ([b9409da](https://www.github.com/yargs/yargs/commit/b9409da199ebca515a848489c206b807fab2e65d)) +* deprecateOption ([#1559](https://www.github.com/yargs/yargs/issues/1559)) ([8aae333](https://www.github.com/yargs/yargs/commit/8aae3332251d09fa136db17ef4a40d83fa052bc4)) +* display appropriate $0 for electron apps ([#1536](https://www.github.com/yargs/yargs/issues/1536)) ([d0e4379](https://www.github.com/yargs/yargs/commit/d0e437912917d6a66bb5128992fa2f566a5f830b)) +* introduces strictCommands() subset of strict mode ([#1540](https://www.github.com/yargs/yargs/issues/1540)) ([1d4cca3](https://www.github.com/yargs/yargs/commit/1d4cca395a98b395e6318f0505fc73bef8b01350)) +* **deps:** yargs-parser with 'greedy-array' configuration ([#1569](https://www.github.com/yargs/yargs/issues/1569)) ([a03a320](https://www.github.com/yargs/yargs/commit/a03a320dbf5c0ce33d829a857fc04a651c0bb53e)) + + +### Bug Fixes + +* help always displayed for the first command parsed having an async handler ([#1535](https://www.github.com/yargs/yargs/issues/1535)) ([d585b30](https://www.github.com/yargs/yargs/commit/d585b303a43746201b05c9c9fda94a444634df33)) +* **deps:** fix enumeration for normalized path arguments ([#1567](https://www.github.com/yargs/yargs/issues/1567)) ([0b5b1b0](https://www.github.com/yargs/yargs/commit/0b5b1b0e5f4f9baf393c48e9cc2bc85c1b67a47a)) +* **locales:** only translate default option group name ([acc16de](https://www.github.com/yargs/yargs/commit/acc16de6b846ea7332db753646a9cec76b589162)) +* **locales:** remove extra space in French for 'default' ([#1564](https://www.github.com/yargs/yargs/issues/1564)) ([ecfc2c4](https://www.github.com/yargs/yargs/commit/ecfc2c474575c6cdbc6d273c94c13181bd1dbaa6)) +* **translations:** add French translation for unknown command ([#1563](https://www.github.com/yargs/yargs/issues/1563)) ([18b0b75](https://www.github.com/yargs/yargs/commit/18b0b752424bf560271e670ff95a0f90c8386787)) +* **translations:** fix pluralization in error messages. ([#1557](https://www.github.com/yargs/yargs/issues/1557)) ([94fa38c](https://www.github.com/yargs/yargs/commit/94fa38cbab8d86943e87bf41d368ed56dffa6835)) +* **yargs:** correct support of bundled electron apps ([#1554](https://www.github.com/yargs/yargs/issues/1554)) ([a0b61ac](https://www.github.com/yargs/yargs/commit/a0b61ac21e2b554aa73dbf1a66d4a7af94047c2f)) + +## [15.1.0](https://www.github.com/yargs/yargs/compare/v15.0.2...v15.1.0) (2020-01-02) + + +### Features + +* **lang:** add Finnish localization (language code fi) ([222c8fe](https://www.github.com/yargs/yargs/commit/222c8fef2e2ad46e314c337dec96940f896bec35)) +* complete short options with a single dash ([#1507](https://www.github.com/yargs/yargs/issues/1507)) ([99011ab](https://www.github.com/yargs/yargs/commit/99011ab5ba90232506ece0a17e59e2001a1ab562)) +* onFinishCommand handler ([#1473](https://www.github.com/yargs/yargs/issues/1473)) ([fe380cd](https://www.github.com/yargs/yargs/commit/fe380cd356aa33aef0449facd59c22cab8930ac9)) + + +### Bug Fixes + +* getCompletion() was not working for options ([#1495](https://www.github.com/yargs/yargs/issues/1495)) ([463feb2](https://www.github.com/yargs/yargs/commit/463feb2870158eb9df670222b0f0a40a05cf18d0)) +* misspelling of package.json `engines` field ([0891d0e](https://www.github.com/yargs/yargs/commit/0891d0ed35b30c83a6d9e9f6a5c5f84d13c546a0)) +* populate positionals when unknown-options-as-args is set ([#1508](https://www.github.com/yargs/yargs/issues/1508)) ([bb0f2eb](https://www.github.com/yargs/yargs/commit/bb0f2eb996fa4e19d330b31a01c2036cafa99a7e)), closes [#1444](https://www.github.com/yargs/yargs/issues/1444) +* show 2 dashes on help for single digit option key or alias ([#1493](https://www.github.com/yargs/yargs/issues/1493)) ([63b3dd3](https://www.github.com/yargs/yargs/commit/63b3dd31a455d428902220c1992ae930e18aff5c)) +* **docs:** use recommended cjs import syntax for ts examples ([#1513](https://www.github.com/yargs/yargs/issues/1513)) ([f9a18bf](https://www.github.com/yargs/yargs/commit/f9a18bfd624a5013108084f690cd8a1de794c430)) + +### [15.0.2](https://www.github.com/yargs/yargs/compare/v15.0.1...v15.0.2) (2019-11-19) + + +### Bug Fixes + +* temporary fix for libraries that call Object.freeze() ([#1483](https://www.github.com/yargs/yargs/issues/1483)) ([99c2dc8](https://www.github.com/yargs/yargs/commit/99c2dc850e67c606644f8b0c0bca1a59c87dcbcd)) + +### [15.0.1](https://www.github.com/yargs/yargs/compare/v15.0.0...v15.0.1) (2019-11-16) + + +### Bug Fixes + +* **deps:** cliui, find-up, and string-width, all drop Node 6 support ([#1479](https://www.github.com/yargs/yargs/issues/1479)) ([6a9ebe2](https://www.github.com/yargs/yargs/commit/6a9ebe2d955e3e979e76c07ffbb1c17fef64cb49)) + +## [15.0.0](https://www.github.com/yargs/yargs/compare/v14.2.0...v15.0.0) (2019-11-10) + + +### ⚠ BREAKING CHANGES + +* **deps:** yargs-parser now throws on invalid combinations of config (#1470) +* yargs-parser@16.0.0 drops support for Node 6 +* drop Node 6 support (#1461) +* remove package.json-based parserConfiguration (#1460) + +### Features + +* **deps:** yargs-parser now throws on invalid combinations of config ([#1470](https://www.github.com/yargs/yargs/issues/1470)) ([c10c38c](https://www.github.com/yargs/yargs/commit/c10c38cca04298f96b55a7e374a9a134abefffa7)) +* expose `Parser` from `require('yargs/yargs')` ([#1477](https://www.github.com/yargs/yargs/issues/1477)) ([1840ba2](https://www.github.com/yargs/yargs/commit/1840ba22f1a24c0ece8e32bbd31db4134a080aee)) + + +### Bug Fixes + +* **docs:** TypeScript import to prevent a future major release warning ([#1441](https://www.github.com/yargs/yargs/issues/1441)) ([b1b156a](https://www.github.com/yargs/yargs/commit/b1b156a3eb4ddd6803fbbd56c611a77919293000)) +* stop-parse was not being respected by commands ([#1459](https://www.github.com/yargs/yargs/issues/1459)) ([12c82e6](https://www.github.com/yargs/yargs/commit/12c82e62663e928148a7ee2f51629aa26a0f9bb2)) +* update to yargs-parser with fix for array default values ([#1463](https://www.github.com/yargs/yargs/issues/1463)) ([ebee59d](https://www.github.com/yargs/yargs/commit/ebee59d9022da538410e69a5c025019ed46d13d2)) +* **docs:** update boolean description and examples in docs ([#1474](https://www.github.com/yargs/yargs/issues/1474)) ([afd5b48](https://www.github.com/yargs/yargs/commit/afd5b4871bfeb90d58351ac56c5c44a83ef033e6)) + + +### Miscellaneous Chores + +* drop Node 6 support ([#1461](https://www.github.com/yargs/yargs/issues/1461)) ([2ba8ce0](https://www.github.com/yargs/yargs/commit/2ba8ce05e8fefbeffc6cb7488d9ebf6e86cceb1d)) + + +### Code Refactoring + +* remove package.json-based parserConfiguration ([#1460](https://www.github.com/yargs/yargs/issues/1460)) ([0d3642b](https://www.github.com/yargs/yargs/commit/0d3642b6f829b637938774c0c6ce5f6bfe1afa51)) + +## [14.2.0](https://github.com/yargs/yargs/compare/v14.1.0...v14.2.0) (2019-10-07) + + +### Bug Fixes + +* async middleware was called twice ([#1422](https://github.com/yargs/yargs/issues/1422)) ([9a42b63](https://github.com/yargs/yargs/commit/9a42b63)) +* fix promise check to accept any spec conform object ([#1424](https://github.com/yargs/yargs/issues/1424)) ([0be43d2](https://github.com/yargs/yargs/commit/0be43d2)) +* groups were not being maintained for nested commands ([#1430](https://github.com/yargs/yargs/issues/1430)) ([d38650e](https://github.com/yargs/yargs/commit/d38650e)) +* **docs:** broken markdown link ([#1426](https://github.com/yargs/yargs/issues/1426)) ([236e24e](https://github.com/yargs/yargs/commit/236e24e)) +* support merging deeply nested configuration ([#1423](https://github.com/yargs/yargs/issues/1423)) ([bae66fe](https://github.com/yargs/yargs/commit/bae66fe)) + + +### Features + +* **deps:** introduce yargs-parser with support for unknown-options-as-args ([#1440](https://github.com/yargs/yargs/issues/1440)) ([4d21520](https://github.com/yargs/yargs/commit/4d21520)) + +## [14.1.0](https://github.com/yargs/yargs/compare/v14.0.0...v14.1.0) (2019-09-06) + + +### Bug Fixes + +* **docs:** fix incorrect parserConfiguration documentation ([2a99124](https://github.com/yargs/yargs/commit/2a99124)) +* detect zsh when zsh isnt run as a login prompt ([#1395](https://github.com/yargs/yargs/issues/1395)) ([8792d13](https://github.com/yargs/yargs/commit/8792d13)) +* populate correct value on yargs.parsed and stop warning on access ([#1412](https://github.com/yargs/yargs/issues/1412)) ([bb0eb52](https://github.com/yargs/yargs/commit/bb0eb52)) +* showCompletionScript was logging script twice ([#1388](https://github.com/yargs/yargs/issues/1388)) ([07c8537](https://github.com/yargs/yargs/commit/07c8537)) +* strict() should not ignore hyphenated arguments ([#1414](https://github.com/yargs/yargs/issues/1414)) ([b774b5e](https://github.com/yargs/yargs/commit/b774b5e)) +* **docs:** formalize existing callback argument to showHelp ([#1386](https://github.com/yargs/yargs/issues/1386)) ([d217764](https://github.com/yargs/yargs/commit/d217764)) + + +### Features + +* make it possible to merge configurations when extending other config. ([#1411](https://github.com/yargs/yargs/issues/1411)) ([5d7ad98](https://github.com/yargs/yargs/commit/5d7ad98)) + +## [14.0.0](https://github.com/yargs/yargs/compare/v13.3.0...v14.0.0) (2019-07-30) + + +### ⚠ BREAKING CHANGES + +* we now only officially support yargs.$0 parameter and discourage direct access to yargs.parsed +* previously to this fix methods like `yargs.getOptions()` contained the state of the last command to execute. +* do not allow additional positionals in strict mode + +### Bug Fixes + +* calling parse multiple times now appropriately maintains state ([#1137](https://github.com/yargs/yargs/issues/1137)) ([#1369](https://github.com/yargs/yargs/issues/1369)) ([026b151](https://github.com/yargs/yargs/commit/026b151)) +* prefer user supplied script name in usage ([#1383](https://github.com/yargs/yargs/issues/1383)) ([28c74b9](https://github.com/yargs/yargs/commit/28c74b9)) +* **deps:** use decamelize from npm instead of vendored copy ([#1377](https://github.com/yargs/yargs/issues/1377)) ([015eeb9](https://github.com/yargs/yargs/commit/015eeb9)) +* **examples:** fix usage-options.js to reflect current API ([#1375](https://github.com/yargs/yargs/issues/1375)) ([6e5b76b](https://github.com/yargs/yargs/commit/6e5b76b)) +* do not allow additional positionals in strict mode ([35d777c](https://github.com/yargs/yargs/commit/35d777c)) +* properties accessed on singleton now reflect current state of instance ([#1366](https://github.com/yargs/yargs/issues/1366)) ([409d35b](https://github.com/yargs/yargs/commit/409d35b)) +* tolerate null prototype for config objects with `extends` ([#1376](https://github.com/yargs/yargs/issues/1376)) ([3d26d11](https://github.com/yargs/yargs/commit/3d26d11)), closes [#1372](https://github.com/yargs/yargs/issues/1372) +* yargs.parsed now populated before returning, when yargs.parse() called with no args (#1382) ([e3981fd](https://github.com/yargs/yargs/commit/e3981fd)), closes [#1382](https://github.com/yargs/yargs/issues/1382) + +### Features + +* adds support for multiple epilog messages ([#1384](https://github.com/yargs/yargs/issues/1384)) ([07a5554](https://github.com/yargs/yargs/commit/07a5554)) +* allow completionCommand to be set via showCompletionScript ([#1385](https://github.com/yargs/yargs/issues/1385)) ([5562853](https://github.com/yargs/yargs/commit/5562853)) + +## [13.3.0](https://www.github.com/yargs/yargs/compare/v13.2.4...v13.3.0) (2019-06-10) + + +### Bug Fixes + +* **deps:** yargs-parser update addressing several parsing bugs ([#1357](https://www.github.com/yargs/yargs/issues/1357)) ([e230d5b](https://www.github.com/yargs/yargs/commit/e230d5b)) + + +### Features + +* **i18n:** swap out os-locale dependency for simple inline implementation ([#1356](https://www.github.com/yargs/yargs/issues/1356)) ([4dfa19b](https://www.github.com/yargs/yargs/commit/4dfa19b)) +* support defaultDescription for positional arguments ([812048c](https://www.github.com/yargs/yargs/commit/812048c)) + +### [13.2.4](https://github.com/yargs/yargs/compare/v13.2.3...v13.2.4) (2019-05-13) + + +### Bug Fixes + +* **i18n:** rename unclear 'implication failed' to 'missing dependent arguments' ([#1317](https://github.com/yargs/yargs/issues/1317)) ([bf46813](https://github.com/yargs/yargs/commit/bf46813)) + + + +### [13.2.3](https://github.com/yargs/yargs/compare/v13.2.2...v13.2.3) (2019-05-05) + + +### Bug Fixes + +* **deps:** upgrade cliui for compatibility with latest chalk. ([#1330](https://github.com/yargs/yargs/issues/1330)) ([b20db65](https://github.com/yargs/yargs/commit/b20db65)) +* address issues with dutch translation ([#1316](https://github.com/yargs/yargs/issues/1316)) ([0295132](https://github.com/yargs/yargs/commit/0295132)) + + +### Tests + +* accept differently formatted output ([#1327](https://github.com/yargs/yargs/issues/1327)) ([c294d1b](https://github.com/yargs/yargs/commit/c294d1b)) + + + +## [13.2.2](https://github.com/yargs/yargs/compare/v13.2.1...v13.2.2) (2019-03-06) + + + +## [13.2.1](https://github.com/yargs/yargs/compare/v13.2.0...v13.2.1) (2019-02-18) + + +### Bug Fixes + +* add zsh script to files array ([3180224](https://github.com/yargs/yargs/commit/3180224)) +* support options/sub-commands in zsh completion ([0a96394](https://github.com/yargs/yargs/commit/0a96394)) + + +# [13.2.0](https://github.com/yargs/yargs/compare/v13.1.0...v13.2.0) (2019-02-15) + + +### Features + +* zsh auto completion ([#1292](https://github.com/yargs/yargs/issues/1292)) ([16c5d25](https://github.com/yargs/yargs/commit/16c5d25)), closes [#1156](https://github.com/yargs/yargs/issues/1156) + + + +# [13.1.0](https://github.com/yargs/yargs/compare/v13.0.0...v13.1.0) (2019-02-12) + + +### Features + +* add applyBeforeValidation, for applying sync middleware before validation ([5be206a](https://github.com/yargs/yargs/commit/5be206a)) + + + + +# [13.0.0](https://github.com/yargs/yargs/compare/v12.0.5...v13.0.0) (2019-02-02) + + +### Bug Fixes + +* **deps:** Update os-locale to avoid security vulnerability ([#1270](https://github.com/yargs/yargs/issues/1270)) ([27bf739](https://github.com/yargs/yargs/commit/27bf739)) +* **validation:** Use the error as a message when none exists otherwise ([#1268](https://github.com/yargs/yargs/issues/1268)) ([0510fe6](https://github.com/yargs/yargs/commit/0510fe6)) +* better bash path completion ([#1272](https://github.com/yargs/yargs/issues/1272)) ([da75ea2](https://github.com/yargs/yargs/commit/da75ea2)) +* middleware added multiple times due to reference bug ([#1282](https://github.com/yargs/yargs/issues/1282)) ([64af518](https://github.com/yargs/yargs/commit/64af518)) + + +### Chores + +* ~drop Node 6 from testing matrix ([#1287](https://github.com/yargs/yargs/issues/1287)) ([ef16792](https://github.com/yargs/yargs/commit/ef16792))~ + * _opting to not drop Node 6 support until April, [see](https://github.com/nodejs/Release)._ +* update dependencies ([#1284](https://github.com/yargs/yargs/issues/1284)) ([f25de4f](https://github.com/yargs/yargs/commit/f25de4f)) + + +### Features + +* Add `.parserConfiguration()` method, deprecating package.json config ([#1262](https://github.com/yargs/yargs/issues/1262)) ([3c6869a](https://github.com/yargs/yargs/commit/3c6869a)) +* adds config option for sorting command output ([#1256](https://github.com/yargs/yargs/issues/1256)) ([6916ce9](https://github.com/yargs/yargs/commit/6916ce9)) +* options/positionals with leading '+' and '0' no longer parse as numbers ([#1286](https://github.com/yargs/yargs/issues/1286)) ([e9dc3aa](https://github.com/yargs/yargs/commit/e9dc3aa)) +* support promises in middleware ([f3a4e4f](https://github.com/yargs/yargs/commit/f3a4e4f)) + + +### BREAKING CHANGES + +* options with leading '+' or '0' now parse as strings +* dropping Node 6 which hits end of life in April 2019 +* see [yargs-parser@12.0.0 CHANGELOG](https://github.com/yargs/yargs-parser/blob/master/CHANGELOG.md#breaking-changes) +* we now warn if the yargs stanza package.json is used. + + + + +## [12.0.5](https://github.com/yargs/yargs/compare/v12.0.4...v12.0.5) (2018-11-19) + + +### Bug Fixes + +* allows camel-case, variadic arguments, and strict mode to be combined ([#1247](https://github.com/yargs/yargs/issues/1247)) ([eacc035](https://github.com/yargs/yargs/commit/eacc035)) + + + + +## [12.0.4](https://github.com/yargs/yargs/compare/v12.0.3...v12.0.4) (2018-11-10) + + +### Bug Fixes + +* don't load config when processing positionals ([5d0dc92](https://github.com/yargs/yargs/commit/5d0dc92)) + + + + +## [12.0.3](https://github.com/yargs/yargs/compare/v12.0.2...v12.0.3) (2018-10-06) + + +### Bug Fixes + +* $0 contains first arg in bundled electron apps ([#1206](https://github.com/yargs/yargs/issues/1206)) ([567820b](https://github.com/yargs/yargs/commit/567820b)) +* accept single function for middleware ([66fd6f7](https://github.com/yargs/yargs/commit/66fd6f7)), closes [#1214](https://github.com/yargs/yargs/issues/1214) [#1214](https://github.com/yargs/yargs/issues/1214) +* hide `hidden` options from help output even if they are in a group ([#1221](https://github.com/yargs/yargs/issues/1221)) ([da54028](https://github.com/yargs/yargs/commit/da54028)) +* improve Norwegian Bokmål translations ([#1208](https://github.com/yargs/yargs/issues/1208)) ([a458fa4](https://github.com/yargs/yargs/commit/a458fa4)) +* improve Norwegian Nynorsk translations ([#1207](https://github.com/yargs/yargs/issues/1207)) ([d422eb5](https://github.com/yargs/yargs/commit/d422eb5)) + + + + +## [12.0.2](https://github.com/yargs/yargs/compare/v12.0.1...v12.0.2) (2018-09-04) + + +### Bug Fixes + +* middleware should work regardless of when method is called ([664b265](https://github.com/yargs/yargs/commit/664b265)), closes [#1178](https://github.com/yargs/yargs/issues/1178) +* translation not working when using __ with a single parameter ([#1183](https://github.com/yargs/yargs/issues/1183)) ([f449aea](https://github.com/yargs/yargs/commit/f449aea)) +* upgrade os-locale to version that addresses license issue ([#1195](https://github.com/yargs/yargs/issues/1195)) ([efc0970](https://github.com/yargs/yargs/commit/efc0970)) + + + + +## [12.0.1](https://github.com/yargs/yargs/compare/v12.0.0...v12.0.1) (2018-06-29) + + + + +# [12.0.0](https://github.com/yargs/yargs/compare/v11.1.0...v12.0.0) (2018-06-26) + + +### Bug Fixes + +* .argv and .parse() now invoke identical code path ([#1126](https://github.com/yargs/yargs/issues/1126)) ([f13ebf4](https://github.com/yargs/yargs/commit/f13ebf4)) +* remove the trailing white spaces from the help output ([#1090](https://github.com/yargs/yargs/issues/1090)) ([3f0746c](https://github.com/yargs/yargs/commit/3f0746c)) +* **completion:** Avoid default command and recommendations during completion ([#1123](https://github.com/yargs/yargs/issues/1123)) ([036e7c5](https://github.com/yargs/yargs/commit/036e7c5)) + + +### Chores + +* test Node.js 6, 8 and 10 ([#1160](https://github.com/yargs/yargs/issues/1160)) ([84f9d2b](https://github.com/yargs/yargs/commit/84f9d2b)) +* upgrade to version of yargs-parser that does not populate value for unset boolean ([#1104](https://github.com/yargs/yargs/issues/1104)) ([d4705f4](https://github.com/yargs/yargs/commit/d4705f4)) + + +### Features + +* add support for global middleware, useful for shared tasks like metrics ([#1119](https://github.com/yargs/yargs/issues/1119)) ([9d71ac7](https://github.com/yargs/yargs/commit/9d71ac7)) +* allow setting scriptName $0 ([#1143](https://github.com/yargs/yargs/issues/1143)) ([a2f2eae](https://github.com/yargs/yargs/commit/a2f2eae)) +* remove `setPlaceholderKeys` ([#1105](https://github.com/yargs/yargs/issues/1105)) ([6ee2c82](https://github.com/yargs/yargs/commit/6ee2c82)) + + +### BREAKING CHANGES + +* Options absent from `argv` (not set via CLI argument) are now absent from the parsed result object rather than being set with `undefined` +* drop Node 4 from testing matrix, such that we'll gradually start drifting away from supporting Node 4. +* yargs-parser does not populate 'false' when boolean flag is not passed +* tests that assert against help output will need to be updated + + + + +# [11.1.0](https://github.com/yargs/yargs/compare/v11.0.0...v11.1.0) (2018-03-04) + + +### Bug Fixes + +* choose correct config directory when require.main does not exist ([#1056](https://github.com/yargs/yargs/issues/1056)) ([a04678c](https://github.com/yargs/yargs/commit/a04678c)) + + +### Features + +* allow hidden options to be displayed with --show-hidden ([#1061](https://github.com/yargs/yargs/issues/1061)) ([ea862ae](https://github.com/yargs/yargs/commit/ea862ae)) +* extend *.rc files in addition to json ([#1080](https://github.com/yargs/yargs/issues/1080)) ([11691a6](https://github.com/yargs/yargs/commit/11691a6)) + + + + +# [11.0.0](https://github.com/yargs/yargs/compare/v10.1.2...v11.0.0) (2018-01-22) + + +### Bug Fixes + +* Set implicit nargs=1 when type=number requiresArg=true ([#1050](https://github.com/yargs/yargs/issues/1050)) ([2b56812](https://github.com/yargs/yargs/commit/2b56812)) + + +### Features + +* requiresArg is now simply an alias for nargs(1) ([#1054](https://github.com/yargs/yargs/issues/1054)) ([a3ddacc](https://github.com/yargs/yargs/commit/a3ddacc)) + + +### BREAKING CHANGES + +* requiresArg now has significantly different error output, matching nargs. + +[Historical Versions](/docs/CHANGELOG-historical.md) diff --git a/node_modules/yargs/LICENSE b/node_modules/yargs/LICENSE new file mode 100644 index 0000000..b0145ca --- /dev/null +++ b/node_modules/yargs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright 2010 James Halliday (mail@substack.net); Modified work Copyright 2014 Contributors (ben@npmjs.com) + +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/node_modules/yargs/README.md b/node_modules/yargs/README.md new file mode 100644 index 0000000..0db992b --- /dev/null +++ b/node_modules/yargs/README.md @@ -0,0 +1,140 @@ +

+ +

+

Yargs

+

+ Yargs be a node.js library fer hearties tryin' ter parse optstrings +

+ +
+ +[![Build Status][travis-image]][travis-url] +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Coverage][coverage-image]][coverage-url] +[![Conventional Commits][conventional-commits-image]][conventional-commits-url] +[![Slack][slack-image]][slack-url] + +## Description : +Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. + +It gives you: + +* commands and (grouped) options (`my-program.js serve --port=5000`). +* a dynamically generated help menu based on your arguments. + +> + +* bash-completion shortcuts for commands and options. +* and [tons more](/docs/api.md). + +## Installation + +Stable version: +```bash +npm i yargs +``` + +Bleeding edge version with the most recent features: +```bash +npm i yargs@next +``` + +## Usage : + +### Simple Example + +```javascript +#!/usr/bin/env node +const {argv} = require('yargs') + +if (argv.ships > 3 && argv.distance < 53.5) { + console.log('Plunder more riffiwobbles!') +} else { + console.log('Retreat from the xupptumblers!') +} +``` + +```bash +$ ./plunder.js --ships=4 --distance=22 +Plunder more riffiwobbles! + +$ ./plunder.js --ships 12 --distance 98.7 +Retreat from the xupptumblers! +``` + +### Complex Example + +```javascript +#!/usr/bin/env node +require('yargs') // eslint-disable-line + .command('serve [port]', 'start the server', (yargs) => { + yargs + .positional('port', { + describe: 'port to bind on', + default: 5000 + }) + }, (argv) => { + if (argv.verbose) console.info(`start server on :${argv.port}`) + serve(argv.port) + }) + .option('verbose', { + alias: 'v', + type: 'boolean', + description: 'Run with verbose logging' + }) + .argv +``` + +Run the example above with `--help` to see the help for the application. + +## TypeScript + +yargs has type definitions at [@types/yargs][type-definitions]. + +``` +npm i @types/yargs --save-dev +``` + +See usage examples in [docs](/docs/typescript.md). + +## Webpack + +See usage examples of yargs with webpack in [docs](/docs/webpack.md). + +## Community : + +Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). + +## Documentation : + +### Table of Contents + +* [Yargs' API](/docs/api.md) +* [Examples](/docs/examples.md) +* [Parsing Tricks](/docs/tricks.md) + * [Stop the Parser](/docs/tricks.md#stop) + * [Negating Boolean Arguments](/docs/tricks.md#negate) + * [Numbers](/docs/tricks.md#numbers) + * [Arrays](/docs/tricks.md#arrays) + * [Objects](/docs/tricks.md#objects) + * [Quotes](/docs/tricks.md#quotes) +* [Advanced Topics](/docs/advanced.md) + * [Composing Your App Using Commands](/docs/advanced.md#commands) + * [Building Configurable CLI Apps](/docs/advanced.md#configuration) + * [Customizing Yargs' Parser](/docs/advanced.md#customizing) +* [Contributing](/contributing.md) + +[travis-url]: https://travis-ci.org/yargs/yargs +[travis-image]: https://img.shields.io/travis/yargs/yargs/master.svg +[npm-url]: https://www.npmjs.com/package/yargs +[npm-image]: https://img.shields.io/npm/v/yargs.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: http://standardjs.com/ +[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg +[conventional-commits-url]: https://conventionalcommits.org/ +[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg +[slack-url]: http://devtoolscommunity.herokuapp.com +[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs +[coverage-image]: https://img.shields.io/nycrc/yargs/yargs +[coverage-url]: https://github.com/yargs/yargs/blob/master/.nycrc diff --git a/node_modules/yargs/build/lib/apply-extends.d.ts b/node_modules/yargs/build/lib/apply-extends.d.ts new file mode 100644 index 0000000..5a9aca7 --- /dev/null +++ b/node_modules/yargs/build/lib/apply-extends.d.ts @@ -0,0 +1,2 @@ +import { Dictionary } from './common-types'; +export declare function applyExtends(config: Dictionary, cwd: string, mergeExtends?: boolean): Dictionary; diff --git a/node_modules/yargs/build/lib/apply-extends.js b/node_modules/yargs/build/lib/apply-extends.js new file mode 100644 index 0000000..005734a --- /dev/null +++ b/node_modules/yargs/build/lib/apply-extends.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.applyExtends = void 0; +const fs = require("fs"); +const path = require("path"); +const yerror_1 = require("./yerror"); +let previouslyVisitedConfigs = []; +function checkForCircularExtends(cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new yerror_1.YError(`Circular extended configurations: '${cfgPath}'.`); + } +} +function getPathToDefaultConfig(cwd, pathToExtend) { + return path.resolve(cwd, pathToExtend); +} +function mergeDeep(config1, config2) { + const target = {}; + function isObject(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); + } + Object.assign(target, config1); + for (const key of Object.keys(config2)) { + if (isObject(config2[key]) && isObject(target[key])) { + target[key] = mergeDeep(config1[key], config2[key]); + } + else { + target[key] = config2[key]; + } + } + return target; +} +function applyExtends(config, cwd, mergeExtends = false) { + let defaultConfig = {}; + if (Object.prototype.hasOwnProperty.call(config, 'extends')) { + if (typeof config.extends !== 'string') + return defaultConfig; + const isPath = /\.json|\..*rc$/.test(config.extends); + let pathToDefault = null; + if (!isPath) { + try { + pathToDefault = require.resolve(config.extends); + } + catch (err) { + // most likely this simply isn't a module. + } + } + else { + pathToDefault = getPathToDefaultConfig(cwd, config.extends); + } + // maybe the module uses key for some other reason, + // err on side of caution. + if (!pathToDefault && !isPath) + return config; + if (!pathToDefault) + throw new yerror_1.YError(`Unable to find extended config '${config.extends}' in '${cwd}'.`); + checkForCircularExtends(pathToDefault); + previouslyVisitedConfigs.push(pathToDefault); + defaultConfig = isPath ? JSON.parse(fs.readFileSync(pathToDefault, 'utf8')) : require(config.extends); + delete config.extends; + defaultConfig = applyExtends(defaultConfig, path.dirname(pathToDefault), mergeExtends); + } + previouslyVisitedConfigs = []; + return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config); +} +exports.applyExtends = applyExtends; diff --git a/node_modules/yargs/build/lib/argsert.d.ts b/node_modules/yargs/build/lib/argsert.d.ts new file mode 100644 index 0000000..6f7a83f --- /dev/null +++ b/node_modules/yargs/build/lib/argsert.d.ts @@ -0,0 +1,2 @@ +export declare function argsert(callerArguments: any[], length?: number): void; +export declare function argsert(expected: string, callerArguments: any[], length?: number): void; diff --git a/node_modules/yargs/build/lib/argsert.js b/node_modules/yargs/build/lib/argsert.js new file mode 100644 index 0000000..40cb091 --- /dev/null +++ b/node_modules/yargs/build/lib/argsert.js @@ -0,0 +1,65 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.argsert = void 0; +const yerror_1 = require("./yerror"); +const parse_command_1 = require("./parse-command"); +const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; +function argsert(arg1, arg2, arg3) { + function parseArgs() { + return typeof arg1 === 'object' + ? [{ demanded: [], optional: [] }, arg1, arg2] + : [parse_command_1.parseCommand(`cmd ${arg1}`), arg2, arg3]; + } + // TODO: should this eventually raise an exception. + try { + // preface the argument description with "cmd", so + // that we can run it through yargs' command parser. + let position = 0; + let [parsed, callerArguments, length] = parseArgs(); + const args = [].slice.call(callerArguments); + while (args.length && args[args.length - 1] === undefined) + args.pop(); + length = length || args.length; + if (length < parsed.demanded.length) { + throw new yerror_1.YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); + } + const totalCommands = parsed.demanded.length + parsed.optional.length; + if (length > totalCommands) { + throw new yerror_1.YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); + } + parsed.demanded.forEach((demanded) => { + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, demanded.cmd, position); + position += 1; + }); + parsed.optional.forEach((optional) => { + if (args.length === 0) + return; + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, optional.cmd, position); + position += 1; + }); + } + catch (err) { + console.warn(err.stack); + } +} +exports.argsert = argsert; +function guessType(arg) { + if (Array.isArray(arg)) { + return 'array'; + } + else if (arg === null) { + return 'null'; + } + return typeof arg; +} +function argumentTypeError(observedType, allowedTypes, position) { + throw new yerror_1.YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); +} diff --git a/node_modules/yargs/build/lib/command.d.ts b/node_modules/yargs/build/lib/command.d.ts new file mode 100644 index 0000000..9db6ab5 --- /dev/null +++ b/node_modules/yargs/build/lib/command.d.ts @@ -0,0 +1,64 @@ +/// +import { Dictionary } from './common-types'; +import { Middleware } from './middleware'; +import { Positional } from './parse-command'; +import { RequireDirectoryOptions } from 'require-directory'; +import { UsageInstance } from './usage'; +import { ValidationInstance } from './validation'; +import { YargsInstance, Options, OptionDefinition, Context, Arguments, DetailedArguments } from './yargs'; +export declare function command(yargs: YargsInstance, usage: UsageInstance, validation: ValidationInstance, globalMiddleware?: Middleware[]): CommandInstance; +/** Instance of the command module. */ +export interface CommandInstance { + addDirectory(dir: string, context: Context, req: NodeRequireFunction, callerFile: string, opts?: RequireDirectoryOptions): void; + addHandler(handler: CommandHandlerDefinition): void; + addHandler(cmd: string | string[], description: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback, commandMiddleware?: Middleware[], deprecated?: boolean): void; + cmdToParseOptions(cmdString: string): Positionals; + freeze(): void; + getCommandHandlers(): Dictionary; + getCommands(): string[]; + hasDefaultCommand(): boolean; + reset(): CommandInstance; + runCommand(command: string | null, yargs: YargsInstance, parsed: DetailedArguments, commandIndex?: number): Arguments | Promise; + runDefaultBuilderOn(yargs: YargsInstance): void; + unfreeze(): void; +} +export interface CommandHandlerDefinition extends Partial> { + aliases?: string[]; + builder?: CommandBuilder | CommandBuilderDefinition; + command?: string | string[]; + desc?: CommandHandler['description']; + describe?: CommandHandler['description']; +} +export declare function isCommandHandlerDefinition(cmd: string | string[] | CommandHandlerDefinition): cmd is CommandHandlerDefinition; +export interface CommandBuilderDefinition { + builder?: CommandBuilder; + deprecated?: boolean; + handler: CommandHandlerCallback; + middlewares?: Middleware[]; +} +export declare function isCommandBuilderDefinition(builder?: CommandBuilder | CommandBuilderDefinition): builder is CommandBuilderDefinition; +export interface CommandHandlerCallback { + (argv: Arguments): any; +} +export interface CommandHandler { + builder: CommandBuilder; + demanded: Positional[]; + deprecated?: boolean; + description?: string | false; + handler: CommandHandlerCallback; + middlewares: Middleware[]; + optional: Positional[]; + original: string; +} +export declare type CommandBuilder = CommandBuilderCallback | Dictionary; +interface CommandBuilderCallback { + (y: YargsInstance): YargsInstance | void; +} +export declare function isCommandBuilderCallback(builder: CommandBuilder): builder is CommandBuilderCallback; +interface Positionals extends Pick { + demand: Dictionary; +} +export interface FinishCommandHandler { + (handlerResult: any): any; +} +export {}; diff --git a/node_modules/yargs/build/lib/command.js b/node_modules/yargs/build/lib/command.js new file mode 100644 index 0000000..d90c455 --- /dev/null +++ b/node_modules/yargs/build/lib/command.js @@ -0,0 +1,416 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isCommandBuilderCallback = exports.isCommandBuilderDefinition = exports.isCommandHandlerDefinition = exports.command = void 0; +const common_types_1 = require("./common-types"); +const is_promise_1 = require("./is-promise"); +const middleware_1 = require("./middleware"); +const parse_command_1 = require("./parse-command"); +const path = require("path"); +const util_1 = require("util"); +const yargs_1 = require("./yargs"); +const requireDirectory = require("require-directory"); +const whichModule = require("which-module"); +const Parser = require("yargs-parser"); +const DEFAULT_MARKER = /(^\*)|(^\$0)/; +// handles parsing positional arguments, +// and populating argv with said positional +// arguments. +function command(yargs, usage, validation, globalMiddleware = []) { + const self = {}; + let handlers = {}; + let aliasMap = {}; + let defaultCommand; + self.addHandler = function addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { + let aliases = []; + const middlewares = middleware_1.commandMiddlewareFactory(commandMiddleware); + handler = handler || (() => { }); + if (Array.isArray(cmd)) { + aliases = cmd.slice(1); + cmd = cmd[0]; + } + else if (isCommandHandlerDefinition(cmd)) { + let command = (Array.isArray(cmd.command) || typeof cmd.command === 'string') ? cmd.command : moduleName(cmd); + if (cmd.aliases) + command = [].concat(command).concat(cmd.aliases); + self.addHandler(command, extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); + return; + } + // allow a module to be provided instead of separate builder and handler + if (isCommandBuilderDefinition(builder)) { + self.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); + return; + } + // parse positionals out of cmd string + const parsedCommand = parse_command_1.parseCommand(cmd); + // remove positional args from aliases only + aliases = aliases.map(alias => parse_command_1.parseCommand(alias).cmd); + // check for default and filter out '*'' + let isDefault = false; + const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => { + if (DEFAULT_MARKER.test(c)) { + isDefault = true; + return false; + } + return true; + }); + // standardize on $0 for default command. + if (parsedAliases.length === 0 && isDefault) + parsedAliases.push('$0'); + // shift cmd and aliases after filtering out '*' + if (isDefault) { + parsedCommand.cmd = parsedAliases[0]; + aliases = parsedAliases.slice(1); + cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); + } + // populate aliasMap + aliases.forEach((alias) => { + aliasMap[alias] = parsedCommand.cmd; + }); + if (description !== false) { + usage.command(cmd, description, isDefault, aliases, deprecated); + } + handlers[parsedCommand.cmd] = { + original: cmd, + description, + handler, + builder: builder || {}, + middlewares, + deprecated, + demanded: parsedCommand.demanded, + optional: parsedCommand.optional + }; + if (isDefault) + defaultCommand = handlers[parsedCommand.cmd]; + }; + self.addDirectory = function addDirectory(dir, context, req, callerFile, opts) { + opts = opts || {}; + // disable recursion to support nested directories of subcommands + if (typeof opts.recurse !== 'boolean') + opts.recurse = false; + // exclude 'json', 'coffee' from require-directory defaults + if (!Array.isArray(opts.extensions)) + opts.extensions = ['js']; + // allow consumer to define their own visitor function + const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o; + // call addHandler via visitor function + opts.visit = function visit(obj, joined, filename) { + const visited = parentVisit(obj, joined, filename); + // allow consumer to skip modules with their own visitor + if (visited) { + // check for cyclic reference + // each command file path should only be seen once per execution + if (~context.files.indexOf(joined)) + return visited; + // keep track of visited files in context.files + context.files.push(joined); + self.addHandler(visited); + } + return visited; + }; + requireDirectory({ require: req, filename: callerFile }, dir, opts); + }; + // lookup module object from require()d command and derive name + // if module was not require()d and no name given, throw error + function moduleName(obj) { + const mod = whichModule(obj); + if (!mod) + throw new Error(`No command name given for module: ${util_1.inspect(obj)}`); + return commandFromFilename(mod.filename); + } + // derive command name from filename + function commandFromFilename(filename) { + return path.basename(filename, path.extname(filename)); + } + function extractDesc({ describe, description, desc }) { + for (const test of [describe, description, desc]) { + if (typeof test === 'string' || test === false) + return test; + common_types_1.assertNotStrictEqual(test, true); + } + return false; + } + self.getCommands = () => Object.keys(handlers).concat(Object.keys(aliasMap)); + self.getCommandHandlers = () => handlers; + self.hasDefaultCommand = () => !!defaultCommand; + self.runCommand = function runCommand(command, yargs, parsed, commandIndex) { + let aliases = parsed.aliases; + const commandHandler = handlers[command] || handlers[aliasMap[command]] || defaultCommand; + const currentContext = yargs.getContext(); + let numFiles = currentContext.files.length; + const parentCommands = currentContext.commands.slice(); + // what does yargs look like after the builder is run? + let innerArgv = parsed.argv; + let positionalMap = {}; + if (command) { + currentContext.commands.push(command); + currentContext.fullCommands.push(commandHandler.original); + } + const builder = commandHandler.builder; + if (isCommandBuilderCallback(builder)) { + // a function can be provided, which builds + // up a yargs chain and possibly returns it. + const builderOutput = builder(yargs.reset(parsed.aliases)); + const innerYargs = yargs_1.isYargsInstance(builderOutput) ? builderOutput : yargs; + if (shouldUpdateUsage(innerYargs)) { + innerYargs.getUsageInstance().usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); + } + innerArgv = innerYargs._parseArgs(null, null, true, commandIndex); + aliases = innerYargs.parsed.aliases; + } + else if (isCommandBuilderOptionDefinitions(builder)) { + // as a short hand, an object can instead be provided, specifying + // the options that a command takes. + const innerYargs = yargs.reset(parsed.aliases); + if (shouldUpdateUsage(innerYargs)) { + innerYargs.getUsageInstance().usage(usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); + } + Object.keys(commandHandler.builder).forEach((key) => { + innerYargs.option(key, builder[key]); + }); + innerArgv = innerYargs._parseArgs(null, null, true, commandIndex); + aliases = innerYargs.parsed.aliases; + } + if (!yargs._hasOutput()) { + positionalMap = populatePositionals(commandHandler, innerArgv, currentContext); + } + const middlewares = globalMiddleware.slice(0).concat(commandHandler.middlewares); + middleware_1.applyMiddleware(innerArgv, yargs, middlewares, true); + // we apply validation post-hoc, so that custom + // checks get passed populated positional arguments. + if (!yargs._hasOutput()) { + yargs._runValidation(innerArgv, aliases, positionalMap, yargs.parsed.error, !command); + } + if (commandHandler.handler && !yargs._hasOutput()) { + yargs._setHasOutput(); + // to simplify the parsing of positionals in commands, + // we temporarily populate '--' rather than _, with arguments + const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; + if (!populateDoubleDash) + yargs._copyDoubleDash(innerArgv); + innerArgv = middleware_1.applyMiddleware(innerArgv, yargs, middlewares, false); + let handlerResult; + if (is_promise_1.isPromise(innerArgv)) { + handlerResult = innerArgv.then(argv => commandHandler.handler(argv)); + } + else { + handlerResult = commandHandler.handler(innerArgv); + } + const handlerFinishCommand = yargs.getHandlerFinishCommand(); + if (is_promise_1.isPromise(handlerResult)) { + yargs.getUsageInstance().cacheHelpMessage(); + handlerResult + .then(value => { + if (handlerFinishCommand) { + handlerFinishCommand(value); + } + }) + .catch(error => { + try { + yargs.getUsageInstance().fail(null, error); + } + catch (err) { + // fail's throwing would cause an unhandled rejection. + } + }) + .then(() => { + yargs.getUsageInstance().clearCachedHelpMessage(); + }); + } + else { + if (handlerFinishCommand) { + handlerFinishCommand(handlerResult); + } + } + } + if (command) { + currentContext.commands.pop(); + currentContext.fullCommands.pop(); + } + numFiles = currentContext.files.length - numFiles; + if (numFiles > 0) + currentContext.files.splice(numFiles * -1, numFiles); + return innerArgv; + }; + function shouldUpdateUsage(yargs) { + return !yargs.getUsageInstance().getUsageDisabled() && + yargs.getUsageInstance().getUsage().length === 0; + } + function usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { + const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() : commandHandler.original; + const pc = parentCommands.filter((c) => { return !DEFAULT_MARKER.test(c); }); + pc.push(c); + return `$0 ${pc.join(' ')}`; + } + self.runDefaultBuilderOn = function (yargs) { + common_types_1.assertNotStrictEqual(defaultCommand, undefined); + if (shouldUpdateUsage(yargs)) { + // build the root-level command string from the default string. + const commandString = DEFAULT_MARKER.test(defaultCommand.original) + ? defaultCommand.original : defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); + yargs.getUsageInstance().usage(commandString, defaultCommand.description); + } + const builder = defaultCommand.builder; + if (isCommandBuilderCallback(builder)) { + builder(yargs); + } + else { + Object.keys(builder).forEach((key) => { + yargs.option(key, builder[key]); + }); + } + }; + // transcribe all positional arguments "command [apple]" + // onto argv. + function populatePositionals(commandHandler, argv, context) { + argv._ = argv._.slice(context.commands.length); // nuke the current commands + const demanded = commandHandler.demanded.slice(0); + const optional = commandHandler.optional.slice(0); + const positionalMap = {}; + validation.positionalCount(demanded.length, argv._.length); + while (demanded.length) { + const demand = demanded.shift(); + populatePositional(demand, argv, positionalMap); + } + while (optional.length) { + const maybe = optional.shift(); + populatePositional(maybe, argv, positionalMap); + } + argv._ = context.commands.concat(argv._); + postProcessPositionals(argv, positionalMap, self.cmdToParseOptions(commandHandler.original)); + return positionalMap; + } + function populatePositional(positional, argv, positionalMap) { + const cmd = positional.cmd[0]; + if (positional.variadic) { + positionalMap[cmd] = argv._.splice(0).map(String); + } + else { + if (argv._.length) + positionalMap[cmd] = [String(argv._.shift())]; + } + } + // we run yargs-parser against the positional arguments + // applying the same parsing logic used for flags. + function postProcessPositionals(argv, positionalMap, parseOptions) { + // combine the parsing hints we've inferred from the command + // string with explicitly configured parsing hints. + const options = Object.assign({}, yargs.getOptions()); + options.default = Object.assign(parseOptions.default, options.default); + for (const key of Object.keys(parseOptions.alias)) { + options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); + } + options.array = options.array.concat(parseOptions.array); + delete options.config; // don't load config when processing positionals. + const unparsed = []; + Object.keys(positionalMap).forEach((key) => { + positionalMap[key].map((value) => { + if (options.configuration['unknown-options-as-args']) + options.key[key] = true; + unparsed.push(`--${key}`); + unparsed.push(value); + }); + }); + // short-circuit parse. + if (!unparsed.length) + return; + const config = Object.assign({}, options.configuration, { + 'populate--': true + }); + const parsed = Parser.detailed(unparsed, Object.assign({}, options, { + configuration: config + })); + if (parsed.error) { + yargs.getUsageInstance().fail(parsed.error.message, parsed.error); + } + else { + // only copy over positional keys (don't overwrite + // flag arguments that were already parsed). + const positionalKeys = Object.keys(positionalMap); + Object.keys(positionalMap).forEach((key) => { + positionalKeys.push(...parsed.aliases[key]); + }); + Object.keys(parsed.argv).forEach((key) => { + if (positionalKeys.indexOf(key) !== -1) { + // any new aliases need to be placed in positionalMap, which + // is used for validation. + if (!positionalMap[key]) + positionalMap[key] = parsed.argv[key]; + argv[key] = parsed.argv[key]; + } + }); + } + } + self.cmdToParseOptions = function (cmdString) { + const parseOptions = { + array: [], + default: {}, + alias: {}, + demand: {} + }; + const parsed = parse_command_1.parseCommand(cmdString); + parsed.demanded.forEach((d) => { + const [cmd, ...aliases] = d.cmd; + if (d.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + parseOptions.demand[cmd] = true; + }); + parsed.optional.forEach((o) => { + const [cmd, ...aliases] = o.cmd; + if (o.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + }); + return parseOptions; + }; + self.reset = () => { + handlers = {}; + aliasMap = {}; + defaultCommand = undefined; + return self; + }; + // used by yargs.parse() to freeze + // the state of commands such that + // we can apply .parse() multiple times + // with the same yargs instance. + const frozens = []; + self.freeze = () => { + frozens.push({ + handlers, + aliasMap, + defaultCommand + }); + }; + self.unfreeze = () => { + const frozen = frozens.pop(); + common_types_1.assertNotStrictEqual(frozen, undefined); + ({ + handlers, + aliasMap, + defaultCommand + } = frozen); + }; + return self; +} +exports.command = command; +function isCommandHandlerDefinition(cmd) { + return typeof cmd === 'object'; +} +exports.isCommandHandlerDefinition = isCommandHandlerDefinition; +function isCommandBuilderDefinition(builder) { + return typeof builder === 'object' && + !!builder.builder && + typeof builder.handler === 'function'; +} +exports.isCommandBuilderDefinition = isCommandBuilderDefinition; +function isCommandBuilderCallback(builder) { + return typeof builder === 'function'; +} +exports.isCommandBuilderCallback = isCommandBuilderCallback; +function isCommandBuilderOptionDefinitions(builder) { + return typeof builder === 'object'; +} diff --git a/node_modules/yargs/build/lib/common-types.d.ts b/node_modules/yargs/build/lib/common-types.d.ts new file mode 100644 index 0000000..f83c0dd --- /dev/null +++ b/node_modules/yargs/build/lib/common-types.d.ts @@ -0,0 +1,36 @@ +/** + * An object whose all properties have the same type. + */ +export declare type Dictionary = { + [key: string]: T; +}; +/** + * Returns the keys of T that match Dictionary and are not arrays. + */ +export declare type DictionaryKeyof = Exclude>, KeyOf>; +/** + * Returns the keys of T that match U. + */ +export declare type KeyOf = Exclude<{ + [K in keyof T]: T[K] extends U ? K : never; +}[keyof T], undefined>; +/** + * An array whose first element is not undefined. + */ +export declare type NotEmptyArray = [T, ...T[]]; +/** + * Returns the type of a Dictionary or array values. + */ +export declare type ValueOf = T extends (infer U)[] ? U : T[keyof T]; +/** + * Typing wrapper around assert.notStrictEqual() + */ +export declare function assertNotStrictEqual(actual: T | N, expected: N, message?: string | Error): asserts actual is Exclude; +/** + * Asserts actual is a single key, not a key array or a key map. + */ +export declare function assertSingleKey(actual: string | string[] | Dictionary): asserts actual is string; +/** + * Typing wrapper around Object.keys() + */ +export declare function objectKeys(object: T): (keyof T)[]; diff --git a/node_modules/yargs/build/lib/common-types.js b/node_modules/yargs/build/lib/common-types.js new file mode 100644 index 0000000..3064cbf --- /dev/null +++ b/node_modules/yargs/build/lib/common-types.js @@ -0,0 +1,25 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.objectKeys = exports.assertSingleKey = exports.assertNotStrictEqual = void 0; +const assert_1 = require("assert"); +/** + * Typing wrapper around assert.notStrictEqual() + */ +function assertNotStrictEqual(actual, expected, message) { + assert_1.notStrictEqual(actual, expected, message); +} +exports.assertNotStrictEqual = assertNotStrictEqual; +/** + * Asserts actual is a single key, not a key array or a key map. + */ +function assertSingleKey(actual) { + assert_1.strictEqual(typeof actual, 'string'); +} +exports.assertSingleKey = assertSingleKey; +/** + * Typing wrapper around Object.keys() + */ +function objectKeys(object) { + return Object.keys(object); +} +exports.objectKeys = objectKeys; diff --git a/node_modules/yargs/build/lib/completion-templates.d.ts b/node_modules/yargs/build/lib/completion-templates.d.ts new file mode 100644 index 0000000..67bcd30 --- /dev/null +++ b/node_modules/yargs/build/lib/completion-templates.d.ts @@ -0,0 +1,2 @@ +export declare const completionShTemplate = "###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_yargs_completions()\n{\n local cur_word args type_list\n\n cur_word=\"${COMP_WORDS[COMP_CWORD]}\"\n args=(\"${COMP_WORDS[@]}\")\n\n # ask yargs to generate completions.\n type_list=$({{app_path}} --get-yargs-completions \"${args[@]}\")\n\n COMPREPLY=( $(compgen -W \"${type_list}\" -- ${cur_word}) )\n\n # if no match was found, fall back to filename completion\n if [ ${#COMPREPLY[@]} -eq 0 ]; then\n COMPREPLY=()\n fi\n\n return 0\n}\ncomplete -o default -F _yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n"; +export declare const completionZshTemplate = "###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local reply\n local si=$IFS\n IFS=$'\n' reply=($(COMP_CWORD=\"$((CURRENT-1))\" COMP_LINE=\"$BUFFER\" COMP_POINT=\"$CURSOR\" {{app_path}} --get-yargs-completions \"${words[@]}\"))\n IFS=$si\n _describe 'values' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n"; diff --git a/node_modules/yargs/build/lib/completion-templates.js b/node_modules/yargs/build/lib/completion-templates.js new file mode 100644 index 0000000..3ee0e06 --- /dev/null +++ b/node_modules/yargs/build/lib/completion-templates.js @@ -0,0 +1,50 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.completionZshTemplate = exports.completionShTemplate = void 0; +exports.completionShTemplate = `###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc +# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. +# +_yargs_completions() +{ + local cur_word args type_list + + cur_word="\${COMP_WORDS[COMP_CWORD]}" + args=("\${COMP_WORDS[@]}") + + # ask yargs to generate completions. + type_list=$({{app_path}} --get-yargs-completions "\${args[@]}") + + COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) ) + + # if no match was found, fall back to filename completion + if [ \${#COMPREPLY[@]} -eq 0 ]; then + COMPREPLY=() + fi + + return 0 +} +complete -o default -F _yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; +exports.completionZshTemplate = `###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc +# or {{app_path}} {{completion_command}} >> ~/.zsh_profile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local reply + local si=$IFS + IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) + IFS=$si + _describe 'values' reply +} +compdef _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; diff --git a/node_modules/yargs/build/lib/completion.d.ts b/node_modules/yargs/build/lib/completion.d.ts new file mode 100644 index 0000000..176a91b --- /dev/null +++ b/node_modules/yargs/build/lib/completion.d.ts @@ -0,0 +1,21 @@ +import { CommandInstance } from './command'; +import { UsageInstance } from './usage'; +import { YargsInstance } from './yargs'; +import { Arguments, DetailedArguments } from 'yargs-parser'; +export declare function completion(yargs: YargsInstance, usage: UsageInstance, command: CommandInstance): CompletionInstance; +/** Instance of the completion module. */ +export interface CompletionInstance { + completionKey: string; + generateCompletionScript($0: string, cmd: string): string; + getCompletion(args: string[], done: (completions: string[]) => any): any; + registerFunction(fn: CompletionFunction): void; + setParsed(parsed: DetailedArguments): void; +} +export declare type CompletionFunction = SyncCompletionFunction | AsyncCompletionFunction; +interface SyncCompletionFunction { + (current: string, argv: Arguments): string[] | Promise; +} +interface AsyncCompletionFunction { + (current: string, argv: Arguments, done: (completions: string[]) => any): any; +} +export {}; diff --git a/node_modules/yargs/build/lib/completion.js b/node_modules/yargs/build/lib/completion.js new file mode 100644 index 0000000..d65925a --- /dev/null +++ b/node_modules/yargs/build/lib/completion.js @@ -0,0 +1,135 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.completion = void 0; +const command_1 = require("./command"); +const templates = require("./completion-templates"); +const is_promise_1 = require("./is-promise"); +const parse_command_1 = require("./parse-command"); +const path = require("path"); +const common_types_1 = require("./common-types"); +// add bash completions to your +// yargs-powered applications. +function completion(yargs, usage, command) { + const self = { + completionKey: 'get-yargs-completions' + }; + let aliases; + self.setParsed = function setParsed(parsed) { + aliases = parsed.aliases; + }; + const zshShell = (process.env.SHELL && process.env.SHELL.indexOf('zsh') !== -1) || + (process.env.ZSH_NAME && process.env.ZSH_NAME.indexOf('zsh') !== -1); + // get a list of completion commands. + // 'args' is the array of strings from the line to be completed + self.getCompletion = function getCompletion(args, done) { + const completions = []; + const current = args.length ? args[args.length - 1] : ''; + const argv = yargs.parse(args, true); + const parentCommands = yargs.getContext().commands; + // a custom completion function can be provided + // to completion(). + function runCompletionFunction(argv) { + common_types_1.assertNotStrictEqual(completionFunction, null); + if (isSyncCompletionFunction(completionFunction)) { + const result = completionFunction(current, argv); + // promise based completion function. + if (is_promise_1.isPromise(result)) { + return result.then((list) => { + process.nextTick(() => { done(list); }); + }).catch((err) => { + process.nextTick(() => { throw err; }); + }); + } + // synchronous completion function. + return done(result); + } + else { + // asynchronous completion function + return completionFunction(current, argv, (completions) => { + done(completions); + }); + } + } + if (completionFunction) { + return is_promise_1.isPromise(argv) ? argv.then(runCompletionFunction) : runCompletionFunction(argv); + } + const handlers = command.getCommandHandlers(); + for (let i = 0, ii = args.length; i < ii; ++i) { + if (handlers[args[i]] && handlers[args[i]].builder) { + const builder = handlers[args[i]].builder; + if (command_1.isCommandBuilderCallback(builder)) { + const y = yargs.reset(); + builder(y); + return y.argv; + } + } + } + if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current) { + usage.getCommands().forEach((usageCommand) => { + const commandName = parse_command_1.parseCommand(usageCommand[0]).cmd; + if (args.indexOf(commandName) === -1) { + if (!zshShell) { + completions.push(commandName); + } + else { + const desc = usageCommand[1] || ''; + completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); + } + } + }); + } + if (current.match(/^-/) || (current === '' && completions.length === 0)) { + const descs = usage.getDescriptions(); + const options = yargs.getOptions(); + Object.keys(options.key).forEach((key) => { + const negable = !!options.configuration['boolean-negation'] && options.boolean.includes(key); + // If the key and its aliases aren't in 'args', add the key to 'completions' + let keyAndAliases = [key].concat(aliases[key] || []); + if (negable) + keyAndAliases = keyAndAliases.concat(keyAndAliases.map(key => `no-${key}`)); + function completeOptionKey(key) { + const notInArgs = keyAndAliases.every(val => args.indexOf(`--${val}`) === -1); + if (notInArgs) { + const startsByTwoDashes = (s) => /^--/.test(s); + const isShortOption = (s) => /^[^0-9]$/.test(s); + const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; + if (!zshShell) { + completions.push(dashes + key); + } + else { + const desc = descs[key] || ''; + completions.push(dashes + `${key.replace(/:/g, '\\:')}:${desc.replace('__yargsString__:', '')}`); + } + } + } + completeOptionKey(key); + if (negable && !!options.default[key]) + completeOptionKey(`no-${key}`); + }); + } + done(completions); + }; + // generate the completion script to add to your .bashrc. + self.generateCompletionScript = function generateCompletionScript($0, cmd) { + let script = zshShell ? templates.completionZshTemplate : templates.completionShTemplate; + const name = path.basename($0); + // add ./to applications not yet installed as bin. + if ($0.match(/\.js$/)) + $0 = `./${$0}`; + script = script.replace(/{{app_name}}/g, name); + script = script.replace(/{{completion_command}}/g, cmd); + return script.replace(/{{app_path}}/g, $0); + }; + // register a function to perform your own custom + // completions., this function can be either + // synchrnous or asynchronous. + let completionFunction = null; + self.registerFunction = (fn) => { + completionFunction = fn; + }; + return self; +} +exports.completion = completion; +function isSyncCompletionFunction(completionFunction) { + return completionFunction.length < 3; +} diff --git a/node_modules/yargs/build/lib/is-promise.d.ts b/node_modules/yargs/build/lib/is-promise.d.ts new file mode 100644 index 0000000..19b5566 --- /dev/null +++ b/node_modules/yargs/build/lib/is-promise.d.ts @@ -0,0 +1 @@ +export declare function isPromise(maybePromise: T | Promise): maybePromise is Promise; diff --git a/node_modules/yargs/build/lib/is-promise.js b/node_modules/yargs/build/lib/is-promise.js new file mode 100644 index 0000000..c24f9a8 --- /dev/null +++ b/node_modules/yargs/build/lib/is-promise.js @@ -0,0 +1,9 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isPromise = void 0; +function isPromise(maybePromise) { + return !!maybePromise && + !!maybePromise.then && + (typeof maybePromise.then === 'function'); +} +exports.isPromise = isPromise; diff --git a/node_modules/yargs/build/lib/levenshtein.d.ts b/node_modules/yargs/build/lib/levenshtein.d.ts new file mode 100644 index 0000000..08b6b7f --- /dev/null +++ b/node_modules/yargs/build/lib/levenshtein.d.ts @@ -0,0 +1 @@ +export declare function levenshtein(a: string, b: string): number; diff --git a/node_modules/yargs/build/lib/levenshtein.js b/node_modules/yargs/build/lib/levenshtein.js new file mode 100644 index 0000000..84c0831 --- /dev/null +++ b/node_modules/yargs/build/lib/levenshtein.js @@ -0,0 +1,58 @@ +"use strict"; +/* +Copyright (c) 2011 Andrei Mackenzie + +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. +*/ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.levenshtein = void 0; +// levenshtein distance algorithm, pulled from Andrei Mackenzie's MIT licensed. +// gist, which can be found here: https://gist.github.com/andrei-m/982927 +// Compute the edit distance between the two given strings +function levenshtein(a, b) { + if (a.length === 0) + return b.length; + if (b.length === 0) + return a.length; + const matrix = []; + // increment along the first column of each row + let i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } + // increment each column in the first row + let j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } + // Fill in the rest of the matrix + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } + else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, // substitution + Math.min(matrix[i][j - 1] + 1, // insertion + matrix[i - 1][j] + 1)); // deletion + } + } + } + return matrix[b.length][a.length]; +} +exports.levenshtein = levenshtein; diff --git a/node_modules/yargs/build/lib/middleware.d.ts b/node_modules/yargs/build/lib/middleware.d.ts new file mode 100644 index 0000000..8fa7c34 --- /dev/null +++ b/node_modules/yargs/build/lib/middleware.d.ts @@ -0,0 +1,10 @@ +import { YargsInstance, Arguments } from './yargs'; +export declare function globalMiddlewareFactory(globalMiddleware: Middleware[], context: T): (callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation?: boolean) => T; +export declare function commandMiddlewareFactory(commandMiddleware?: MiddlewareCallback[]): Middleware[]; +export declare function applyMiddleware(argv: Arguments | Promise, yargs: YargsInstance, middlewares: Middleware[], beforeValidation: boolean): Arguments | Promise; +export interface MiddlewareCallback { + (argv: Arguments, yargs: YargsInstance): Partial | Promise>; +} +export interface Middleware extends MiddlewareCallback { + applyBeforeValidation: boolean; +} diff --git a/node_modules/yargs/build/lib/middleware.js b/node_modules/yargs/build/lib/middleware.js new file mode 100644 index 0000000..e93b6d2 --- /dev/null +++ b/node_modules/yargs/build/lib/middleware.js @@ -0,0 +1,57 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.applyMiddleware = exports.commandMiddlewareFactory = exports.globalMiddlewareFactory = void 0; +const argsert_1 = require("./argsert"); +const is_promise_1 = require("./is-promise"); +function globalMiddlewareFactory(globalMiddleware, context) { + return function (callback, applyBeforeValidation = false) { + argsert_1.argsert(' [boolean]', [callback, applyBeforeValidation], arguments.length); + if (Array.isArray(callback)) { + for (let i = 0; i < callback.length; i++) { + if (typeof callback[i] !== 'function') { + throw Error('middleware must be a function'); + } + callback[i].applyBeforeValidation = applyBeforeValidation; + } + Array.prototype.push.apply(globalMiddleware, callback); + } + else if (typeof callback === 'function') { + callback.applyBeforeValidation = applyBeforeValidation; + globalMiddleware.push(callback); + } + return context; + }; +} +exports.globalMiddlewareFactory = globalMiddlewareFactory; +function commandMiddlewareFactory(commandMiddleware) { + if (!commandMiddleware) + return []; + return commandMiddleware.map(middleware => { + middleware.applyBeforeValidation = false; + return middleware; + }); +} +exports.commandMiddlewareFactory = commandMiddlewareFactory; +function applyMiddleware(argv, yargs, middlewares, beforeValidation) { + const beforeValidationError = new Error('middleware cannot return a promise when applyBeforeValidation is true'); + return middlewares + .reduce((acc, middleware) => { + if (middleware.applyBeforeValidation !== beforeValidation) { + return acc; + } + if (is_promise_1.isPromise(acc)) { + return acc + .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) + .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); + } + else { + const result = middleware(acc, yargs); + if (beforeValidation && is_promise_1.isPromise(result)) + throw beforeValidationError; + return is_promise_1.isPromise(result) + ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) + : Object.assign(acc, result); + } + }, argv); +} +exports.applyMiddleware = applyMiddleware; diff --git a/node_modules/yargs/build/lib/obj-filter.d.ts b/node_modules/yargs/build/lib/obj-filter.d.ts new file mode 100644 index 0000000..031ae28 --- /dev/null +++ b/node_modules/yargs/build/lib/obj-filter.d.ts @@ -0,0 +1 @@ +export declare function objFilter(original?: T, filter?: (k: keyof T, v: T[keyof T]) => boolean): T; diff --git a/node_modules/yargs/build/lib/obj-filter.js b/node_modules/yargs/build/lib/obj-filter.js new file mode 100644 index 0000000..790f947 --- /dev/null +++ b/node_modules/yargs/build/lib/obj-filter.js @@ -0,0 +1,14 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.objFilter = void 0; +const common_types_1 = require("./common-types"); +function objFilter(original = {}, filter = () => true) { + const obj = {}; + common_types_1.objectKeys(original).forEach((key) => { + if (filter(key, original[key])) { + obj[key] = original[key]; + } + }); + return obj; +} +exports.objFilter = objFilter; diff --git a/node_modules/yargs/build/lib/parse-command.d.ts b/node_modules/yargs/build/lib/parse-command.d.ts new file mode 100644 index 0000000..fc57836 --- /dev/null +++ b/node_modules/yargs/build/lib/parse-command.d.ts @@ -0,0 +1,11 @@ +import { NotEmptyArray } from './common-types'; +export declare function parseCommand(cmd: string): ParsedCommand; +export interface ParsedCommand { + cmd: string; + demanded: Positional[]; + optional: Positional[]; +} +export interface Positional { + cmd: NotEmptyArray; + variadic: boolean; +} diff --git a/node_modules/yargs/build/lib/parse-command.js b/node_modules/yargs/build/lib/parse-command.js new file mode 100644 index 0000000..aaf2327 --- /dev/null +++ b/node_modules/yargs/build/lib/parse-command.js @@ -0,0 +1,36 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseCommand = void 0; +function parseCommand(cmd) { + const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); + const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); + const bregex = /\.*[\][<>]/g; + const firstCommand = splitCommand.shift(); + if (!firstCommand) + throw new Error(`No command found in: ${cmd}`); + const parsedCommand = { + cmd: firstCommand.replace(bregex, ''), + demanded: [], + optional: [] + }; + splitCommand.forEach((cmd, i) => { + let variadic = false; + cmd = cmd.replace(/\s/g, ''); + if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) + variadic = true; + if (/^\[/.test(cmd)) { + parsedCommand.optional.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic + }); + } + else { + parsedCommand.demanded.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic + }); + } + }); + return parsedCommand; +} +exports.parseCommand = parseCommand; diff --git a/node_modules/yargs/build/lib/process-argv.d.ts b/node_modules/yargs/build/lib/process-argv.d.ts new file mode 100644 index 0000000..18fd43b --- /dev/null +++ b/node_modules/yargs/build/lib/process-argv.d.ts @@ -0,0 +1,2 @@ +export declare function getProcessArgvWithoutBin(): string[]; +export declare function getProcessArgvBin(): string; diff --git a/node_modules/yargs/build/lib/process-argv.js b/node_modules/yargs/build/lib/process-argv.js new file mode 100644 index 0000000..a9201dd --- /dev/null +++ b/node_modules/yargs/build/lib/process-argv.js @@ -0,0 +1,31 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getProcessArgvBin = exports.getProcessArgvWithoutBin = void 0; +function getProcessArgvBinIndex() { + // The binary name is the first command line argument for: + // - bundled Electron apps: bin argv1 argv2 ... argvn + if (isBundledElectronApp()) + return 0; + // or the second one (default) for: + // - standard node apps: node bin.js argv1 argv2 ... argvn + // - unbundled Electron apps: electron bin.js argv1 arg2 ... argvn + return 1; +} +function isBundledElectronApp() { + // process.defaultApp is either set by electron in an electron unbundled app, or undefined + // see https://github.com/electron/electron/blob/master/docs/api/process.md#processdefaultapp-readonly + return isElectronApp() && !process.defaultApp; +} +function isElectronApp() { + // process.versions.electron is either set by electron, or undefined + // see https://github.com/electron/electron/blob/master/docs/api/process.md#processversionselectron-readonly + return !!process.versions.electron; +} +function getProcessArgvWithoutBin() { + return process.argv.slice(getProcessArgvBinIndex() + 1); +} +exports.getProcessArgvWithoutBin = getProcessArgvWithoutBin; +function getProcessArgvBin() { + return process.argv[getProcessArgvBinIndex()]; +} +exports.getProcessArgvBin = getProcessArgvBin; diff --git a/node_modules/yargs/build/lib/usage.d.ts b/node_modules/yargs/build/lib/usage.d.ts new file mode 100644 index 0000000..d9dd1fa --- /dev/null +++ b/node_modules/yargs/build/lib/usage.d.ts @@ -0,0 +1,49 @@ +import { Dictionary } from './common-types'; +import { YargsInstance } from './yargs'; +import { YError } from './yerror'; +import { Y18N } from 'y18n'; +export declare function usage(yargs: YargsInstance, y18n: Y18N): UsageInstance; +/** Instance of the usage module. */ +export interface UsageInstance { + cacheHelpMessage(): void; + clearCachedHelpMessage(): void; + command(cmd: string, description: string | undefined, isDefault: boolean, aliases: string[], deprecated?: boolean): void; + deferY18nLookup(str: string): string; + describe(keys: string | string[] | Dictionary, desc?: string): void; + epilog(msg: string): void; + example(cmd: string, description?: string): void; + fail(msg?: string | null, err?: YError | string): void; + failFn(f: FailureFunction): void; + freeze(): void; + functionDescription(fn: { + name?: string; + }): string; + getCommands(): [string, string, boolean, string[], boolean][]; + getDescriptions(): Dictionary; + getPositionalGroupName(): string; + getUsage(): [string, string][]; + getUsageDisabled(): boolean; + help(): string; + reset(localLookup: Dictionary): UsageInstance; + showHelp(level: 'error' | 'log' | ((message: string) => void)): void; + showHelpOnFail(enabled?: boolean | string, message?: string): UsageInstance; + showVersion(): void; + stringifiedValues(values?: any[], separator?: string): string; + unfreeze(): void; + usage(msg: string | null, description?: string | false): UsageInstance; + version(ver: any): void; + wrap(cols: number | null | undefined): void; +} +export interface FailureFunction { + (msg: string | undefined | null, err: YError | string | undefined, usage: UsageInstance): void; +} +export interface FrozenUsageInstance { + failMessage: string | undefined | null; + failureOutput: boolean; + usages: [string, string][]; + usageDisabled: boolean; + epilogs: string[]; + examples: [string, string][]; + commands: [string, string, boolean, string[], boolean][]; + descriptions: Dictionary; +} diff --git a/node_modules/yargs/build/lib/usage.js b/node_modules/yargs/build/lib/usage.js new file mode 100644 index 0000000..73f7b24 --- /dev/null +++ b/node_modules/yargs/build/lib/usage.js @@ -0,0 +1,540 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.usage = void 0; +// this file handles outputting usage instructions, +// failures, etc. keeps logging in one place. +const common_types_1 = require("./common-types"); +const obj_filter_1 = require("./obj-filter"); +const path = require("path"); +const yerror_1 = require("./yerror"); +const decamelize = require("decamelize"); +const setBlocking = require("set-blocking"); +const stringWidth = require("string-width"); +function usage(yargs, y18n) { + const __ = y18n.__; + const self = {}; + // methods for ouputting/building failure message. + const fails = []; + self.failFn = function failFn(f) { + fails.push(f); + }; + let failMessage = null; + let showHelpOnFail = true; + self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { + function parseFunctionArgs() { + return typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; + } + const [enabled, message] = parseFunctionArgs(); + failMessage = message; + showHelpOnFail = enabled; + return self; + }; + let failureOutput = false; + self.fail = function fail(msg, err) { + const logger = yargs._getLoggerInstance(); + if (fails.length) { + for (let i = fails.length - 1; i >= 0; --i) { + fails[i](msg, err, self); + } + } + else { + if (yargs.getExitProcess()) + setBlocking(true); + // don't output failure message more than once + if (!failureOutput) { + failureOutput = true; + if (showHelpOnFail) { + yargs.showHelp('error'); + logger.error(); + } + if (msg || err) + logger.error(msg || err); + if (failMessage) { + if (msg || err) + logger.error(''); + logger.error(failMessage); + } + } + err = err || new yerror_1.YError(msg); + if (yargs.getExitProcess()) { + return yargs.exit(1); + } + else if (yargs._hasParseCallback()) { + return yargs.exit(1, err); + } + else { + throw err; + } + } + }; + // methods for ouputting/building help (usage) message. + let usages = []; + let usageDisabled = false; + self.usage = (msg, description) => { + if (msg === null) { + usageDisabled = true; + usages = []; + return self; + } + usageDisabled = false; + usages.push([msg, description || '']); + return self; + }; + self.getUsage = () => { + return usages; + }; + self.getUsageDisabled = () => { + return usageDisabled; + }; + self.getPositionalGroupName = () => { + return __('Positionals:'); + }; + let examples = []; + self.example = (cmd, description) => { + examples.push([cmd, description || '']); + }; + let commands = []; + self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { + // the last default wins, so cancel out any previously set default + if (isDefault) { + commands = commands.map((cmdArray) => { + cmdArray[2] = false; + return cmdArray; + }); + } + commands.push([cmd, description || '', isDefault, aliases, deprecated]); + }; + self.getCommands = () => commands; + let descriptions = {}; + self.describe = function describe(keyOrKeys, desc) { + if (Array.isArray(keyOrKeys)) { + keyOrKeys.forEach((k) => { + self.describe(k, desc); + }); + } + else if (typeof keyOrKeys === 'object') { + Object.keys(keyOrKeys).forEach((k) => { + self.describe(k, keyOrKeys[k]); + }); + } + else { + descriptions[keyOrKeys] = desc; + } + }; + self.getDescriptions = () => descriptions; + let epilogs = []; + self.epilog = (msg) => { + epilogs.push(msg); + }; + let wrapSet = false; + let wrap; + self.wrap = (cols) => { + wrapSet = true; + wrap = cols; + }; + function getWrap() { + if (!wrapSet) { + wrap = windowWidth(); + wrapSet = true; + } + return wrap; + } + const deferY18nLookupPrefix = '__yargsString__:'; + self.deferY18nLookup = str => deferY18nLookupPrefix + str; + self.help = function help() { + if (cachedHelpMessage) + return cachedHelpMessage; + normalizeAliases(); + // handle old demanded API + const base$0 = yargs.customScriptName ? yargs.$0 : path.basename(yargs.$0); + const demandedOptions = yargs.getDemandedOptions(); + const demandedCommands = yargs.getDemandedCommands(); + const deprecatedOptions = yargs.getDeprecatedOptions(); + const groups = yargs.getGroups(); + const options = yargs.getOptions(); + let keys = []; + keys = keys.concat(Object.keys(descriptions)); + keys = keys.concat(Object.keys(demandedOptions)); + keys = keys.concat(Object.keys(demandedCommands)); + keys = keys.concat(Object.keys(options.default)); + keys = keys.filter(filterHiddenOptions); + keys = Object.keys(keys.reduce((acc, key) => { + if (key !== '_') + acc[key] = true; + return acc; + }, {})); + const theWrap = getWrap(); + const ui = require('cliui')({ + width: theWrap, + wrap: !!theWrap + }); + // the usage string. + if (!usageDisabled) { + if (usages.length) { + // user-defined usage. + usages.forEach((usage) => { + ui.div(`${usage[0].replace(/\$0/g, base$0)}`); + if (usage[1]) { + ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); + } + }); + ui.div(); + } + else if (commands.length) { + let u = null; + // demonstrate how commands are used. + if (demandedCommands._) { + u = `${base$0} <${__('command')}>\n`; + } + else { + u = `${base$0} [${__('command')}]\n`; + } + ui.div(`${u}`); + } + } + // your application's commands, i.e., non-option + // arguments populated in '_'. + if (commands.length) { + ui.div(__('Commands:')); + const context = yargs.getContext(); + const parentCommands = context.commands.length ? `${context.commands.join(' ')} ` : ''; + if (yargs.getParserConfiguration()['sort-commands'] === true) { + commands = commands.sort((a, b) => a[0].localeCompare(b[0])); + } + commands.forEach((command) => { + const commandString = `${base$0} ${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; // drop $0 from default commands. + ui.span({ + text: commandString, + padding: [0, 2, 0, 2], + width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4 + }, { text: command[1] }); + const hints = []; + if (command[2]) + hints.push(`[${__('default')}]`); + if (command[3] && command[3].length) { + hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); + } + if (command[4]) { + if (typeof command[4] === 'string') { + hints.push(`[${__('deprecated: %s', command[4])}]`); + } + else { + hints.push(`[${__('deprecated')}]`); + } + } + if (hints.length) { + ui.div({ text: hints.join(' '), padding: [0, 0, 0, 2], align: 'right' }); + } + else { + ui.div(); + } + }); + ui.div(); + } + // perform some cleanup on the keys array, making it + // only include top-level keys not their aliases. + const aliasKeys = (Object.keys(options.alias) || []) + .concat(Object.keys(yargs.parsed.newAliases) || []); + keys = keys.filter(key => !yargs.parsed.newAliases[key] && aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); + // populate 'Options:' group with any keys that have not + // explicitly had a group set. + const defaultGroup = __('Options:'); + if (!groups[defaultGroup]) + groups[defaultGroup] = []; + addUngroupedKeys(keys, options.alias, groups, defaultGroup); + // display 'Options:' table along with any custom tables: + Object.keys(groups).forEach((groupName) => { + if (!groups[groupName].length) + return; + // if we've grouped the key 'f', but 'f' aliases 'foobar', + // normalizedKeys should contain only 'foobar'. + const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => { + if (~aliasKeys.indexOf(key)) + return key; + for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { + if (~(options.alias[aliasKey] || []).indexOf(key)) + return aliasKey; + } + return key; + }); + if (normalizedKeys.length < 1) + return; + ui.div(groupName); + // actually generate the switches string --foo, -f, --bar. + const switches = normalizedKeys.reduce((acc, key) => { + acc[key] = [key].concat(options.alias[key] || []) + .map(sw => { + // for the special positional group don't + // add '--' or '-' prefix. + if (groupName === self.getPositionalGroupName()) + return sw; + else { + return ( + // matches yargs-parser logic in which single-digits + // aliases declared with a boolean type are now valid + /^[0-9]$/.test(sw) + ? ~options.boolean.indexOf(key) ? '-' : '--' + : sw.length > 1 ? '--' : '-') + sw; + } + }) + .join(', '); + return acc; + }, {}); + normalizedKeys.forEach((key) => { + const kswitch = switches[key]; + let desc = descriptions[key] || ''; + let type = null; + if (~desc.lastIndexOf(deferY18nLookupPrefix)) + desc = __(desc.substring(deferY18nLookupPrefix.length)); + if (~options.boolean.indexOf(key)) + type = `[${__('boolean')}]`; + if (~options.count.indexOf(key)) + type = `[${__('count')}]`; + if (~options.string.indexOf(key)) + type = `[${__('string')}]`; + if (~options.normalize.indexOf(key)) + type = `[${__('string')}]`; + if (~options.array.indexOf(key)) + type = `[${__('array')}]`; + if (~options.number.indexOf(key)) + type = `[${__('number')}]`; + const deprecatedExtra = (deprecated) => typeof deprecated === 'string' + ? `[${__('deprecated: %s', deprecated)}]` + : `[${__('deprecated')}]`; + const extra = [ + (key in deprecatedOptions) ? deprecatedExtra(deprecatedOptions[key]) : null, + type, + (key in demandedOptions) ? `[${__('required')}]` : null, + options.choices && options.choices[key] ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` : null, + defaultString(options.default[key], options.defaultDescription[key]) + ].filter(Boolean).join(' '); + ui.span({ text: kswitch, padding: [0, 2, 0, 2], width: maxWidth(switches, theWrap) + 4 }, desc); + if (extra) + ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); + else + ui.div(); + }); + ui.div(); + }); + // describe some common use-cases for your application. + if (examples.length) { + ui.div(__('Examples:')); + examples.forEach((example) => { + example[0] = example[0].replace(/\$0/g, base$0); + }); + examples.forEach((example) => { + if (example[1] === '') { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2] + }); + } + else { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + width: maxWidth(examples, theWrap) + 4 + }, { + text: example[1] + }); + } + }); + ui.div(); + } + // the usage string. + if (epilogs.length > 0) { + const e = epilogs.map(epilog => epilog.replace(/\$0/g, base$0)).join('\n'); + ui.div(`${e}\n`); + } + // Remove the trailing white spaces + return ui.toString().replace(/\s*$/, ''); + }; + // return the maximum width of a string + // in the left-hand column of a table. + function maxWidth(table, theWrap, modifier) { + let width = 0; + // table might be of the form [leftColumn], + // or {key: leftColumn} + if (!Array.isArray(table)) { + table = Object.values(table).map(v => [v]); + } + table.forEach((v) => { + width = Math.max(stringWidth(modifier ? `${modifier} ${v[0]}` : v[0]), width); + }); + // if we've enabled 'wrap' we should limit + // the max-width of the left-column. + if (theWrap) + width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); + return width; + } + // make sure any options set for aliases, + // are copied to the keys being aliased. + function normalizeAliases() { + // handle old demanded API + const demandedOptions = yargs.getDemandedOptions(); + const options = yargs.getOptions(); + (Object.keys(options.alias) || []).forEach((key) => { + options.alias[key].forEach((alias) => { + // copy descriptions. + if (descriptions[alias]) + self.describe(key, descriptions[alias]); + // copy demanded. + if (alias in demandedOptions) + yargs.demandOption(key, demandedOptions[alias]); + // type messages. + if (~options.boolean.indexOf(alias)) + yargs.boolean(key); + if (~options.count.indexOf(alias)) + yargs.count(key); + if (~options.string.indexOf(alias)) + yargs.string(key); + if (~options.normalize.indexOf(alias)) + yargs.normalize(key); + if (~options.array.indexOf(alias)) + yargs.array(key); + if (~options.number.indexOf(alias)) + yargs.number(key); + }); + }); + } + // if yargs is executing an async handler, we take a snapshot of the + // help message to display on failure: + let cachedHelpMessage; + self.cacheHelpMessage = function () { + cachedHelpMessage = this.help(); + }; + // however this snapshot must be cleared afterwards + // not to be be used by next calls to parse + self.clearCachedHelpMessage = function () { + cachedHelpMessage = undefined; + }; + // given a set of keys, place any keys that are + // ungrouped under the 'Options:' grouping. + function addUngroupedKeys(keys, aliases, groups, defaultGroup) { + let groupedKeys = []; + let toCheck = null; + Object.keys(groups).forEach((group) => { + groupedKeys = groupedKeys.concat(groups[group]); + }); + keys.forEach((key) => { + toCheck = [key].concat(aliases[key]); + if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { + groups[defaultGroup].push(key); + } + }); + return groupedKeys; + } + function filterHiddenOptions(key) { + return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt]; + } + self.showHelp = (level) => { + const logger = yargs._getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(self.help()); + }; + self.functionDescription = (fn) => { + const description = fn.name ? decamelize(fn.name, '-') : __('generated-value'); + return ['(', description, ')'].join(''); + }; + self.stringifiedValues = function stringifiedValues(values, separator) { + let string = ''; + const sep = separator || ', '; + const array = [].concat(values); + if (!values || !array.length) + return string; + array.forEach((value) => { + if (string.length) + string += sep; + string += JSON.stringify(value); + }); + return string; + }; + // format the default-value-string displayed in + // the right-hand column. + function defaultString(value, defaultDescription) { + let string = `[${__('default:')} `; + if (value === undefined && !defaultDescription) + return null; + if (defaultDescription) { + string += defaultDescription; + } + else { + switch (typeof value) { + case 'string': + string += `"${value}"`; + break; + case 'object': + string += JSON.stringify(value); + break; + default: + string += value; + } + } + return `${string}]`; + } + // guess the width of the console window, max-width 80. + function windowWidth() { + const maxWidth = 80; + // CI is not a TTY + /* c8 ignore next 2 */ + if (typeof process === 'object' && process.stdout && process.stdout.columns) { + return Math.min(maxWidth, process.stdout.columns); + } + else { + return maxWidth; + } + } + // logic for displaying application version. + let version = null; + self.version = (ver) => { + version = ver; + }; + self.showVersion = () => { + const logger = yargs._getLoggerInstance(); + logger.log(version); + }; + self.reset = function reset(localLookup) { + // do not reset wrap here + // do not reset fails here + failMessage = null; + failureOutput = false; + usages = []; + usageDisabled = false; + epilogs = []; + examples = []; + commands = []; + descriptions = obj_filter_1.objFilter(descriptions, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions + }); + }; + self.unfreeze = function unfreeze() { + const frozen = frozens.pop(); + common_types_1.assertNotStrictEqual(frozen, undefined); + ({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions + } = frozen); + }; + return self; +} +exports.usage = usage; diff --git a/node_modules/yargs/build/lib/validation.d.ts b/node_modules/yargs/build/lib/validation.d.ts new file mode 100644 index 0000000..e2d7854 --- /dev/null +++ b/node_modules/yargs/build/lib/validation.d.ts @@ -0,0 +1,34 @@ +import { Dictionary } from './common-types'; +import { UsageInstance } from './usage'; +import { YargsInstance, Arguments } from './yargs'; +import { DetailedArguments } from 'yargs-parser'; +import { Y18N } from 'y18n'; +export declare function validation(yargs: YargsInstance, usage: UsageInstance, y18n: Y18N): ValidationInstance; +/** Instance of the validation module. */ +export interface ValidationInstance { + check(f: CustomCheck['func'], global: boolean): void; + conflicting(argv: Arguments): void; + conflicts(key: string | Dictionary, value?: string | string[]): void; + customChecks(argv: Arguments, aliases: DetailedArguments['aliases']): void; + freeze(): void; + getConflicting(): Dictionary<(string | undefined)[]>; + getImplied(): Dictionary; + implications(argv: Arguments): void; + implies(key: string | Dictionary, value?: KeyOrPos | KeyOrPos[]): void; + isValidAndSomeAliasIsNotNew(key: string, aliases: DetailedArguments['aliases']): boolean; + limitedChoices(argv: Arguments): void; + nonOptionCount(argv: Arguments): void; + positionalCount(required: number, observed: number): void; + recommendCommands(cmd: string, potentialCommands: string[]): void; + requiredArguments(argv: Arguments): void; + reset(localLookup: Dictionary): ValidationInstance; + unfreeze(): void; + unknownArguments(argv: Arguments, aliases: DetailedArguments['aliases'], positionalMap: Dictionary, isDefaultCommand: boolean): void; + unknownCommands(argv: Arguments): boolean; +} +interface CustomCheck { + func: (argv: Arguments, aliases: DetailedArguments['aliases']) => any; + global: boolean; +} +export declare type KeyOrPos = string | number; +export {}; diff --git a/node_modules/yargs/build/lib/validation.js b/node_modules/yargs/build/lib/validation.js new file mode 100644 index 0000000..60c5e43 --- /dev/null +++ b/node_modules/yargs/build/lib/validation.js @@ -0,0 +1,330 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.validation = void 0; +const argsert_1 = require("./argsert"); +const common_types_1 = require("./common-types"); +const levenshtein_1 = require("./levenshtein"); +const obj_filter_1 = require("./obj-filter"); +const specialKeys = ['$0', '--', '_']; +// validation-type-stuff, missing params, +// bad implications, custom checks. +function validation(yargs, usage, y18n) { + const __ = y18n.__; + const __n = y18n.__n; + const self = {}; + // validate appropriate # of non-option + // arguments were provided, i.e., '_'. + self.nonOptionCount = function nonOptionCount(argv) { + const demandedCommands = yargs.getDemandedCommands(); + // don't count currently executing commands + const _s = argv._.length - yargs.getContext().commands.length; + if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) { + if (_s < demandedCommands._.min) { + if (demandedCommands._.minMsg !== undefined) { + usage.fail( + // replace $0 with observed, $1 with expected. + demandedCommands._.minMsg + ? demandedCommands._.minMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.min.toString()) + : null); + } + else { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s, demandedCommands._.min)); + } + } + else if (_s > demandedCommands._.max) { + if (demandedCommands._.maxMsg !== undefined) { + usage.fail( + // replace $0 with observed, $1 with expected. + demandedCommands._.maxMsg + ? demandedCommands._.maxMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.max.toString()) + : null); + } + else { + usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s, demandedCommands._.max)); + } + } + } + }; + // validate the appropriate # of + // positional arguments were provided: + self.positionalCount = function positionalCount(required, observed) { + if (observed < required) { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed, required)); + } + }; + // make sure all the required arguments are present. + self.requiredArguments = function requiredArguments(argv) { + const demandedOptions = yargs.getDemandedOptions(); + let missing = null; + for (const key of Object.keys(demandedOptions)) { + if (!Object.prototype.hasOwnProperty.call(argv, key) || typeof argv[key] === 'undefined') { + missing = missing || {}; + missing[key] = demandedOptions[key]; + } + } + if (missing) { + const customMsgs = []; + for (const key of Object.keys(missing)) { + const msg = missing[key]; + if (msg && customMsgs.indexOf(msg) < 0) { + customMsgs.push(msg); + } + } + const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; + usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); + } + }; + // check for unknown arguments (strict-mode). + self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand) { + const commandKeys = yargs.getCommandInstance().getCommands(); + const unknown = []; + const currentContext = yargs.getContext(); + Object.keys(argv).forEach((key) => { + if (specialKeys.indexOf(key) === -1 && + !Object.prototype.hasOwnProperty.call(positionalMap, key) && + !Object.prototype.hasOwnProperty.call(yargs._getParseContext(), key) && + !self.isValidAndSomeAliasIsNotNew(key, aliases)) { + unknown.push(key); + } + }); + if ((currentContext.commands.length > 0) || (commandKeys.length > 0) || isDefaultCommand) { + argv._.slice(currentContext.commands.length).forEach((key) => { + if (commandKeys.indexOf(key) === -1) { + unknown.push(key); + } + }); + } + if (unknown.length > 0) { + usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.join(', '))); + } + }; + self.unknownCommands = function unknownCommands(argv) { + const commandKeys = yargs.getCommandInstance().getCommands(); + const unknown = []; + const currentContext = yargs.getContext(); + if ((currentContext.commands.length > 0) || (commandKeys.length > 0)) { + argv._.slice(currentContext.commands.length).forEach((key) => { + if (commandKeys.indexOf(key) === -1) { + unknown.push(key); + } + }); + } + if (unknown.length > 0) { + usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); + return true; + } + else { + return false; + } + }; + // check for a key that is not an alias, or for which every alias is new, + // implying that it was invented by the parser, e.g., during camelization + self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { + if (!Object.prototype.hasOwnProperty.call(aliases, key)) { + return false; + } + const newAliases = yargs.parsed.newAliases; + for (const a of [key, ...aliases[key]]) { + if (!Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]) { + return true; + } + } + return false; + }; + // validate arguments limited to enumerated choices + self.limitedChoices = function limitedChoices(argv) { + const options = yargs.getOptions(); + const invalid = {}; + if (!Object.keys(options.choices).length) + return; + Object.keys(argv).forEach((key) => { + if (specialKeys.indexOf(key) === -1 && + Object.prototype.hasOwnProperty.call(options.choices, key)) { + [].concat(argv[key]).forEach((value) => { + // TODO case-insensitive configurability + if (options.choices[key].indexOf(value) === -1 && + value !== undefined) { + invalid[key] = (invalid[key] || []).concat(value); + } + }); + } + }); + const invalidKeys = Object.keys(invalid); + if (!invalidKeys.length) + return; + let msg = __('Invalid values:'); + invalidKeys.forEach((key) => { + msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; + }); + usage.fail(msg); + }; + // custom checks, added using the `check` option on yargs. + let checks = []; + self.check = function check(f, global) { + checks.push({ + func: f, + global + }); + }; + self.customChecks = function customChecks(argv, aliases) { + for (let i = 0, f; (f = checks[i]) !== undefined; i++) { + const func = f.func; + let result = null; + try { + result = func(argv, aliases); + } + catch (err) { + usage.fail(err.message ? err.message : err, err); + continue; + } + if (!result) { + usage.fail(__('Argument check failed: %s', func.toString())); + } + else if (typeof result === 'string' || result instanceof Error) { + usage.fail(result.toString(), result); + } + } + }; + // check implications, argument foo implies => argument bar. + let implied = {}; + self.implies = function implies(key, value) { + argsert_1.argsert(' [array|number|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach((k) => { + self.implies(k, key[k]); + }); + } + else { + yargs.global(key); + if (!implied[key]) { + implied[key] = []; + } + if (Array.isArray(value)) { + value.forEach((i) => self.implies(key, i)); + } + else { + common_types_1.assertNotStrictEqual(value, undefined); + implied[key].push(value); + } + } + }; + self.getImplied = function getImplied() { + return implied; + }; + function keyExists(argv, val) { + // convert string '1' to number 1 + const num = Number(val); + val = isNaN(num) ? val : num; + if (typeof val === 'number') { + // check length of argv._ + val = argv._.length >= val; + } + else if (val.match(/^--no-.+/)) { + // check if key/value doesn't exist + val = val.match(/^--no-(.+)/)[1]; + val = !argv[val]; + } + else { + // check if key/value exists + val = argv[val]; + } + return val; + } + self.implications = function implications(argv) { + const implyFail = []; + Object.keys(implied).forEach((key) => { + const origKey = key; + (implied[key] || []).forEach((value) => { + let key = origKey; + const origValue = value; + key = keyExists(argv, key); + value = keyExists(argv, value); + if (key && !value) { + implyFail.push(` ${origKey} -> ${origValue}`); + } + }); + }); + if (implyFail.length) { + let msg = `${__('Implications failed:')}\n`; + implyFail.forEach((value) => { + msg += (value); + }); + usage.fail(msg); + } + }; + let conflicting = {}; + self.conflicts = function conflicts(key, value) { + argsert_1.argsert(' [array|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach((k) => { + self.conflicts(k, key[k]); + }); + } + else { + yargs.global(key); + if (!conflicting[key]) { + conflicting[key] = []; + } + if (Array.isArray(value)) { + value.forEach((i) => self.conflicts(key, i)); + } + else { + conflicting[key].push(value); + } + } + }; + self.getConflicting = () => conflicting; + self.conflicting = function conflictingFn(argv) { + Object.keys(argv).forEach((key) => { + if (conflicting[key]) { + conflicting[key].forEach((value) => { + // we default keys to 'undefined' that have been configured, we should not + // apply conflicting check unless they are a value other than 'undefined'. + if (value && argv[key] !== undefined && argv[value] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + } + }); + }; + self.recommendCommands = function recommendCommands(cmd, potentialCommands) { + const threshold = 3; // if it takes more than three edits, let's move on. + potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); + let recommended = null; + let bestDistance = Infinity; + for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { + const d = levenshtein_1.levenshtein(cmd, candidate); + if (d <= threshold && d < bestDistance) { + bestDistance = d; + recommended = candidate; + } + } + if (recommended) + usage.fail(__('Did you mean %s?', recommended)); + }; + self.reset = function reset(localLookup) { + implied = obj_filter_1.objFilter(implied, k => !localLookup[k]); + conflicting = obj_filter_1.objFilter(conflicting, k => !localLookup[k]); + checks = checks.filter(c => c.global); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + implied, + checks, + conflicting + }); + }; + self.unfreeze = function unfreeze() { + const frozen = frozens.pop(); + common_types_1.assertNotStrictEqual(frozen, undefined); + ({ + implied, + checks, + conflicting + } = frozen); + }; + return self; +} +exports.validation = validation; diff --git a/node_modules/yargs/build/lib/yargs.d.ts b/node_modules/yargs/build/lib/yargs.d.ts new file mode 100644 index 0000000..8e6e27c --- /dev/null +++ b/node_modules/yargs/build/lib/yargs.d.ts @@ -0,0 +1,274 @@ +/// +import { CommandInstance, CommandHandler, CommandBuilderDefinition, CommandBuilder, CommandHandlerCallback, FinishCommandHandler } from './command'; +import { Dictionary } from './common-types'; +import { Arguments as ParserArguments, DetailedArguments as ParserDetailedArguments, Configuration as ParserConfiguration, Options as ParserOptions, ConfigCallback, CoerceCallback } from 'yargs-parser'; +import { YError } from './yerror'; +import { UsageInstance, FailureFunction } from './usage'; +import { CompletionFunction } from './completion'; +import { ValidationInstance, KeyOrPos } from './validation'; +import { Y18N } from 'y18n'; +import { MiddlewareCallback, Middleware } from './middleware'; +import { RequireDirectoryOptions } from 'require-directory'; +export declare function Yargs(processArgs?: string | string[], cwd?: string, parentRequire?: NodeRequire): YargsInstance; +export declare function rebase(base: string, dir: string): string; +/** Instance of the yargs module. */ +export interface YargsInstance { + $0: string; + argv: Arguments; + customScriptName: boolean; + parsed: DetailedArguments | false; + _copyDoubleDash>(argv: T): T; + _getLoggerInstance(): LoggerInstance; + _getParseContext(): Object; + _hasOutput(): boolean; + _hasParseCallback(): boolean; + _parseArgs: { + (args: null, shortCircuit: null, _calledFromCommand: boolean, commandIndex?: number): Arguments | Promise; + (args: string | string[], shortCircuit?: boolean): Arguments | Promise; + }; + _runValidation(argv: Arguments, aliases: Dictionary, positionalMap: Dictionary, parseErrors: Error | null, isDefaultCommand?: boolean): void; + _setHasOutput(): void; + addHelpOpt: { + (opt?: string | false): YargsInstance; + (opt?: string, msg?: string): YargsInstance; + }; + addShowHiddenOpt: { + (opt?: string | false): YargsInstance; + (opt?: string, msg?: string): YargsInstance; + }; + alias: { + (keys: string | string[], aliases: string | string[]): YargsInstance; + (keyAliases: Dictionary): YargsInstance; + }; + array(keys: string | string[]): YargsInstance; + boolean(keys: string | string[]): YargsInstance; + check(f: (argv: Arguments, aliases: Dictionary) => any, _global?: boolean): YargsInstance; + choices: { + (keys: string | string[], choices: string | string[]): YargsInstance; + (keyChoices: Dictionary): YargsInstance; + }; + coerce: { + (keys: string | string[], coerceCallback: CoerceCallback): YargsInstance; + (keyCoerceCallbacks: Dictionary): YargsInstance; + }; + command(cmd: string | string[], description: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback, commandMiddleware?: Middleware[], deprecated?: boolean): YargsInstance; + commandDir(dir: string, opts?: RequireDirectoryOptions): YargsInstance; + completion: { + (cmd?: string, fn?: CompletionFunction): YargsInstance; + (cmd?: string, desc?: string | false, fn?: CompletionFunction): YargsInstance; + }; + config: { + (config: Dictionary): YargsInstance; + (keys?: string | string[], configCallback?: ConfigCallback): YargsInstance; + (keys?: string | string[], msg?: string, configCallback?: ConfigCallback): YargsInstance; + }; + conflicts: { + (key: string, conflictsWith: string | string[]): YargsInstance; + (keyConflicts: Dictionary): YargsInstance; + }; + count(keys: string | string[]): YargsInstance; + default: { + (key: string, value: any, defaultDescription?: string): YargsInstance; + (keys: string[], value: Exclude): YargsInstance; + (keys: Dictionary): YargsInstance; + }; + defaults: YargsInstance['default']; + demand: { + (min: number, max?: number | string, msg?: string): YargsInstance; + (keys: string | string[], msg?: string | true): YargsInstance; + (keys: string | string[], max: string[], msg?: string | true): YargsInstance; + (keyMsgs: Dictionary): YargsInstance; + (keyMsgs: Dictionary, max: string[], msg?: string): YargsInstance; + }; + demandCommand(): YargsInstance; + demandCommand(min: number, minMsg?: string): YargsInstance; + demandCommand(min: number, max: number, minMsg?: string | null, maxMsg?: string | null): YargsInstance; + demandOption: { + (keys: string | string[], msg?: string): YargsInstance; + (keyMsgs: Dictionary): YargsInstance; + }; + deprecateOption(option: string, message?: string | boolean): YargsInstance; + describe: { + (keys: string | string[], description?: string): YargsInstance; + (keyDescriptions: Dictionary): YargsInstance; + }; + detectLocale(detect: boolean): YargsInstance; + env(prefix?: string | false): YargsInstance; + epilog: YargsInstance['epilogue']; + epilogue(msg: string): YargsInstance; + example(cmd: string | [string, string?][], description?: string): YargsInstance; + exit(code: number, err?: YError | string): void; + exitProcess(enabled: boolean): YargsInstance; + fail(f: FailureFunction): YargsInstance; + getCommandInstance(): CommandInstance; + getCompletion(args: string[], done: (completions: string[]) => any): void; + getContext(): Context; + getDemandedCommands(): Options['demandedCommands']; + getDemandedOptions(): Options['demandedOptions']; + getDeprecatedOptions(): Options['deprecatedOptions']; + getDetectLocale(): boolean; + getExitProcess(): boolean; + getGroups(): Dictionary; + getHandlerFinishCommand(): FinishCommandHandler | null; + getOptions(): Options; + getParserConfiguration(): Configuration; + getStrict(): boolean; + getStrictCommands(): boolean; + getUsageInstance(): UsageInstance; + getValidationInstance(): ValidationInstance; + global(keys: string | string[], global?: boolean): YargsInstance; + group(keys: string | string[], groupName: string): YargsInstance; + help: YargsInstance['addHelpOpt']; + hide(key: string): YargsInstance; + implies: { + (key: string, implication: KeyOrPos | KeyOrPos[]): YargsInstance; + (keyImplications: Dictionary): YargsInstance; + }; + locale: { + (): string; + (locale: string): YargsInstance; + }; + middleware(callback: MiddlewareCallback | MiddlewareCallback[], applyBeforeValidation?: boolean): YargsInstance; + nargs: { + (keys: string | string[], nargs: number): YargsInstance; + (keyNargs: Dictionary): YargsInstance; + }; + normalize(keys: string | string[]): YargsInstance; + number(keys: string | string[]): YargsInstance; + onFinishCommand(f: FinishCommandHandler): YargsInstance; + option: { + (key: string, optionDefinition: OptionDefinition): YargsInstance; + (keyOptionDefinitions: Dictionary): YargsInstance; + }; + options: YargsInstance['option']; + parse: { + (): Arguments | Promise; + (args: string | string[], context: object, parseCallback?: ParseCallback): Arguments | Promise; + (args: string | string[], parseCallback: ParseCallback): Arguments | Promise; + (args: string | string[], shortCircuit: boolean): Arguments | Promise; + }; + parserConfiguration(config: Configuration): YargsInstance; + pkgConf(key: string, rootPath?: string): YargsInstance; + positional(key: string, positionalDefinition: PositionalDefinition): YargsInstance; + recommendCommands(recommend: boolean): YargsInstance; + require: YargsInstance['demand']; + required: YargsInstance['demand']; + requiresArg(keys: string | string[] | Dictionary): YargsInstance; + reset(aliases?: DetailedArguments['aliases']): YargsInstance; + resetOptions(aliases?: DetailedArguments['aliases']): YargsInstance; + scriptName(scriptName: string): YargsInstance; + showCompletionScript($0?: string, cmd?: string): YargsInstance; + showHelp(level: 'error' | 'log' | ((message: string) => void)): YargsInstance; + showHelpOnFail: { + (message?: string): YargsInstance; + (enabled: boolean, message: string): YargsInstance; + }; + showHidden: YargsInstance['addShowHiddenOpt']; + skipValidation(keys: string | string[]): YargsInstance; + strict(enable?: boolean): YargsInstance; + strictCommands(enable?: boolean): YargsInstance; + string(key: string | string[]): YargsInstance; + terminalWidth(): number | null; + updateStrings(obj: Dictionary): YargsInstance; + updateLocale: YargsInstance['updateStrings']; + usage: { + (msg: string | null): YargsInstance; + (msg: string, description: CommandHandler['description'], builder?: CommandBuilderDefinition | CommandBuilder, handler?: CommandHandlerCallback): YargsInstance; + }; + version: { + (ver?: string | false): YargsInstance; + (key?: string, ver?: string): YargsInstance; + (key?: string, msg?: string, ver?: string): YargsInstance; + }; + wrap(cols: number | null | undefined): YargsInstance; +} +export declare function isYargsInstance(y: YargsInstance | void): y is YargsInstance; +/** Yargs' context. */ +export interface Context { + commands: string[]; + files: string[]; + fullCommands: string[]; +} +declare type LoggerInstance = Pick; +export interface Options extends ParserOptions { + __: Y18N['__']; + alias: Dictionary; + array: string[]; + boolean: string[]; + choices: Dictionary; + config: Dictionary; + configObjects: Dictionary[]; + configuration: Configuration; + count: string[]; + defaultDescription: Dictionary; + demandedCommands: Dictionary<{ + min: number; + max: number; + minMsg?: string | null; + maxMsg?: string | null; + }>; + demandedOptions: Dictionary; + deprecatedOptions: Dictionary; + hiddenOptions: string[]; + /** Manually set keys */ + key: Dictionary; + local: string[]; + normalize: string[]; + number: string[]; + showHiddenOpt: string; + skipValidation: string[]; + string: string[]; +} +export interface Configuration extends Partial { + /** Should a config object be deep-merged with the object config it extends? */ + 'deep-merge-config'?: boolean; + /** Should commands be sorted in help? */ + 'sort-commands'?: boolean; +} +export interface OptionDefinition { + alias?: string | string[]; + array?: boolean; + boolean?: boolean; + choices?: string | string[]; + coerce?: CoerceCallback; + config?: boolean; + configParser?: ConfigCallback; + conflicts?: string | string[]; + count?: boolean; + default?: any; + defaultDescription?: string; + deprecate?: string | boolean; + deprecated?: OptionDefinition['deprecate']; + desc?: string; + describe?: OptionDefinition['desc']; + description?: OptionDefinition['desc']; + demand?: string | true; + demandOption?: OptionDefinition['demand']; + global?: boolean; + group?: string; + hidden?: boolean; + implies?: string | number | KeyOrPos[]; + nargs?: number; + normalize?: boolean; + number?: boolean; + require?: OptionDefinition['demand']; + required?: OptionDefinition['demand']; + requiresArg?: boolean; + skipValidation?: boolean; + string?: boolean; + type?: 'array' | 'boolean' | 'count' | 'number' | 'string'; +} +interface PositionalDefinition extends Pick { + type?: 'boolean' | 'number' | 'string'; +} +interface ParseCallback { + (err: YError | string | undefined | null, argv: Arguments | Promise, output: string): void; +} +export interface Arguments extends ParserArguments { + /** The script name or node command */ + $0: string; +} +export interface DetailedArguments extends ParserDetailedArguments { + argv: Arguments; +} +export {}; diff --git a/node_modules/yargs/build/lib/yargs.js b/node_modules/yargs/build/lib/yargs.js new file mode 100644 index 0000000..316f3d6 --- /dev/null +++ b/node_modules/yargs/build/lib/yargs.js @@ -0,0 +1,1190 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isYargsInstance = exports.rebase = exports.Yargs = void 0; +const command_1 = require("./command"); +const common_types_1 = require("./common-types"); +const yerror_1 = require("./yerror"); +const usage_1 = require("./usage"); +const argsert_1 = require("./argsert"); +const fs = require("fs"); +const completion_1 = require("./completion"); +const path = require("path"); +const validation_1 = require("./validation"); +const obj_filter_1 = require("./obj-filter"); +const apply_extends_1 = require("./apply-extends"); +const middleware_1 = require("./middleware"); +const processArgv = require("./process-argv"); +const is_promise_1 = require("./is-promise"); +const Parser = require("yargs-parser"); +const y18nFactory = require("y18n"); +const setBlocking = require("set-blocking"); +const findUp = require("find-up"); +const requireMainFilename = require("require-main-filename"); +function Yargs(processArgs = [], cwd = process.cwd(), parentRequire = require) { + const self = {}; + let command; + let completion = null; + let groups = {}; + const globalMiddleware = []; + let output = ''; + const preservedGroups = {}; + let usage; + let validation; + let handlerFinishCommand = null; + const y18n = y18nFactory({ + directory: path.resolve(__dirname, '../../locales'), + updateFiles: false + }); + self.middleware = middleware_1.globalMiddlewareFactory(globalMiddleware, self); + self.scriptName = function (scriptName) { + self.customScriptName = true; + self.$0 = scriptName; + return self; + }; + // ignore the node bin, specify this in your + // bin file with #!/usr/bin/env node + let default$0; + if (/\b(node|iojs|electron)(\.exe)?$/.test(process.argv[0])) { + default$0 = process.argv.slice(1, 2); + } + else { + default$0 = process.argv.slice(0, 1); + } + self.$0 = default$0 + .map(x => { + const b = rebase(cwd, x); + return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; + }) + .join(' ').trim(); + if (process.env._ !== undefined && processArgv.getProcessArgvBin() === process.env._) { + self.$0 = process.env._.replace(`${path.dirname(process.execPath)}/`, ''); + } + // use context object to keep track of resets, subcommand execution, etc + // submodules should modify and check the state of context as necessary + const context = { resets: -1, commands: [], fullCommands: [], files: [] }; + self.getContext = () => context; + // puts yargs back into an initial state. any keys + // that have been set to "global" will not be reset + // by this action. + let options; + self.resetOptions = self.reset = function resetOptions(aliases = {}) { + context.resets++; + options = options || {}; + // put yargs back into an initial state, this + // logic is used to build a nested command + // hierarchy. + const tmpOptions = {}; + tmpOptions.local = options.local ? options.local : []; + tmpOptions.configObjects = options.configObjects ? options.configObjects : []; + // if a key has been explicitly set as local, + // we should reset it before passing options to command. + const localLookup = {}; + tmpOptions.local.forEach((l) => { + localLookup[l] = true; + (aliases[l] || []).forEach((a) => { + localLookup[a] = true; + }); + }); + // add all groups not set to local to preserved groups + Object.assign(preservedGroups, Object.keys(groups).reduce((acc, groupName) => { + const keys = groups[groupName].filter(key => !(key in localLookup)); + if (keys.length > 0) { + acc[groupName] = keys; + } + return acc; + }, {})); + // groups can now be reset + groups = {}; + const arrayOptions = [ + 'array', 'boolean', 'string', 'skipValidation', + 'count', 'normalize', 'number', + 'hiddenOptions' + ]; + const objectOptions = [ + 'narg', 'key', 'alias', 'default', 'defaultDescription', + 'config', 'choices', 'demandedOptions', 'demandedCommands', 'coerce', + 'deprecatedOptions' + ]; + arrayOptions.forEach(k => { + tmpOptions[k] = (options[k] || []).filter(k => !localLookup[k]); + }); + objectOptions.forEach((k) => { + tmpOptions[k] = obj_filter_1.objFilter(options[k], k => !localLookup[k]); + }); + tmpOptions.envPrefix = options.envPrefix; + options = tmpOptions; + // if this is the first time being executed, create + // instances of all our helpers -- otherwise just reset. + usage = usage ? usage.reset(localLookup) : usage_1.usage(self, y18n); + validation = validation ? validation.reset(localLookup) : validation_1.validation(self, usage, y18n); + command = command ? command.reset() : command_1.command(self, usage, validation, globalMiddleware); + if (!completion) + completion = completion_1.completion(self, usage, command); + completionCommand = null; + output = ''; + exitError = null; + hasOutput = false; + self.parsed = false; + return self; + }; + self.resetOptions(); + // temporary hack: allow "freezing" of reset-able state for parse(msg, cb) + const frozens = []; + function freeze() { + frozens.push({ + options, + configObjects: options.configObjects.slice(0), + exitProcess, + groups, + strict, + strictCommands, + completionCommand, + output, + exitError, + hasOutput, + parsed: self.parsed, + parseFn, + parseContext, + handlerFinishCommand + }); + usage.freeze(); + validation.freeze(); + command.freeze(); + } + function unfreeze() { + const frozen = frozens.pop(); + common_types_1.assertNotStrictEqual(frozen, undefined); + let configObjects; + ({ + options, + configObjects, + exitProcess, + groups, + output, + exitError, + hasOutput, + parsed: self.parsed, + strict, + strictCommands, + completionCommand, + parseFn, + parseContext, + handlerFinishCommand + } = frozen); + options.configObjects = configObjects; + usage.unfreeze(); + validation.unfreeze(); + command.unfreeze(); + } + self.boolean = function (keys) { + argsert_1.argsert('', [keys], arguments.length); + populateParserHintArray('boolean', keys); + return self; + }; + self.array = function (keys) { + argsert_1.argsert('', [keys], arguments.length); + populateParserHintArray('array', keys); + return self; + }; + self.number = function (keys) { + argsert_1.argsert('', [keys], arguments.length); + populateParserHintArray('number', keys); + return self; + }; + self.normalize = function (keys) { + argsert_1.argsert('', [keys], arguments.length); + populateParserHintArray('normalize', keys); + return self; + }; + self.count = function (keys) { + argsert_1.argsert('', [keys], arguments.length); + populateParserHintArray('count', keys); + return self; + }; + self.string = function (keys) { + argsert_1.argsert('', [keys], arguments.length); + populateParserHintArray('string', keys); + return self; + }; + self.requiresArg = function (keys) { + // the 2nd paramter [number] in the argsert the assertion is mandatory + // as populateParserHintSingleValueDictionary recursively calls requiresArg + // with Nan as a 2nd parameter, although we ignore it + argsert_1.argsert(' [number]', [keys], arguments.length); + // If someone configures nargs at the same time as requiresArg, + // nargs should take precedent, + // see: https://github.com/yargs/yargs/pull/1572 + // TODO: make this work with aliases, using a check similar to + // checkAllAliases() in yargs-parser. + if (typeof keys === 'string' && options.narg[keys]) { + return self; + } + else { + populateParserHintSingleValueDictionary(self.requiresArg, 'narg', keys, NaN); + } + return self; + }; + self.skipValidation = function (keys) { + argsert_1.argsert('', [keys], arguments.length); + populateParserHintArray('skipValidation', keys); + return self; + }; + function populateParserHintArray(type, keys) { + keys = [].concat(keys); + keys.forEach((key) => { + key = sanitizeKey(key); + options[type].push(key); + }); + } + self.nargs = function (key, value) { + argsert_1.argsert(' [number]', [key, value], arguments.length); + populateParserHintSingleValueDictionary(self.nargs, 'narg', key, value); + return self; + }; + self.choices = function (key, value) { + argsert_1.argsert(' [string|array]', [key, value], arguments.length); + populateParserHintArrayDictionary(self.choices, 'choices', key, value); + return self; + }; + self.alias = function (key, value) { + argsert_1.argsert(' [string|array]', [key, value], arguments.length); + populateParserHintArrayDictionary(self.alias, 'alias', key, value); + return self; + }; + // TODO: actually deprecate self.defaults. + self.default = self.defaults = function (key, value, defaultDescription) { + argsert_1.argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); + if (defaultDescription) { + common_types_1.assertSingleKey(key); + options.defaultDescription[key] = defaultDescription; + } + if (typeof value === 'function') { + common_types_1.assertSingleKey(key); + if (!options.defaultDescription[key]) + options.defaultDescription[key] = usage.functionDescription(value); + value = value.call(); + } + populateParserHintSingleValueDictionary(self.default, 'default', key, value); + return self; + }; + self.describe = function (key, desc) { + argsert_1.argsert(' [string]', [key, desc], arguments.length); + setKey(key, true); + usage.describe(key, desc); + return self; + }; + function setKey(key, set) { + populateParserHintSingleValueDictionary(setKey, 'key', key, set); + return self; + } + function demandOption(keys, msg) { + argsert_1.argsert(' [string]', [keys, msg], arguments.length); + populateParserHintSingleValueDictionary(self.demandOption, 'demandedOptions', keys, msg); + return self; + } + self.demandOption = demandOption; + self.coerce = function (keys, value) { + argsert_1.argsert(' [function]', [keys, value], arguments.length); + populateParserHintSingleValueDictionary(self.coerce, 'coerce', keys, value); + return self; + }; + function populateParserHintSingleValueDictionary(builder, type, key, value) { + populateParserHintDictionary(builder, type, key, value, (type, key, value) => { + options[type][key] = value; + }); + } + function populateParserHintArrayDictionary(builder, type, key, value) { + populateParserHintDictionary(builder, type, key, value, (type, key, value) => { + options[type][key] = (options[type][key] || []).concat(value); + }); + } + function populateParserHintDictionary(builder, type, key, value, singleKeyHandler) { + if (Array.isArray(key)) { + // an array of keys with one value ['x', 'y', 'z'], function parse () {} + key.forEach((k) => { + builder(k, value); + }); + } + else if (((key) => typeof key === 'object')(key)) { + // an object of key value pairs: {'x': parse () {}, 'y': parse() {}} + for (const k of common_types_1.objectKeys(key)) { + builder(k, key[k]); + } + } + else { + singleKeyHandler(type, sanitizeKey(key), value); + } + } + function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; + } + function deleteFromParserHintObject(optionKey) { + // delete from all parsing hints: + // boolean, array, key, alias, etc. + common_types_1.objectKeys(options).forEach((hintKey) => { + // configObjects is not a parsing hint array + if (((key) => key === 'configObjects')(hintKey)) + return; + const hint = options[hintKey]; + if (Array.isArray(hint)) { + if (~hint.indexOf(optionKey)) + hint.splice(hint.indexOf(optionKey), 1); + } + else if (typeof hint === 'object') { + delete hint[optionKey]; + } + }); + // now delete the description from usage.js. + delete usage.getDescriptions()[optionKey]; + } + self.config = function config(key = 'config', msg, parseFn) { + argsert_1.argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); + // allow a config object to be provided directly. + if ((typeof key === 'object') && !Array.isArray(key)) { + key = apply_extends_1.applyExtends(key, cwd, self.getParserConfiguration()['deep-merge-config']); + options.configObjects = (options.configObjects || []).concat(key); + return self; + } + // allow for a custom parsing function. + if (typeof msg === 'function') { + parseFn = msg; + msg = undefined; + } + self.describe(key, msg || usage.deferY18nLookup('Path to JSON config file')); + (Array.isArray(key) ? key : [key]).forEach((k) => { + options.config[k] = parseFn || true; + }); + return self; + }; + self.example = function (cmd, description) { + argsert_1.argsert(' [string]', [cmd, description], arguments.length); + if (Array.isArray(cmd)) { + cmd.forEach((exampleParams) => self.example(...exampleParams)); + } + else { + usage.example(cmd, description); + } + return self; + }; + self.command = function (cmd, description, builder, handler, middlewares, deprecated) { + argsert_1.argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); + command.addHandler(cmd, description, builder, handler, middlewares, deprecated); + return self; + }; + self.commandDir = function (dir, opts) { + argsert_1.argsert(' [object]', [dir, opts], arguments.length); + const req = parentRequire || require; + command.addDirectory(dir, self.getContext(), req, require('get-caller-file')(), opts); + return self; + }; + // TODO: deprecate self.demand in favor of + // .demandCommand() .demandOption(). + self.demand = self.required = self.require = function demand(keys, max, msg) { + // you can optionally provide a 'max' key, + // which will raise an exception if too many '_' + // options are provided. + if (Array.isArray(max)) { + max.forEach((key) => { + common_types_1.assertNotStrictEqual(msg, true); + demandOption(key, msg); + }); + max = Infinity; + } + else if (typeof max !== 'number') { + msg = max; + max = Infinity; + } + if (typeof keys === 'number') { + common_types_1.assertNotStrictEqual(msg, true); + self.demandCommand(keys, max, msg, msg); + } + else if (Array.isArray(keys)) { + keys.forEach((key) => { + common_types_1.assertNotStrictEqual(msg, true); + demandOption(key, msg); + }); + } + else { + if (typeof msg === 'string') { + demandOption(keys, msg); + } + else if (msg === true || typeof msg === 'undefined') { + demandOption(keys); + } + } + return self; + }; + self.demandCommand = function demandCommand(min = 1, max, minMsg, maxMsg) { + argsert_1.argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); + if (typeof max !== 'number') { + minMsg = max; + max = Infinity; + } + self.global('_', false); + options.demandedCommands._ = { + min, + max, + minMsg, + maxMsg + }; + return self; + }; + self.getDemandedOptions = () => { + argsert_1.argsert([], 0); + return options.demandedOptions; + }; + self.getDemandedCommands = () => { + argsert_1.argsert([], 0); + return options.demandedCommands; + }; + self.deprecateOption = function deprecateOption(option, message) { + argsert_1.argsert(' [string|boolean]', [option, message], arguments.length); + options.deprecatedOptions[option] = message; + return self; + }; + self.getDeprecatedOptions = () => { + argsert_1.argsert([], 0); + return options.deprecatedOptions; + }; + self.implies = function (key, value) { + argsert_1.argsert(' [number|string|array]', [key, value], arguments.length); + validation.implies(key, value); + return self; + }; + self.conflicts = function (key1, key2) { + argsert_1.argsert(' [string|array]', [key1, key2], arguments.length); + validation.conflicts(key1, key2); + return self; + }; + self.usage = function (msg, description, builder, handler) { + argsert_1.argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); + if (description !== undefined) { + common_types_1.assertNotStrictEqual(msg, null); + // .usage() can be used as an alias for defining + // a default command. + if ((msg || '').match(/^\$0( |$)/)) { + return self.command(msg, description, builder, handler); + } + else { + throw new yerror_1.YError('.usage() description must start with $0 if being used as alias for .command()'); + } + } + else { + usage.usage(msg); + return self; + } + }; + self.epilogue = self.epilog = function (msg) { + argsert_1.argsert('', [msg], arguments.length); + usage.epilog(msg); + return self; + }; + self.fail = function (f) { + argsert_1.argsert('', [f], arguments.length); + usage.failFn(f); + return self; + }; + self.onFinishCommand = function (f) { + argsert_1.argsert('', [f], arguments.length); + handlerFinishCommand = f; + return self; + }; + self.getHandlerFinishCommand = () => handlerFinishCommand; + self.check = function (f, _global) { + argsert_1.argsert(' [boolean]', [f, _global], arguments.length); + validation.check(f, _global !== false); + return self; + }; + self.global = function global(globals, global) { + argsert_1.argsert(' [boolean]', [globals, global], arguments.length); + globals = [].concat(globals); + if (global !== false) { + options.local = options.local.filter(l => globals.indexOf(l) === -1); + } + else { + globals.forEach((g) => { + if (options.local.indexOf(g) === -1) + options.local.push(g); + }); + } + return self; + }; + self.pkgConf = function pkgConf(key, rootPath) { + argsert_1.argsert(' [string]', [key, rootPath], arguments.length); + let conf = null; + // prefer cwd to require-main-filename in this method + // since we're looking for e.g. "nyc" config in nyc consumer + // rather than "yargs" config in nyc (where nyc is the main filename) + const obj = pkgUp(rootPath || cwd); + // If an object exists in the key, add it to options.configObjects + if (obj[key] && typeof obj[key] === 'object') { + conf = apply_extends_1.applyExtends(obj[key], rootPath || cwd, self.getParserConfiguration()['deep-merge-config']); + options.configObjects = (options.configObjects || []).concat(conf); + } + return self; + }; + const pkgs = {}; + function pkgUp(rootPath) { + const npath = rootPath || '*'; + if (pkgs[npath]) + return pkgs[npath]; + let obj = {}; + try { + let startDir = rootPath || requireMainFilename(parentRequire); + // When called in an environment that lacks require.main.filename, such as a jest test runner, + // startDir is already process.cwd(), and should not be shortened. + // Whether or not it is _actually_ a directory (e.g., extensionless bin) is irrelevant, find-up handles it. + if (!rootPath && path.extname(startDir)) { + startDir = path.dirname(startDir); + } + const pkgJsonPath = findUp.sync('package.json', { + cwd: startDir + }); + common_types_1.assertNotStrictEqual(pkgJsonPath, undefined); + obj = JSON.parse(fs.readFileSync(pkgJsonPath).toString()); + } + catch (noop) { } + pkgs[npath] = obj || {}; + return pkgs[npath]; + } + let parseFn = null; + let parseContext = null; + self.parse = function parse(args, shortCircuit, _parseFn) { + argsert_1.argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); + freeze(); + if (typeof args === 'undefined') { + const argv = self._parseArgs(processArgs); + const tmpParsed = self.parsed; + unfreeze(); + // TODO: remove this compatibility hack when we release yargs@15.x: + self.parsed = tmpParsed; + return argv; + } + // a context object can optionally be provided, this allows + // additional information to be passed to a command handler. + if (typeof shortCircuit === 'object') { + parseContext = shortCircuit; + shortCircuit = _parseFn; + } + // by providing a function as a second argument to + // parse you can capture output that would otherwise + // default to printing to stdout/stderr. + if (typeof shortCircuit === 'function') { + parseFn = shortCircuit; + shortCircuit = false; + } + // completion short-circuits the parsing process, + // skipping validation, etc. + if (!shortCircuit) + processArgs = args; + if (parseFn) + exitProcess = false; + const parsed = self._parseArgs(args, !!shortCircuit); + completion.setParsed(self.parsed); + if (parseFn) + parseFn(exitError, parsed, output); + unfreeze(); + return parsed; + }; + self._getParseContext = () => parseContext || {}; + self._hasParseCallback = () => !!parseFn; + self.option = self.options = function option(key, opt) { + argsert_1.argsert(' [object]', [key, opt], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach((k) => { + self.options(k, key[k]); + }); + } + else { + if (typeof opt !== 'object') { + opt = {}; + } + options.key[key] = true; // track manually set keys. + if (opt.alias) + self.alias(key, opt.alias); + const deprecate = opt.deprecate || opt.deprecated; + if (deprecate) { + self.deprecateOption(key, deprecate); + } + const demand = opt.demand || opt.required || opt.require; + // A required option can be specified via "demand: true". + if (demand) { + self.demand(key, demand); + } + if (opt.demandOption) { + self.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); + } + if (opt.conflicts) { + self.conflicts(key, opt.conflicts); + } + if ('default' in opt) { + self.default(key, opt.default); + } + if (opt.implies !== undefined) { + self.implies(key, opt.implies); + } + if (opt.nargs !== undefined) { + self.nargs(key, opt.nargs); + } + if (opt.config) { + self.config(key, opt.configParser); + } + if (opt.normalize) { + self.normalize(key); + } + if (opt.choices) { + self.choices(key, opt.choices); + } + if (opt.coerce) { + self.coerce(key, opt.coerce); + } + if (opt.group) { + self.group(key, opt.group); + } + if (opt.boolean || opt.type === 'boolean') { + self.boolean(key); + if (opt.alias) + self.boolean(opt.alias); + } + if (opt.array || opt.type === 'array') { + self.array(key); + if (opt.alias) + self.array(opt.alias); + } + if (opt.number || opt.type === 'number') { + self.number(key); + if (opt.alias) + self.number(opt.alias); + } + if (opt.string || opt.type === 'string') { + self.string(key); + if (opt.alias) + self.string(opt.alias); + } + if (opt.count || opt.type === 'count') { + self.count(key); + } + if (typeof opt.global === 'boolean') { + self.global(key, opt.global); + } + if (opt.defaultDescription) { + options.defaultDescription[key] = opt.defaultDescription; + } + if (opt.skipValidation) { + self.skipValidation(key); + } + const desc = opt.describe || opt.description || opt.desc; + self.describe(key, desc); + if (opt.hidden) { + self.hide(key); + } + if (opt.requiresArg) { + self.requiresArg(key); + } + } + return self; + }; + self.getOptions = () => options; + self.positional = function (key, opts) { + argsert_1.argsert(' ', [key, opts], arguments.length); + if (context.resets === 0) { + throw new yerror_1.YError(".positional() can only be called in a command's builder function"); + } + // .positional() only supports a subset of the configuration + // options available to .option(). + const supportedOpts = ['default', 'defaultDescription', 'implies', 'normalize', + 'choices', 'conflicts', 'coerce', 'type', 'describe', + 'desc', 'description', 'alias']; + opts = obj_filter_1.objFilter(opts, (k, v) => { + let accept = supportedOpts.indexOf(k) !== -1; + // type can be one of string|number|boolean. + if (k === 'type' && ['string', 'number', 'boolean'].indexOf(v) === -1) + accept = false; + return accept; + }); + // copy over any settings that can be inferred from the command string. + const fullCommand = context.fullCommands[context.fullCommands.length - 1]; + const parseOptions = fullCommand ? command.cmdToParseOptions(fullCommand) : { + array: [], + alias: {}, + default: {}, + demand: {} + }; + common_types_1.objectKeys(parseOptions).forEach((pk) => { + const parseOption = parseOptions[pk]; + if (Array.isArray(parseOption)) { + if (parseOption.indexOf(key) !== -1) + opts[pk] = true; + } + else { + if (parseOption[key] && !(pk in opts)) + opts[pk] = parseOption[key]; + } + }); + self.group(key, usage.getPositionalGroupName()); + return self.option(key, opts); + }; + self.group = function group(opts, groupName) { + argsert_1.argsert(' ', [opts, groupName], arguments.length); + const existing = preservedGroups[groupName] || groups[groupName]; + if (preservedGroups[groupName]) { + // we now only need to track this group name in groups. + delete preservedGroups[groupName]; + } + const seen = {}; + groups[groupName] = (existing || []).concat(opts).filter((key) => { + if (seen[key]) + return false; + return (seen[key] = true); + }); + return self; + }; + // combine explicit and preserved groups. explicit groups should be first + self.getGroups = () => Object.assign({}, groups, preservedGroups); + // as long as options.envPrefix is not undefined, + // parser will apply env vars matching prefix to argv + self.env = function (prefix) { + argsert_1.argsert('[string|boolean]', [prefix], arguments.length); + if (prefix === false) + delete options.envPrefix; + else + options.envPrefix = prefix || ''; + return self; + }; + self.wrap = function (cols) { + argsert_1.argsert('', [cols], arguments.length); + usage.wrap(cols); + return self; + }; + let strict = false; + self.strict = function (enabled) { + argsert_1.argsert('[boolean]', [enabled], arguments.length); + strict = enabled !== false; + return self; + }; + self.getStrict = () => strict; + let strictCommands = false; + self.strictCommands = function (enabled) { + argsert_1.argsert('[boolean]', [enabled], arguments.length); + strictCommands = enabled !== false; + return self; + }; + self.getStrictCommands = () => strictCommands; + let parserConfig = {}; + self.parserConfiguration = function parserConfiguration(config) { + argsert_1.argsert('', [config], arguments.length); + parserConfig = config; + return self; + }; + self.getParserConfiguration = () => parserConfig; + self.showHelp = function (level) { + argsert_1.argsert('[string|function]', [level], arguments.length); + if (!self.parsed) + self._parseArgs(processArgs); // run parser, if it has not already been executed. + if (command.hasDefaultCommand()) { + context.resets++; // override the restriction on top-level positoinals. + command.runDefaultBuilderOn(self); + } + usage.showHelp(level); + return self; + }; + let versionOpt = null; + self.version = function version(opt, msg, ver) { + const defaultVersionOpt = 'version'; + argsert_1.argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); + // nuke the key previously configured + // to return version #. + if (versionOpt) { + deleteFromParserHintObject(versionOpt); + usage.version(undefined); + versionOpt = null; + } + if (arguments.length === 0) { + ver = guessVersion(); + opt = defaultVersionOpt; + } + else if (arguments.length === 1) { + if (opt === false) { // disable default 'version' key. + return self; + } + ver = opt; + opt = defaultVersionOpt; + } + else if (arguments.length === 2) { + ver = msg; + msg = undefined; + } + versionOpt = typeof opt === 'string' ? opt : defaultVersionOpt; + msg = msg || usage.deferY18nLookup('Show version number'); + usage.version(ver || undefined); + self.boolean(versionOpt); + self.describe(versionOpt, msg); + return self; + }; + function guessVersion() { + const obj = pkgUp(); + return obj.version || 'unknown'; + } + let helpOpt = null; + self.addHelpOpt = self.help = function addHelpOpt(opt, msg) { + const defaultHelpOpt = 'help'; + argsert_1.argsert('[string|boolean] [string]', [opt, msg], arguments.length); + // nuke the key previously configured + // to return help. + if (helpOpt) { + deleteFromParserHintObject(helpOpt); + helpOpt = null; + } + if (arguments.length === 1) { + if (opt === false) + return self; + } + // use arguments, fallback to defaults for opt and msg + helpOpt = typeof opt === 'string' ? opt : defaultHelpOpt; + self.boolean(helpOpt); + self.describe(helpOpt, msg || usage.deferY18nLookup('Show help')); + return self; + }; + const defaultShowHiddenOpt = 'show-hidden'; + options.showHiddenOpt = defaultShowHiddenOpt; + self.addShowHiddenOpt = self.showHidden = function addShowHiddenOpt(opt, msg) { + argsert_1.argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (arguments.length === 1) { + if (opt === false) + return self; + } + const showHiddenOpt = typeof opt === 'string' ? opt : defaultShowHiddenOpt; + self.boolean(showHiddenOpt); + self.describe(showHiddenOpt, msg || usage.deferY18nLookup('Show hidden options')); + options.showHiddenOpt = showHiddenOpt; + return self; + }; + self.hide = function hide(key) { + argsert_1.argsert('', [key], arguments.length); + options.hiddenOptions.push(key); + return self; + }; + self.showHelpOnFail = function showHelpOnFail(enabled, message) { + argsert_1.argsert('[boolean|string] [string]', [enabled, message], arguments.length); + usage.showHelpOnFail(enabled, message); + return self; + }; + var exitProcess = true; + self.exitProcess = function (enabled = true) { + argsert_1.argsert('[boolean]', [enabled], arguments.length); + exitProcess = enabled; + return self; + }; + self.getExitProcess = () => exitProcess; + var completionCommand = null; + self.completion = function (cmd, desc, fn) { + argsert_1.argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); + // a function to execute when generating + // completions can be provided as the second + // or third argument to completion. + if (typeof desc === 'function') { + fn = desc; + desc = undefined; + } + // register the completion command. + completionCommand = cmd || completionCommand || 'completion'; + if (!desc && desc !== false) { + desc = 'generate completion script'; + } + self.command(completionCommand, desc); + // a function can be provided + if (fn) + completion.registerFunction(fn); + return self; + }; + self.showCompletionScript = function ($0, cmd) { + argsert_1.argsert('[string] [string]', [$0, cmd], arguments.length); + $0 = $0 || self.$0; + _logger.log(completion.generateCompletionScript($0, cmd || completionCommand || 'completion')); + return self; + }; + self.getCompletion = function (args, done) { + argsert_1.argsert(' ', [args, done], arguments.length); + completion.getCompletion(args, done); + }; + self.locale = function (locale) { + argsert_1.argsert('[string]', [locale], arguments.length); + if (!locale) { + guessLocale(); + return y18n.getLocale(); + } + detectLocale = false; + y18n.setLocale(locale); + return self; + }; + self.updateStrings = self.updateLocale = function (obj) { + argsert_1.argsert('', [obj], arguments.length); + detectLocale = false; + y18n.updateLocale(obj); + return self; + }; + let detectLocale = true; + self.detectLocale = function (detect) { + argsert_1.argsert('', [detect], arguments.length); + detectLocale = detect; + return self; + }; + self.getDetectLocale = () => detectLocale; + var hasOutput = false; + var exitError = null; + // maybe exit, always capture + // context about why we wanted to exit. + self.exit = (code, err) => { + hasOutput = true; + exitError = err; + if (exitProcess) + process.exit(code); + }; + // we use a custom logger that buffers output, + // so that we can print to non-CLIs, e.g., chat-bots. + const _logger = { + log(...args) { + if (!self._hasParseCallback()) + console.log(...args); + hasOutput = true; + if (output.length) + output += '\n'; + output += args.join(' '); + }, + error(...args) { + if (!self._hasParseCallback()) + console.error(...args); + hasOutput = true; + if (output.length) + output += '\n'; + output += args.join(' '); + } + }; + self._getLoggerInstance = () => _logger; + // has yargs output an error our help + // message in the current execution context. + self._hasOutput = () => hasOutput; + self._setHasOutput = () => { + hasOutput = true; + }; + let recommendCommands; + self.recommendCommands = function (recommend = true) { + argsert_1.argsert('[boolean]', [recommend], arguments.length); + recommendCommands = recommend; + return self; + }; + self.getUsageInstance = () => usage; + self.getValidationInstance = () => validation; + self.getCommandInstance = () => command; + self.terminalWidth = () => { + argsert_1.argsert([], 0); + return typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null; + }; + Object.defineProperty(self, 'argv', { + get: () => self._parseArgs(processArgs), + enumerable: true + }); + self._parseArgs = function parseArgs(args, shortCircuit, _calledFromCommand, commandIndex) { + let skipValidation = !!_calledFromCommand; + args = args || processArgs; + options.__ = y18n.__; + options.configuration = self.getParserConfiguration(); + const populateDoubleDash = !!options.configuration['populate--']; + const config = Object.assign({}, options.configuration, { + 'populate--': true + }); + const parsed = Parser.detailed(args, Object.assign({}, options, { + configuration: config + })); + let argv = parsed.argv; + if (parseContext) + argv = Object.assign({}, argv, parseContext); + const aliases = parsed.aliases; + argv.$0 = self.$0; + self.parsed = parsed; + try { + guessLocale(); // guess locale lazily, so that it can be turned off in chain. + // while building up the argv object, there + // are two passes through the parser. If completion + // is being performed short-circuit on the first pass. + if (shortCircuit) { + return (populateDoubleDash || _calledFromCommand) ? argv : self._copyDoubleDash(argv); + } + // if there's a handler associated with a + // command defer processing to it. + if (helpOpt) { + // consider any multi-char helpOpt alias as a valid help command + // unless all helpOpt aliases are single-char + // note that parsed.aliases is a normalized bidirectional map :) + const helpCmds = [helpOpt] + .concat(aliases[helpOpt] || []) + .filter(k => k.length > 1); + // check if help should trigger and strip it from _. + if (~helpCmds.indexOf(argv._[argv._.length - 1])) { + argv._.pop(); + argv[helpOpt] = true; + } + } + const handlerKeys = command.getCommands(); + const requestCompletions = completion.completionKey in argv; + const skipRecommendation = argv[helpOpt] || requestCompletions; + const skipDefaultCommand = skipRecommendation && (handlerKeys.length > 1 || handlerKeys[0] !== '$0'); + if (argv._.length) { + if (handlerKeys.length) { + let firstUnknownCommand; + for (let i = (commandIndex || 0), cmd; argv._[i] !== undefined; i++) { + cmd = String(argv._[i]); + if (~handlerKeys.indexOf(cmd) && cmd !== completionCommand) { + // commands are executed using a recursive algorithm that executes + // the deepest command first; we keep track of the position in the + // argv._ array that is currently being executed. + const innerArgv = command.runCommand(cmd, self, parsed, i + 1); + return populateDoubleDash ? innerArgv : self._copyDoubleDash(innerArgv); + } + else if (!firstUnknownCommand && cmd !== completionCommand) { + firstUnknownCommand = cmd; + break; + } + } + // run the default command, if defined + if (command.hasDefaultCommand() && !skipDefaultCommand) { + const innerArgv = command.runCommand(null, self, parsed); + return populateDoubleDash ? innerArgv : self._copyDoubleDash(innerArgv); + } + // recommend a command if recommendCommands() has + // been enabled, and no commands were found to execute + if (recommendCommands && firstUnknownCommand && !skipRecommendation) { + validation.recommendCommands(firstUnknownCommand, handlerKeys); + } + } + // generate a completion script for adding to ~/.bashrc. + if (completionCommand && ~argv._.indexOf(completionCommand) && !requestCompletions) { + if (exitProcess) + setBlocking(true); + self.showCompletionScript(); + self.exit(0); + } + } + else if (command.hasDefaultCommand() && !skipDefaultCommand) { + const innerArgv = command.runCommand(null, self, parsed); + return populateDoubleDash ? innerArgv : self._copyDoubleDash(innerArgv); + } + // we must run completions first, a user might + // want to complete the --help or --version option. + if (requestCompletions) { + if (exitProcess) + setBlocking(true); + // we allow for asynchronous completions, + // e.g., loading in a list of commands from an API. + args = [].concat(args); + const completionArgs = args.slice(args.indexOf(`--${completion.completionKey}`) + 1); + completion.getCompletion(completionArgs, (completions) => { + ; + (completions || []).forEach((completion) => { + _logger.log(completion); + }); + self.exit(0); + }); + return (populateDoubleDash || _calledFromCommand) ? argv : self._copyDoubleDash(argv); + } + // Handle 'help' and 'version' options + // if we haven't already output help! + if (!hasOutput) { + Object.keys(argv).forEach((key) => { + if (key === helpOpt && argv[key]) { + if (exitProcess) + setBlocking(true); + skipValidation = true; + self.showHelp('log'); + self.exit(0); + } + else if (key === versionOpt && argv[key]) { + if (exitProcess) + setBlocking(true); + skipValidation = true; + usage.showVersion(); + self.exit(0); + } + }); + } + // Check if any of the options to skip validation were provided + if (!skipValidation && options.skipValidation.length > 0) { + skipValidation = Object.keys(argv).some(key => options.skipValidation.indexOf(key) >= 0 && argv[key] === true); + } + // If the help or version options where used and exitProcess is false, + // or if explicitly skipped, we won't run validations. + if (!skipValidation) { + if (parsed.error) + throw new yerror_1.YError(parsed.error.message); + // if we're executed via bash completion, don't + // bother with validation. + if (!requestCompletions) { + self._runValidation(argv, aliases, {}, parsed.error); + } + } + } + catch (err) { + if (err instanceof yerror_1.YError) + usage.fail(err.message, err); + else + throw err; + } + return (populateDoubleDash || _calledFromCommand) ? argv : self._copyDoubleDash(argv); + }; + // to simplify the parsing of positionals in commands, + // we temporarily populate '--' rather than _, with arguments + // after the '--' directive. After the parse, we copy these back. + self._copyDoubleDash = function (argv) { + if (is_promise_1.isPromise(argv) || !argv._ || !argv['--']) + return argv; + argv._.push.apply(argv._, argv['--']); + // TODO(bcoe): refactor command parsing such that this delete is not + // necessary: https://github.com/yargs/yargs/issues/1482 + try { + delete argv['--']; + } + catch (_err) { } + return argv; + }; + self._runValidation = function runValidation(argv, aliases, positionalMap, parseErrors, isDefaultCommand = false) { + if (parseErrors) + throw new yerror_1.YError(parseErrors.message); + validation.nonOptionCount(argv); + validation.requiredArguments(argv); + let failedStrictCommands = false; + if (strictCommands) { + failedStrictCommands = validation.unknownCommands(argv); + } + if (strict && !failedStrictCommands) { + validation.unknownArguments(argv, aliases, positionalMap, isDefaultCommand); + } + validation.customChecks(argv, aliases); + validation.limitedChoices(argv); + validation.implications(argv); + validation.conflicting(argv); + }; + function guessLocale() { + if (!detectLocale) + return; + const locale = process.env.LC_ALL || process.env.LC_MESSAGES || process.env.LANG || process.env.LANGUAGE || 'en_US'; + self.locale(locale.replace(/[.:].*/, '')); + } + // an app should almost always have --version and --help, + // if you *really* want to disable this use .help(false)/.version(false). + self.help(); + self.version(); + return self; +} +exports.Yargs = Yargs; +// rebase an absolute path to a relative one with respect to a base directory +// exported for tests +function rebase(base, dir) { + return path.relative(base, dir); +} +exports.rebase = rebase; +function isYargsInstance(y) { + return !!y && (typeof y._parseArgs === 'function'); +} +exports.isYargsInstance = isYargsInstance; diff --git a/node_modules/yargs/build/lib/yerror.d.ts b/node_modules/yargs/build/lib/yerror.d.ts new file mode 100644 index 0000000..024d0c7 --- /dev/null +++ b/node_modules/yargs/build/lib/yerror.d.ts @@ -0,0 +1,4 @@ +export declare class YError extends Error { + name: string; + constructor(msg?: string | null); +} diff --git a/node_modules/yargs/build/lib/yerror.js b/node_modules/yargs/build/lib/yerror.js new file mode 100644 index 0000000..0fa146e --- /dev/null +++ b/node_modules/yargs/build/lib/yerror.js @@ -0,0 +1,11 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.YError = void 0; +class YError extends Error { + constructor(msg) { + super(msg || 'yargs error'); + this.name = 'YError'; + Error.captureStackTrace(this, YError); + } +} +exports.YError = YError; diff --git a/node_modules/yargs/index.js b/node_modules/yargs/index.js new file mode 100644 index 0000000..7dc62de --- /dev/null +++ b/node_modules/yargs/index.js @@ -0,0 +1,40 @@ +'use strict' +// classic singleton yargs API, to use yargs +// without running as a singleton do: +// require('yargs/yargs')(process.argv.slice(2)) +const yargs = require('./yargs') +const processArgv = require('./build/lib/process-argv') + +Argv(processArgv.getProcessArgvWithoutBin()) + +module.exports = Argv + +function Argv (processArgs, cwd) { + const argv = yargs(processArgs, cwd, require) + singletonify(argv) + return argv +} + +/* Hack an instance of Argv with process.argv into Argv + so people can do + require('yargs')(['--beeble=1','-z','zizzle']).argv + to parse a list of args and + require('yargs').argv + to get a parsed version of process.argv. +*/ +function singletonify (inst) { + Object.keys(inst).forEach((key) => { + if (key === 'argv') { + Argv.__defineGetter__(key, inst.__lookupGetter__(key)) + } else if (typeof inst[key] === 'function') { + Argv[key] = inst[key].bind(inst) + } else { + Argv.__defineGetter__('$0', () => { + return inst.$0 + }) + Argv.__defineGetter__('parsed', () => { + return inst.parsed + }) + } + }) +} diff --git a/node_modules/yargs/locales/be.json b/node_modules/yargs/locales/be.json new file mode 100644 index 0000000..e28fa30 --- /dev/null +++ b/node_modules/yargs/locales/be.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Каманды:", + "Options:": "Опцыі:", + "Examples:": "Прыклады:", + "boolean": "булевы тып", + "count": "падлік", + "string": "радковы тып", + "number": "лік", + "array": "масіў", + "required": "неабходна", + "default": "па змаўчанні", + "default:": "па змаўчанні:", + "choices:": "магчымасці:", + "aliases:": "аліасы:", + "generated-value": "згенераванае значэнне", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s", + "other": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s", + "other": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s" + }, + "Missing argument value: %s": { + "one": "Не хапае значэння аргументу: %s", + "other": "Не хапае значэнняў аргументаў: %s" + }, + "Missing required argument: %s": { + "one": "Не хапае неабходнага аргументу: %s", + "other": "Не хапае неабходных аргументаў: %s" + }, + "Unknown argument: %s": { + "one": "Невядомы аргумент: %s", + "other": "Невядомыя аргументы: %s" + }, + "Invalid values:": "Несапраўдныя значэння:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s", + "Argument check failed: %s": "Праверка аргументаў не ўдалася: %s", + "Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:", + "Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s", + "Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s", + "Path to JSON config file": "Шлях да файла канфігурацыі JSON", + "Show help": "Паказаць дапамогу", + "Show version number": "Паказаць нумар версіі", + "Did you mean %s?": "Вы мелі на ўвазе %s?" +} diff --git a/node_modules/yargs/locales/de.json b/node_modules/yargs/locales/de.json new file mode 100644 index 0000000..dc73ec3 --- /dev/null +++ b/node_modules/yargs/locales/de.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Kommandos:", + "Options:": "Optionen:", + "Examples:": "Beispiele:", + "boolean": "boolean", + "count": "Zähler", + "string": "string", + "number": "Zahl", + "array": "array", + "required": "erforderlich", + "default": "Standard", + "default:": "Standard:", + "choices:": "Möglichkeiten:", + "aliases:": "Aliase:", + "generated-value": "Generierter-Wert", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt", + "other": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt", + "other": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt" + }, + "Missing argument value: %s": { + "one": "Fehlender Argumentwert: %s", + "other": "Fehlende Argumentwerte: %s" + }, + "Missing required argument: %s": { + "one": "Fehlendes Argument: %s", + "other": "Fehlende Argumente: %s" + }, + "Unknown argument: %s": { + "one": "Unbekanntes Argument: %s", + "other": "Unbekannte Argumente: %s" + }, + "Invalid values:": "Unzulässige Werte:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s", + "Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s", + "Implications failed:": "Fehlende abhängige Argumente:", + "Not enough arguments following: %s": "Nicht genügend Argumente nach: %s", + "Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s", + "Path to JSON config file": "Pfad zur JSON-Config Datei", + "Show help": "Hilfe anzeigen", + "Show version number": "Version anzeigen", + "Did you mean %s?": "Meintest du %s?" +} diff --git a/node_modules/yargs/locales/en.json b/node_modules/yargs/locales/en.json new file mode 100644 index 0000000..d794947 --- /dev/null +++ b/node_modules/yargs/locales/en.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Commands:", + "Options:": "Options:", + "Examples:": "Examples:", + "boolean": "boolean", + "count": "count", + "string": "string", + "number": "number", + "array": "array", + "required": "required", + "default": "default", + "default:": "default:", + "choices:": "choices:", + "aliases:": "aliases:", + "generated-value": "generated-value", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Not enough non-option arguments: got %s, need at least %s", + "other": "Not enough non-option arguments: got %s, need at least %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Too many non-option arguments: got %s, maximum of %s", + "other": "Too many non-option arguments: got %s, maximum of %s" + }, + "Missing argument value: %s": { + "one": "Missing argument value: %s", + "other": "Missing argument values: %s" + }, + "Missing required argument: %s": { + "one": "Missing required argument: %s", + "other": "Missing required arguments: %s" + }, + "Unknown argument: %s": { + "one": "Unknown argument: %s", + "other": "Unknown arguments: %s" + }, + "Invalid values:": "Invalid values:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s", + "Argument check failed: %s": "Argument check failed: %s", + "Implications failed:": "Missing dependent arguments:", + "Not enough arguments following: %s": "Not enough arguments following: %s", + "Invalid JSON config file: %s": "Invalid JSON config file: %s", + "Path to JSON config file": "Path to JSON config file", + "Show help": "Show help", + "Show version number": "Show version number", + "Did you mean %s?": "Did you mean %s?", + "Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive", + "Positionals:": "Positionals:", + "command": "command", + "deprecated": "deprecated", + "deprecated: %s": "deprecated: %s" +} diff --git a/node_modules/yargs/locales/es.json b/node_modules/yargs/locales/es.json new file mode 100644 index 0000000..d77b461 --- /dev/null +++ b/node_modules/yargs/locales/es.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opciones:", + "Examples:": "Ejemplos:", + "boolean": "booleano", + "count": "cuenta", + "string": "cadena de caracteres", + "number": "número", + "array": "tabla", + "required": "requerido", + "default": "defecto", + "default:": "defecto:", + "choices:": "selección:", + "aliases:": "alias:", + "generated-value": "valor-generado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s", + "other": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s", + "other": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s" + }, + "Missing argument value: %s": { + "one": "Falta argumento: %s", + "other": "Faltan argumentos: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento requerido: %s", + "other": "Faltan argumentos requeridos: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconocido: %s", + "other": "Argumentos desconocidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s", + "Argument check failed: %s": "Verificación de argumento ha fallado: %s", + "Implications failed:": "Implicaciones fallidas:", + "Not enough arguments following: %s": "No hay suficientes argumentos después de: %s", + "Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s", + "Path to JSON config file": "Ruta al archivo de configuración JSON", + "Show help": "Muestra ayuda", + "Show version number": "Muestra número de versión", + "Did you mean %s?": "Quisiste decir %s?" +} diff --git a/node_modules/yargs/locales/fi.json b/node_modules/yargs/locales/fi.json new file mode 100644 index 0000000..0728c57 --- /dev/null +++ b/node_modules/yargs/locales/fi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Komennot:", + "Options:": "Valinnat:", + "Examples:": "Esimerkkejä:", + "boolean": "totuusarvo", + "count": "lukumäärä", + "string": "merkkijono", + "number": "numero", + "array": "taulukko", + "required": "pakollinen", + "default": "oletusarvo", + "default:": "oletusarvo:", + "choices:": "vaihtoehdot:", + "aliases:": "aliakset:", + "generated-value": "generoitu-arvo", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s", + "other": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s", + "other": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s" + }, + "Missing argument value: %s": { + "one": "Argumentin arvo puuttuu: %s", + "other": "Argumentin arvot puuttuvat: %s" + }, + "Missing required argument: %s": { + "one": "Pakollinen argumentti puuttuu: %s", + "other": "Pakollisia argumentteja puuttuu: %s" + }, + "Unknown argument: %s": { + "one": "Tuntematon argumenttn: %s", + "other": "Tuntemattomia argumentteja: %s" + }, + "Invalid values:": "Virheelliset arvot:", + "Argument: %s, Given: %s, Choices: %s": "Argumentti: %s, Annettu: %s, Vaihtoehdot: %s", + "Argument check failed: %s": "Argumentin tarkistus epäonnistui: %s", + "Implications failed:": "Riippuvia argumentteja puuttuu:", + "Not enough arguments following: %s": "Argumentin perässä ei ole tarpeeksi argumentteja: %s", + "Invalid JSON config file: %s": "Epävalidi JSON-asetustiedosto: %s", + "Path to JSON config file": "JSON-asetustiedoston polku", + "Show help": "Näytä ohje", + "Show version number": "Näytä versionumero", + "Did you mean %s?": "Tarkoititko %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentit %s ja %s eivät ole yhteensopivat", + "Positionals:": "Sijaintiparametrit:", + "command": "komento" +} diff --git a/node_modules/yargs/locales/fr.json b/node_modules/yargs/locales/fr.json new file mode 100644 index 0000000..edd743f --- /dev/null +++ b/node_modules/yargs/locales/fr.json @@ -0,0 +1,53 @@ +{ + "Commands:": "Commandes :", + "Options:": "Options :", + "Examples:": "Exemples :", + "boolean": "booléen", + "count": "compteur", + "string": "chaîne de caractères", + "number": "nombre", + "array": "tableau", + "required": "requis", + "default": "défaut", + "default:": "défaut :", + "choices:": "choix :", + "aliases:": "alias :", + "generated-value": "valeur générée", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Pas assez d'arguments (hors options) : reçu %s, besoin d'au moins %s", + "other": "Pas assez d'arguments (hors options) : reçus %s, besoin d'au moins %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Trop d'arguments (hors options) : reçu %s, maximum de %s", + "other": "Trop d'arguments (hors options) : reçus %s, maximum de %s" + }, + "Missing argument value: %s": { + "one": "Argument manquant : %s", + "other": "Arguments manquants : %s" + }, + "Missing required argument: %s": { + "one": "Argument requis manquant : %s", + "other": "Arguments requis manquants : %s" + }, + "Unknown argument: %s": { + "one": "Argument inconnu : %s", + "other": "Arguments inconnus : %s" + }, + "Unknown command: %s": { + "one": "Commande inconnue : %s", + "other": "Commandes inconnues : %s" + }, + "Invalid values:": "Valeurs invalides :", + "Argument: %s, Given: %s, Choices: %s": "Argument : %s, donné : %s, choix : %s", + "Argument check failed: %s": "Echec de la vérification de l'argument : %s", + "Implications failed:": "Arguments dépendants manquants :", + "Not enough arguments following: %s": "Pas assez d'arguments après : %s", + "Invalid JSON config file: %s": "Fichier de configuration JSON invalide : %s", + "Path to JSON config file": "Chemin du fichier de configuration JSON", + "Show help": "Affiche l'aide", + "Show version number": "Affiche le numéro de version", + "Did you mean %s?": "Vouliez-vous dire %s ?", + "Arguments %s and %s are mutually exclusive" : "Les arguments %s et %s sont mutuellement exclusifs", + "Positionals:": "Arguments positionnels :", + "command": "commande" +} diff --git a/node_modules/yargs/locales/hi.json b/node_modules/yargs/locales/hi.json new file mode 100644 index 0000000..a9de77c --- /dev/null +++ b/node_modules/yargs/locales/hi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "आदेश:", + "Options:": "विकल्प:", + "Examples:": "उदाहरण:", + "boolean": "सत्यता", + "count": "संख्या", + "string": "वर्णों का तार ", + "number": "अंक", + "array": "सरणी", + "required": "आवश्यक", + "default": "डिफॉल्ट", + "default:": "डिफॉल्ट:", + "choices:": "विकल्प:", + "aliases:": "उपनाम:", + "generated-value": "उत्पन्न-मूल्य", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है", + "other": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य", + "other": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य" + }, + "Missing argument value: %s": { + "one": "कुछ तर्को के मूल्य गुम हैं: %s", + "other": "कुछ तर्को के मूल्य गुम हैं: %s" + }, + "Missing required argument: %s": { + "one": "आवश्यक तर्क गुम हैं: %s", + "other": "आवश्यक तर्क गुम हैं: %s" + }, + "Unknown argument: %s": { + "one": "अज्ञात तर्क प्राप्त: %s", + "other": "अज्ञात तर्क प्राप्त: %s" + }, + "Invalid values:": "अमान्य मूल्य:", + "Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s", + "Argument check failed: %s": "तर्क जांच विफल: %s", + "Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:", + "Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s", + "Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s", + "Path to JSON config file": "JSON config फाइल का पथ", + "Show help": "सहायता दिखाएँ", + "Show version number": "Version संख्या दिखाएँ", + "Did you mean %s?": "क्या आपका मतलब है %s?", + "Arguments %s and %s are mutually exclusive" : "तर्क %s और %s परस्पर अनन्य हैं", + "Positionals:": "स्थानीय:", + "command": "आदेश" +} diff --git a/node_modules/yargs/locales/hu.json b/node_modules/yargs/locales/hu.json new file mode 100644 index 0000000..21492d0 --- /dev/null +++ b/node_modules/yargs/locales/hu.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Parancsok:", + "Options:": "Opciók:", + "Examples:": "Példák:", + "boolean": "boolean", + "count": "számláló", + "string": "szöveg", + "number": "szám", + "array": "tömb", + "required": "kötelező", + "default": "alapértelmezett", + "default:": "alapértelmezett:", + "choices:": "lehetőségek:", + "aliases:": "aliaszok:", + "generated-value": "generált-érték", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell", + "other": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet", + "other": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet" + }, + "Missing argument value: %s": { + "one": "Hiányzó argumentum érték: %s", + "other": "Hiányzó argumentum értékek: %s" + }, + "Missing required argument: %s": { + "one": "Hiányzó kötelező argumentum: %s", + "other": "Hiányzó kötelező argumentumok: %s" + }, + "Unknown argument: %s": { + "one": "Ismeretlen argumentum: %s", + "other": "Ismeretlen argumentumok: %s" + }, + "Invalid values:": "Érvénytelen érték:", + "Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s", + "Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s", + "Implications failed:": "Implikációk sikertelenek:", + "Not enough arguments following: %s": "Nem elég argumentum követi: %s", + "Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s", + "Path to JSON config file": "JSON konfigurációs file helye", + "Show help": "Súgo megjelenítése", + "Show version number": "Verziószám megjelenítése", + "Did you mean %s?": "Erre gondoltál %s?" +} diff --git a/node_modules/yargs/locales/id.json b/node_modules/yargs/locales/id.json new file mode 100644 index 0000000..125867c --- /dev/null +++ b/node_modules/yargs/locales/id.json @@ -0,0 +1,50 @@ + +{ + "Commands:": "Perintah:", + "Options:": "Pilihan:", + "Examples:": "Contoh:", + "boolean": "boolean", + "count": "jumlah", + "number": "nomor", + "string": "string", + "array": "larik", + "required": "diperlukan", + "default": "bawaan", + "default:": "bawaan:", + "aliases:": "istilah lain:", + "choices:": "pilihan:", + "generated-value": "nilai-yang-dihasilkan", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumen wajib kurang: hanya %s, minimal %s", + "other": "Argumen wajib kurang: hanya %s, minimal %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Terlalu banyak argumen wajib: ada %s, maksimal %s", + "other": "Terlalu banyak argumen wajib: ada %s, maksimal %s" + }, + "Missing argument value: %s": { + "one": "Kurang argumen: %s", + "other": "Kurang argumen: %s" + }, + "Missing required argument: %s": { + "one": "Kurang argumen wajib: %s", + "other": "Kurang argumen wajib: %s" + }, + "Unknown argument: %s": { + "one": "Argumen tak diketahui: %s", + "other": "Argumen tak diketahui: %s" + }, + "Invalid values:": "Nilai-nilai tidak valid:", + "Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s", + "Argument check failed: %s": "Pemeriksaan argument gagal: %s", + "Implications failed:": "Implikasi gagal:", + "Not enough arguments following: %s": "Kurang argumen untuk: %s", + "Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s", + "Path to JSON config file": "Alamat berkas konfigurasi JSON", + "Show help": "Lihat bantuan", + "Show version number": "Lihat nomor versi", + "Did you mean %s?": "Maksud Anda: %s?", + "Arguments %s and %s are mutually exclusive" : "Argumen %s dan %s saling eksklusif", + "Positionals:": "Posisional-posisional:", + "command": "perintah" +} diff --git a/node_modules/yargs/locales/it.json b/node_modules/yargs/locales/it.json new file mode 100644 index 0000000..fde5756 --- /dev/null +++ b/node_modules/yargs/locales/it.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandi:", + "Options:": "Opzioni:", + "Examples:": "Esempi:", + "boolean": "booleano", + "count": "contatore", + "string": "stringa", + "number": "numero", + "array": "vettore", + "required": "richiesto", + "default": "predefinito", + "default:": "predefinito:", + "choices:": "scelte:", + "aliases:": "alias:", + "generated-value": "valore generato", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s", + "other": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s", + "other": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s" + }, + "Missing argument value: %s": { + "one": "Argomento mancante: %s", + "other": "Argomenti mancanti: %s" + }, + "Missing required argument: %s": { + "one": "Argomento richiesto mancante: %s", + "other": "Argomenti richiesti mancanti: %s" + }, + "Unknown argument: %s": { + "one": "Argomento sconosciuto: %s", + "other": "Argomenti sconosciuti: %s" + }, + "Invalid values:": "Valori non validi:", + "Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s", + "Argument check failed: %s": "Controllo dell'argomento fallito: %s", + "Implications failed:": "Argomenti dipendenti mancanti:", + "Not enough arguments following: %s": "Argomenti insufficienti dopo: %s", + "Invalid JSON config file: %s": "File di configurazione JSON non valido: %s", + "Path to JSON config file": "Percorso del file di configurazione JSON", + "Show help": "Mostra la schermata di aiuto", + "Show version number": "Mostra il numero di versione", + "Did you mean %s?": "Intendi forse %s?" +} diff --git a/node_modules/yargs/locales/ja.json b/node_modules/yargs/locales/ja.json new file mode 100644 index 0000000..3954ae6 --- /dev/null +++ b/node_modules/yargs/locales/ja.json @@ -0,0 +1,51 @@ +{ + "Commands:": "コマンド:", + "Options:": "オプション:", + "Examples:": "例:", + "boolean": "真偽", + "count": "カウント", + "string": "文字列", + "number": "数値", + "array": "配列", + "required": "必須", + "default": "デフォルト", + "default:": "デフォルト:", + "choices:": "選択してください:", + "aliases:": "エイリアス:", + "generated-value": "生成された値", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:", + "other": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:", + "other": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:" + }, + "Missing argument value: %s": { + "one": "引数の値が見つかりません: %s", + "other": "引数の値が見つかりません: %s" + }, + "Missing required argument: %s": { + "one": "必須の引数が見つかりません: %s", + "other": "必須の引数が見つかりません: %s" + }, + "Unknown argument: %s": { + "one": "未知の引数です: %s", + "other": "未知の引数です: %s" + }, + "Invalid values:": "不正な値です:", + "Argument: %s, Given: %s, Choices: %s": "引数は %s です。与えられた値: %s, 選択してください: %s", + "Argument check failed: %s": "引数のチェックに失敗しました: %s", + "Implications failed:": "オプションの組み合わせで不正が生じました:", + "Not enough arguments following: %s": "次の引数が不足しています。: %s", + "Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s", + "Path to JSON config file": "JSONの設定ファイルまでのpath", + "Show help": "ヘルプを表示", + "Show version number": "バージョンを表示", + "Did you mean %s?": "もしかして %s?", + "Arguments %s and %s are mutually exclusive" : "引数 %s と %s は同時に指定できません", + "Positionals:": "位置:", + "command": "コマンド", + "deprecated": "非推奨", + "deprecated: %s": "非推奨: %s" +} diff --git a/node_modules/yargs/locales/ko.json b/node_modules/yargs/locales/ko.json new file mode 100644 index 0000000..e3187ea --- /dev/null +++ b/node_modules/yargs/locales/ko.json @@ -0,0 +1,49 @@ +{ + "Commands:": "명령:", + "Options:": "옵션:", + "Examples:": "예시:", + "boolean": "여부", + "count": "개수", + "string": "문자열", + "number": "숫자", + "array": "배열", + "required": "필수", + "default": "기본", + "default:": "기본:", + "choices:": "선택:", + "aliases:": "별칭:", + "generated-value": "생성된 값", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "옵션이 아닌 인자가 충분치 않습니다: %s개를 받았지만, 적어도 %s개는 필요합니다", + "other": "옵션이 아닌 인자가 충분치 않습니다: %s개를 받았지만, 적어도 %s개는 필요합니다" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "옵션이 아닌 인자가 너무 많습니다: %s개를 받았지만, %s개 이하여야 합니다", + "other": "옵션이 아닌 인자가 너무 많습니다: %s개를 받았지만, %s개 이하여야 합니다" + }, + "Missing argument value: %s": { + "one": "인자값을 받지 못했습니다: %s", + "other": "인자값들을 받지 못했습니다: %s" + }, + "Missing required argument: %s": { + "one": "필수 인자를 받지 못했습니다: %s", + "other": "필수 인자들을 받지 못했습니다: %s" + }, + "Unknown argument: %s": { + "one": "알 수 없는 인자입니다: %s", + "other": "알 수 없는 인자들입니다: %s" + }, + "Invalid values:": "잘못된 값입니다:", + "Argument: %s, Given: %s, Choices: %s": "인자: %s, 입력받은 값: %s, 선택지: %s", + "Argument check failed: %s": "유효하지 않은 인자입니다: %s", + "Implications failed:": "옵션의 조합이 잘못되었습니다:", + "Not enough arguments following: %s": "인자가 충분하게 주어지지 않았습니다: %s", + "Invalid JSON config file: %s": "유효하지 않은 JSON 설정파일입니다: %s", + "Path to JSON config file": "JSON 설정파일 경로", + "Show help": "도움말을 보여줍니다", + "Show version number": "버전 넘버를 보여줍니다", + "Did you mean %s?": "찾고계신게 %s입니까?", + "Arguments %s and %s are mutually exclusive" : "%s와 %s 인자는 같이 사용될 수 없습니다", + "Positionals:": "위치:", + "command": "명령" +} diff --git a/node_modules/yargs/locales/nb.json b/node_modules/yargs/locales/nb.json new file mode 100644 index 0000000..6f410ed --- /dev/null +++ b/node_modules/yargs/locales/nb.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoer:", + "Options:": "Alternativer:", + "Examples:": "Eksempler:", + "boolean": "boolsk", + "count": "antall", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "valg:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s", + "other": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s", + "other": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Mangler argument verdi: %s", + "other": "Mangler argument verdier: %s" + }, + "Missing required argument: %s": { + "one": "Mangler obligatorisk argument: %s", + "other": "Mangler obligatoriske argumenter: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjente argumenter: %s" + }, + "Invalid values:": "Ugyldige verdier:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s", + "Argument check failed: %s": "Argumentsjekk mislyktes: %s", + "Implications failed:": "Konsekvensene mislyktes:", + "Not enough arguments following: %s": "Ikke nok følgende argumenter: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/nl.json b/node_modules/yargs/locales/nl.json new file mode 100644 index 0000000..9ff95c5 --- /dev/null +++ b/node_modules/yargs/locales/nl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Commando's:", + "Options:": "Opties:", + "Examples:": "Voorbeelden:", + "boolean": "booleaans", + "count": "aantal", + "string": "string", + "number": "getal", + "array": "lijst", + "required": "verplicht", + "default": "standaard", + "default:": "standaard:", + "choices:": "keuzes:", + "aliases:": "aliassen:", + "generated-value": "gegenereerde waarde", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig", + "other": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s", + "other": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s" + }, + "Missing argument value: %s": { + "one": "Missende argumentwaarde: %s", + "other": "Missende argumentwaarden: %s" + }, + "Missing required argument: %s": { + "one": "Missend verplicht argument: %s", + "other": "Missende verplichte argumenten: %s" + }, + "Unknown argument: %s": { + "one": "Onbekend argument: %s", + "other": "Onbekende argumenten: %s" + }, + "Invalid values:": "Ongeldige waarden:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s", + "Argument check failed: %s": "Argumentcontrole mislukt: %s", + "Implications failed:": "Ontbrekende afhankelijke argumenten:", + "Not enough arguments following: %s": "Niet genoeg argumenten na: %s", + "Invalid JSON config file: %s": "Ongeldig JSON-config-bestand: %s", + "Path to JSON config file": "Pad naar JSON-config-bestand", + "Show help": "Toon help", + "Show version number": "Toon versienummer", + "Did you mean %s?": "Bedoelde u misschien %s?", + "Arguments %s and %s are mutually exclusive": "Argumenten %s en %s kunnen niet tegelijk gebruikt worden", + "Positionals:": "Positie-afhankelijke argumenten", + "command": "commando" +} diff --git a/node_modules/yargs/locales/nn.json b/node_modules/yargs/locales/nn.json new file mode 100644 index 0000000..24479ac --- /dev/null +++ b/node_modules/yargs/locales/nn.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoar:", + "Options:": "Alternativ:", + "Examples:": "Døme:", + "boolean": "boolsk", + "count": "mengd", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "val:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s", + "other": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikkje-alternativ argument: fekk %s, maksimum %s", + "other": "For mange ikkje-alternativ argument: fekk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Manglar argumentverdi: %s", + "other": "Manglar argumentverdiar: %s" + }, + "Missing required argument: %s": { + "one": "Manglar obligatorisk argument: %s", + "other": "Manglar obligatoriske argument: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjende argument: %s" + }, + "Invalid values:": "Ugyldige verdiar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gjeve: %s, Val: %s", + "Argument check failed: %s": "Argumentsjekk mislukkast: %s", + "Implications failed:": "Konsekvensane mislukkast:", + "Not enough arguments following: %s": "Ikkje nok fylgjande argument: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/pirate.json b/node_modules/yargs/locales/pirate.json new file mode 100644 index 0000000..dcb5cb7 --- /dev/null +++ b/node_modules/yargs/locales/pirate.json @@ -0,0 +1,13 @@ +{ + "Commands:": "Choose yer command:", + "Options:": "Options for me hearties!", + "Examples:": "Ex. marks the spot:", + "required": "requi-yar-ed", + "Missing required argument: %s": { + "one": "Ye be havin' to set the followin' argument land lubber: %s", + "other": "Ye be havin' to set the followin' arguments land lubber: %s" + }, + "Show help": "Parlay this here code of conduct", + "Show version number": "'Tis the version ye be askin' fer", + "Arguments %s and %s are mutually exclusive" : "Yon scurvy dogs %s and %s be as bad as rum and a prudish wench" +} diff --git a/node_modules/yargs/locales/pl.json b/node_modules/yargs/locales/pl.json new file mode 100644 index 0000000..a41d4bd --- /dev/null +++ b/node_modules/yargs/locales/pl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Polecenia:", + "Options:": "Opcje:", + "Examples:": "Przykłady:", + "boolean": "boolean", + "count": "ilość", + "string": "ciąg znaków", + "number": "liczba", + "array": "tablica", + "required": "wymagany", + "default": "domyślny", + "default:": "domyślny:", + "choices:": "dostępne:", + "aliases:": "aliasy:", + "generated-value": "wygenerowana-wartość", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s", + "other": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s", + "other": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s" + }, + "Missing argument value: %s": { + "one": "Brak wartości dla argumentu: %s", + "other": "Brak wartości dla argumentów: %s" + }, + "Missing required argument: %s": { + "one": "Brak wymaganego argumentu: %s", + "other": "Brak wymaganych argumentów: %s" + }, + "Unknown argument: %s": { + "one": "Nieznany argument: %s", + "other": "Nieznane argumenty: %s" + }, + "Invalid values:": "Nieprawidłowe wartości:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Otrzymano: %s, Dostępne: %s", + "Argument check failed: %s": "Weryfikacja argumentów nie powiodła się: %s", + "Implications failed:": "Założenia nie zostały spełnione:", + "Not enough arguments following: %s": "Niewystarczająca ilość argumentów następujących po: %s", + "Invalid JSON config file: %s": "Nieprawidłowy plik konfiguracyjny JSON: %s", + "Path to JSON config file": "Ścieżka do pliku konfiguracyjnego JSON", + "Show help": "Pokaż pomoc", + "Show version number": "Pokaż numer wersji", + "Did you mean %s?": "Czy chodziło Ci o %s?", + "Arguments %s and %s are mutually exclusive": "Argumenty %s i %s wzajemnie się wykluczają", + "Positionals:": "Pozycyjne:", + "command": "polecenie" +} diff --git a/node_modules/yargs/locales/pt.json b/node_modules/yargs/locales/pt.json new file mode 100644 index 0000000..0c8ac99 --- /dev/null +++ b/node_modules/yargs/locales/pt.json @@ -0,0 +1,45 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "boolean", + "count": "contagem", + "string": "cadeia de caracteres", + "number": "número", + "array": "arranjo", + "required": "requerido", + "default": "padrão", + "default:": "padrão:", + "choices:": "escolhas:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos não opcionais: recebido %s, máximo de %s", + "other": "Excesso de argumentos não opcionais: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Escolhas: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Insuficientes argumentos a seguir: %s", + "Invalid JSON config file: %s": "Arquivo de configuração em JSON esta inválido: %s", + "Path to JSON config file": "Caminho para o arquivo de configuração em JSON", + "Show help": "Mostra ajuda", + "Show version number": "Mostra número de versão", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" +} diff --git a/node_modules/yargs/locales/pt_BR.json b/node_modules/yargs/locales/pt_BR.json new file mode 100644 index 0000000..eae1ec6 --- /dev/null +++ b/node_modules/yargs/locales/pt_BR.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "booleano", + "count": "contagem", + "string": "string", + "number": "número", + "array": "array", + "required": "obrigatório", + "default:": "padrão:", + "choices:": "opções:", + "aliases:": "sinônimos:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos: recebido %s, máximo de %s", + "other": "Excesso de argumentos: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Opções: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Argumentos insuficientes a seguir: %s", + "Invalid JSON config file: %s": "Arquivo JSON de configuração inválido: %s", + "Path to JSON config file": "Caminho para o arquivo JSON de configuração", + "Show help": "Exibe ajuda", + "Show version number": "Exibe a versão", + "Did you mean %s?": "Você quis dizer %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos", + "Positionals:": "Posicionais:", + "command": "comando" +} diff --git a/node_modules/yargs/locales/ru.json b/node_modules/yargs/locales/ru.json new file mode 100644 index 0000000..5f7f768 --- /dev/null +++ b/node_modules/yargs/locales/ru.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Команды:", + "Options:": "Опции:", + "Examples:": "Примеры:", + "boolean": "булевый тип", + "count": "подсчет", + "string": "строковой тип", + "number": "число", + "array": "массив", + "required": "необходимо", + "default": "по умолчанию", + "default:": "по умолчанию:", + "choices:": "возможности:", + "aliases:": "алиасы:", + "generated-value": "генерированное значение", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s", + "other": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s", + "other": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s" + }, + "Missing argument value: %s": { + "one": "Не хватает значения аргумента: %s", + "other": "Не хватает значений аргументов: %s" + }, + "Missing required argument: %s": { + "one": "Не хватает необходимого аргумента: %s", + "other": "Не хватает необходимых аргументов: %s" + }, + "Unknown argument: %s": { + "one": "Неизвестный аргумент: %s", + "other": "Неизвестные аргументы: %s" + }, + "Invalid values:": "Недействительные значения:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Данное значение: %s, Возможности: %s", + "Argument check failed: %s": "Проверка аргументов не удалась: %s", + "Implications failed:": "Данный аргумент требует следующий дополнительный аргумент:", + "Not enough arguments following: %s": "Недостаточно следующих аргументов: %s", + "Invalid JSON config file: %s": "Недействительный файл конфигурации JSON: %s", + "Path to JSON config file": "Путь к файлу конфигурации JSON", + "Show help": "Показать помощь", + "Show version number": "Показать номер версии", + "Did you mean %s?": "Вы имели в виду %s?" +} diff --git a/node_modules/yargs/locales/th.json b/node_modules/yargs/locales/th.json new file mode 100644 index 0000000..33b048e --- /dev/null +++ b/node_modules/yargs/locales/th.json @@ -0,0 +1,46 @@ +{ + "Commands:": "คอมมาน", + "Options:": "ออฟชั่น", + "Examples:": "ตัวอย่าง", + "boolean": "บูลีน", + "count": "นับ", + "string": "สตริง", + "number": "ตัวเลข", + "array": "อาเรย์", + "required": "จำเป็น", + "default": "ค่าเริ่มต้", + "default:": "ค่าเริ่มต้น", + "choices:": "ตัวเลือก", + "aliases:": "เอเลียส", + "generated-value": "ค่าที่ถูกสร้างขึ้น", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า", + "other": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า", + "other": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า" + }, + "Missing argument value: %s": { + "one": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s", + "other": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s" + }, + "Missing required argument: %s": { + "one": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s", + "other": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s" + }, + "Unknown argument: %s": { + "one": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s", + "other": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s" + }, + "Invalid values:": "ค่าไม่ถูกต้อง:", + "Argument: %s, Given: %s, Choices: %s": "อาร์กิวเมนต์: %s, ได้รับ: %s, ตัวเลือก: %s", + "Argument check failed: %s": "ตรวจสอบพบอาร์กิวเมนต์ที่ไม่ถูกต้อง: %s", + "Implications failed:": "Implications ไม่สำเร็จ:", + "Not enough arguments following: %s": "ใส่อาร์กิวเมนต์ไม่ครบ: %s", + "Invalid JSON config file: %s": "ไฟล์คอนฟิค JSON ไม่ถูกต้อง: %s", + "Path to JSON config file": "พาทไฟล์คอนฟิค JSON", + "Show help": "ขอความช่วยเหลือ", + "Show version number": "แสดงตัวเลขเวอร์ชั่น", + "Did you mean %s?": "คุณหมายถึง %s?" +} diff --git a/node_modules/yargs/locales/tr.json b/node_modules/yargs/locales/tr.json new file mode 100644 index 0000000..0d0d2cc --- /dev/null +++ b/node_modules/yargs/locales/tr.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Komutlar:", + "Options:": "Seçenekler:", + "Examples:": "Örnekler:", + "boolean": "boolean", + "count": "sayı", + "string": "string", + "number": "numara", + "array": "array", + "required": "zorunlu", + "default": "varsayılan", + "default:": "varsayılan:", + "choices:": "seçimler:", + "aliases:": "takma adlar:", + "generated-value": "oluşturulan-değer", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli", + "other": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s", + "other": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s" + }, + "Missing argument value: %s": { + "one": "Eksik argüman değeri: %s", + "other": "Eksik argüman değerleri: %s" + }, + "Missing required argument: %s": { + "one": "Eksik zorunlu argüman: %s", + "other": "Eksik zorunlu argümanlar: %s" + }, + "Unknown argument: %s": { + "one": "Bilinmeyen argüman: %s", + "other": "Bilinmeyen argümanlar: %s" + }, + "Invalid values:": "Geçersiz değerler:", + "Argument: %s, Given: %s, Choices: %s": "Argüman: %s, Verilen: %s, Seçimler: %s", + "Argument check failed: %s": "Argüman kontrolü başarısız oldu: %s", + "Implications failed:": "Sonuçlar başarısız oldu:", + "Not enough arguments following: %s": "%s için yeterli argüman bulunamadı", + "Invalid JSON config file: %s": "Geçersiz JSON yapılandırma dosyası: %s", + "Path to JSON config file": "JSON yapılandırma dosya konumu", + "Show help": "Yardım detaylarını göster", + "Show version number": "Versiyon detaylarını göster", + "Did you mean %s?": "Bunu mu demek istediniz: %s?", + "Positionals:": "Sıralılar:", + "command": "komut" +} diff --git a/node_modules/yargs/locales/zh_CN.json b/node_modules/yargs/locales/zh_CN.json new file mode 100644 index 0000000..257d26b --- /dev/null +++ b/node_modules/yargs/locales/zh_CN.json @@ -0,0 +1,48 @@ +{ + "Commands:": "命令:", + "Options:": "选项:", + "Examples:": "示例:", + "boolean": "布尔", + "count": "计数", + "string": "字符串", + "number": "数字", + "array": "数组", + "required": "必需", + "default": "默认值", + "default:": "默认值:", + "choices:": "可选值:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个", + "other": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个", + "other": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个" + }, + "Missing argument value: %s": { + "one": "没有给此选项指定值:%s", + "other": "没有给这些选项指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必须的选项:%s", + "other": "缺少这些必须的选项:%s" + }, + "Unknown argument: %s": { + "one": "无法识别的选项:%s", + "other": "无法识别这些选项:%s" + }, + "Invalid values:": "无效的选项值:", + "Argument: %s, Given: %s, Choices: %s": "选项名称: %s, 传入的值: %s, 可选的值:%s", + "Argument check failed: %s": "选项值验证失败:%s", + "Implications failed:": "缺少依赖的选项:", + "Not enough arguments following: %s": "没有提供足够的值给此选项:%s", + "Invalid JSON config file: %s": "无效的 JSON 配置文件:%s", + "Path to JSON config file": "JSON 配置文件的路径", + "Show help": "显示帮助信息", + "Show version number": "显示版本号", + "Did you mean %s?": "是指 %s?", + "Arguments %s and %s are mutually exclusive" : "选项 %s 和 %s 是互斥的", + "Positionals:": "位置:", + "command": "命令" +} diff --git a/node_modules/yargs/locales/zh_TW.json b/node_modules/yargs/locales/zh_TW.json new file mode 100644 index 0000000..e3c7bcf --- /dev/null +++ b/node_modules/yargs/locales/zh_TW.json @@ -0,0 +1,47 @@ +{ + "Commands:": "命令:", + "Options:": "選項:", + "Examples:": "例:", + "boolean": "布林", + "count": "次數", + "string": "字串", + "number": "數字", + "array": "陣列", + "required": "必須", + "default": "預設值", + "default:": "預設值:", + "choices:": "可選值:", + "aliases:": "別名:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個", + "other": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個", + "other": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個" + }, + "Missing argument value: %s": { + "one": "此引數無指定值:%s", + "other": "這些引數無指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必須的引數:%s", + "other": "缺少這些必須的引數:%s" + }, + "Unknown argument: %s": { + "one": "未知的引數:%s", + "other": "未知的這些引數:%s" + }, + "Invalid values:": "無效的選項值:", + "Argument: %s, Given: %s, Choices: %s": "引數名稱: %s, 傳入的值: %s, 可選的值:%s", + "Argument check failed: %s": "引數驗證失敗:%s", + "Implications failed:": "缺少依賴的選項:", + "Not enough arguments following: %s": "沒有提供足夠的值給此引數:%s", + "Invalid JSON config file: %s": "無效的 JSON 設置文件:%s", + "Path to JSON config file": "JSON 設置文件的路徑", + "Show help": "顯示說明", + "Show version number": "顯示版本", + "Did you mean %s?": "是指 %s?", + "Arguments %s and %s are mutually exclusive" : "引數 %s 和 %s 是互斥的" +} diff --git a/node_modules/yargs/package.json b/node_modules/yargs/package.json new file mode 100644 index 0000000..dc3018a --- /dev/null +++ b/node_modules/yargs/package.json @@ -0,0 +1,92 @@ +{ + "name": "yargs", + "version": "15.4.1", + "description": "yargs the modern, pirate-themed, successor to optimist.", + "main": "./index.js", + "contributors": [ + { + "name": "Yargs Contributors", + "url": "https://github.com/yargs/yargs/graphs/contributors" + } + ], + "files": [ + "index.js", + "yargs.js", + "build", + "locales", + "LICENSE" + ], + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "devDependencies": { + "@types/chai": "^4.2.11", + "@types/decamelize": "^1.2.0", + "@types/mocha": "^7.0.2", + "@types/node": "^10.0.3", + "@typescript-eslint/eslint-plugin": "^3.0.0", + "@typescript-eslint/parser": "^3.0.0", + "c8": "^7.0.0", + "chai": "^4.2.0", + "chalk": "^4.0.0", + "coveralls": "^3.0.9", + "cpr": "^3.0.1", + "cross-spawn": "^7.0.0", + "es6-promise": "^4.2.5", + "eslint": "^6.8.0", + "eslint-plugin-import": "^2.20.1", + "eslint-plugin-node": "^11.0.0", + "gts": "^2.0.0-alpha.4", + "hashish": "0.0.4", + "mocha": "^7.0.0", + "rimraf": "^3.0.2", + "standardx": "^5.0.0", + "typescript": "^3.7.0", + "which": "^2.0.0", + "yargs-test-extends": "^1.0.1" + }, + "scripts": { + "fix": "standardx --fix && standardx --fix **/*.ts", + "posttest": "npm run check", + "test": "c8 mocha --require ./test/before.js --timeout=12000 --check-leaks", + "coverage": "c8 report --check-coverage", + "check": "standardx && standardx **/*.ts", + "compile": "rimraf build && tsc", + "prepare": "npm run compile", + "pretest": "npm run compile -- -p tsconfig.test.json" + }, + "repository": { + "type": "git", + "url": "https://github.com/yargs/yargs.git" + }, + "homepage": "https://yargs.js.org/", + "standardx": { + "ignore": [ + "build", + "**/example/**" + ] + }, + "keywords": [ + "argument", + "args", + "option", + "parser", + "parsing", + "cli", + "command" + ], + "license": "MIT", + "engines": { + "node": ">=8" + } +} diff --git a/node_modules/yargs/yargs.js b/node_modules/yargs/yargs.js new file mode 100644 index 0000000..93e8059 --- /dev/null +++ b/node_modules/yargs/yargs.js @@ -0,0 +1,14 @@ +'use strict' + +// an async function fails early in Node.js versions prior to 8. +async function requiresNode8OrGreater () {} +requiresNode8OrGreater() + +const { Yargs, rebase } = require('./build/lib/yargs') +const Parser = require('yargs-parser') + +exports = module.exports = Yargs +exports.rebase = rebase + +// allow consumers to directly use the version of yargs-parser used by yargs +exports.Parser = Parser diff --git a/package.json b/package.json new file mode 100644 index 0000000..46d1618 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "name": "multipay", + "version": "1.0.0", + "private": true, + "type": "module", + "scripts": { + "dev": "bun --watch src/server.ts", + "start": "bun src/server.ts", + "test": "bun test" + }, + "dependencies": { + "pg": "^8.23.1", + "postgres": "^4.0.0", + "qrcode": "^1.5.4" + } +} diff --git a/public/admin.html b/public/admin.html new file mode 100644 index 0000000..cf150d6 --- /dev/null +++ b/public/admin.html @@ -0,0 +1,25 @@ + + + + + MultiPay 管理后台 + + + + + +
+ + + + diff --git a/public/admin.js b/public/admin.js new file mode 100644 index 0000000..24c4ad2 --- /dev/null +++ b/public/admin.js @@ -0,0 +1,45 @@ +const $ = (s) => document.querySelector(s); +const state = { view:'dashboard', admin:null, gateways:[] }; +const names={dashboard:['数据总览','支付概览'],orders:['交易管理','充值记录'],users:['账户管理','用户管理'],packages:['运营配置','充值套餐'],reconcile:['财务管理','对账明细'],gateways:['通道管理','支付网关'],settings:['系统管理','系统设置']}; +const fmtMoney=c=>`¥ ${(Number(c||0)/100).toLocaleString('zh-CN',{minimumFractionDigits:2})}`; +const fmtTime=s=>s?new Date(s).toLocaleString('zh-CN',{hour12:false}):'—'; +const chName=c=>({alipay:'支付宝',wechat:'微信支付',mock:'模拟支付'})[c]||c; +const statusName=s=>({pending:'待支付',paid:'已支付',failed:'失败',closed:'已关闭',refunded:'已退款',success:'成功',matched:'一致',mismatch:'差异',reviewed:'已复核',not_required:'无需回调'})[s]||s; +const catName=c=>({recharge:'充值',purchase:'购买',service:'服务',other:'其他'})[c]||c; +function esc(v=''){return String(v).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));} +async function api(path,options={}){const r=await fetch(path,{headers:{'content-type':'application/json',...(options.headers||{})},...options});let d={};try{d=await r.json()}catch{}if(!r.ok){if(r.status===401)showLogin();throw new Error(d.message||`请求失败 (${r.status})`)}return d;} +function toast(msg,type='ok'){const t=$('#toast');t.textContent=msg;t.className=`toast show ${type}`;setTimeout(()=>t.className='toast',2500);} +function showLogin(){$('#loginPage').classList.remove('hidden');$('#adminApp').classList.add('hidden');} +function showApp(admin){state.admin=admin;$('#adminName').textContent=admin.username;$('#loginPage').classList.add('hidden');$('#adminApp').classList.remove('hidden');navigate('dashboard');} +async function boot(){try{const d=await api('/api/admin/session');showApp(d.admin)}catch{showLogin()}} +$('#loginForm').onsubmit=async e=>{e.preventDefault();const b=e.submitter;b.disabled=true;$('#loginError').textContent='';try{const form=new FormData(e.target);const d=await api('/api/admin/login',{method:'POST',body:JSON.stringify(Object.fromEntries(form))});showApp(d.admin)}catch(err){$('#loginError').textContent=err.message}finally{b.disabled=false}}; +$('#logout').onclick=async()=>{await api('/api/admin/logout',{method:'POST'});showLogin()}; +$('#nav').onclick=e=>{const b=e.target.closest('[data-view]');if(b)navigate(b.dataset.view)}; +async function navigate(view){state.view=view;document.querySelectorAll('#nav button').forEach(b=>b.classList.toggle('active',b.dataset.view===view));[$('#pageEyebrow').textContent,$('#pageTitle').textContent]=names[view];$('#content').innerHTML='
加载中…
';try{await ({dashboard:renderDashboard,orders:renderOrders,users:renderUsers,packages:renderPackages,reconcile:renderReconcile,gateways:renderGateways,settings:renderSettings})[view]()}catch(err){$('#content').innerHTML=`
${esc(err.message)}
`}} +function statusPill(s){return `${statusName(s)}`} +function empty(cols,text='暂无数据'){return `
${text}
`} +async function renderDashboard(){const d=await api('/api/admin/dashboard');const s=d.stats||{};$('#content').innerHTML=`
今日实收金额${fmtMoney(s.paid_cents)}已完成 ${s.paid_orders||0} 笔支付
今日订单总数${s.total_orders||0}包含全部支付状态
待支付订单${s.pending_orders||0}等待用户扫码确认
支付成功率${s.total_orders?Math.round((s.paid_orders||0)/s.total_orders*100):0}%今日实时统计
最近活动

最新充值记录

${d.recent.length?d.recent.map(orderRow).join(''):empty(5)}
订单渠道金额状态时间
渠道概况

通道分布

${d.channels.length?d.channels.map(x=>`
${x.channel==='alipay'?'支':x.channel==='wechat'?'微':'M'}
${chName(x.channel)}${x.count} 笔订单
${fmtMoney(x.amount_cents)}
`).join(''):'
暂无渠道数据
'}
`} +function orderRow(o){return `${esc(o.merchant_order_no)}${esc(o.subject)}${chName(o.channel)}${fmtMoney(o.amount_cents)}${statusPill(o.status)}${fmtTime(o.created_at)}`} +function filterBar(kind){const isRec=kind==='reconcile';return `
${isRec?'':''}
`} +async function renderOrders(search=''){const d=await api(`/api/admin/orders?${search}`);$('#content').innerHTML=`${filterBar('orders')}
共 ${d.total} 条记录

充值订单

${d.rows.length?d.rows.map(o=>``).join(''):empty(10)}
业务订单用户分类渠道金额积分状态业务回调创建时间
${esc(o.merchant_order_no)}${esc(o.subject)}${esc(o.user_id||'—')}${catName(o.category)}${chName(o.channel)}${fmtMoney(o.amount_cents)}${o.points?`+${Number(o.points).toLocaleString('zh-CN')}`:'—'}${statusPill(o.status)}${o.refund_status&&o.refund_status!=='not_started'&&o.status!=='refunded'?`${esc({requesting:'退款请求中',processing:'渠道处理中',provider_success:'渠道已退款',business_failed:'积分回退失败',failed:'退款失败'}[o.refund_status]||o.refund_status)}`:''}${statusPill(o.callback_status)}${fmtTime(o.created_at)}
${o.status==='paid'&&o.notify_url?``:''}${o.status==='paid'?``:''}
`;wireFilters(renderOrders);document.querySelectorAll('[data-retry]').forEach(b=>b.onclick=async()=>{b.disabled=true;try{await api(`/api/admin/orders/${b.dataset.retry}/retry-callback`,{method:'POST'});toast('业务回调已重新发送');renderOrders(search)}catch(e){toast(e.message,'error')}});document.querySelectorAll('[data-refund]').forEach(b=>b.onclick=()=>openRefund(d.rows.find(o=>o.id===b.dataset.refund),search))} +function openRefund(order,search=''){ + const started=order.refund_status&&order.refund_status!=='not_started'; + const rollback=started?Boolean(order.refund_points_enabled):true; + const points=started?Number(order.refund_points||0):Number(order.points||0); + $('#modalContent').innerHTML=`原路全额退款

订单退费

退款金额${fmtMoney(order.amount_cents)}${esc(order.merchant_order_no)} · ${chName(order.channel)}

默认回退本次充值到账的积分,也可以手动填写。退款成功后将从 PostgreSQL users.quota 中扣减。

`; + const form=$('#refundForm'),toggle=form.querySelector('[name="rollback_points"]'),input=form.querySelector('[name="points"]'); + if(!started)toggle.onchange=()=>input.disabled=!toggle.checked; + form.onsubmit=async e=>{e.preventDefault();const shouldRollback=started?rollback:toggle.checked;const refundPoints=shouldRollback?Number(input.value):0;if(!Number.isSafeInteger(refundPoints)||refundPoints<0)return toast('回退积分必须是非负整数','error');if(!started&&!confirm(`确认原路退回 ${fmtMoney(order.amount_cents)}${shouldRollback?`,并回退 ${refundPoints} 积分`:''}?`))return;const button=e.submitter;button.disabled=true;try{const d=await api(`/api/admin/orders/${encodeURIComponent(order.id)}/refund`,{method:'POST',body:JSON.stringify({rollback_points:shouldRollback,points:refundPoints})});closeModal();toast(d.message);renderOrders(search)}catch(err){toast(err.message,'error');button.disabled=false}}; + openModal(); +} +function wireFilters(fn){$('#filters').onsubmit=e=>{e.preventDefault();fn(new URLSearchParams(new FormData(e.target)).toString())}} +async function renderUsers(search=''){const d=await api(`/api/admin/users?search=${encodeURIComponent(search)}`);$('#content').innerHTML=`

用户管理

数据来源:PostgreSQL users 表;支付确认后由服务端自动增加 quota 积分。

${d.rows.length?d.rows.map(u=>``).join(''):empty(7)}
用户 ID用户名可用积分累计已使用成功充值累计金额同步时间
${esc(u.id)}${esc(u.username||u.display_name)}${Number(u.quota||0).toLocaleString('zh-CN')}${Number(u.used_quota||0).toLocaleString('zh-CN')}${u.paid_orders||0} 笔${fmtMoney(u.paid_cents)}${fmtTime(u.updated_at)}
`;$('#userSearch').onsubmit=e=>{e.preventDefault();renderUsers(new FormData(e.target).get('search')||'')}} +function openUser(user={}){const isNew=!user.id;$('#modalContent').innerHTML=`${isNew?'新增':'编辑'}用户

用户资料

`;const form=$('#userForm');form.onsubmit=async e=>{e.preventDefault();const f=new FormData(form);const id=f.get('id');try{await api(`/api/admin/users/${encodeURIComponent(id)}`,{method:'PUT',body:JSON.stringify({...Object.fromEntries(f),enabled:f.has('enabled')})});closeModal();toast('用户已保存');renderUsers()}catch(err){toast(err.message,'error')}};openModal()} +async function renderPackages(){const d=await api('/api/admin/packages');$('#content').innerHTML=`

充值套餐

配置前台显示的充值金额、到账积分和展示顺序。

${d.rows.map(p=>`
${esc(p.name)}${fmtMoney(p.amount_cents)}

到账 ${Number(p.points).toLocaleString('zh-CN')} 积分

排序 ${p.sort_order} · ${p.enabled?'已启用':'已停用'}
`).join('')}
`;$('#addPackage').onclick=()=>openPackage();document.querySelectorAll('[data-package]').forEach(b=>b.onclick=()=>openPackage(d.rows.find(p=>String(p.id)===b.dataset.package)))} +function openPackage(pkg={}){const isNew=!pkg.id;$('#modalContent').innerHTML=`${isNew?'新增':'编辑'}充值套餐

套餐配置

`;const form=$('#packageForm');form.onsubmit=async e=>{e.preventDefault();const f=new FormData(form);try{await api(`/api/admin/packages/${pkg.id||'new'}`,{method:'PUT',body:JSON.stringify({...Object.fromEntries(f),enabled:f.has('enabled')})});closeModal();toast('充值套餐已保存');renderPackages()}catch(err){toast(err.message,'error')}};openModal()} +async function renderReconcile(search=''){const d=await api(`/api/admin/reconciliation?${search}`);$('#content').innerHTML=`${filterBar('reconcile')}
共 ${d.total} 条记录

资金对账结果

${d.rows.length?d.rows.map(r=>``).join(''):empty(8)}
业务订单渠道分类订单金额实付金额差额结果对账时间
${esc(r.merchant_order_no)}${esc(r.provider_trade_no||'—')}${chName(r.channel)}${catName(r.category)}${fmtMoney(r.expected_cents)}${fmtMoney(r.actual_cents)}${fmtMoney(r.difference_cents)}${statusPill(r.result)}${fmtTime(r.reconciled_at)}
`;wireFilters(renderReconcile)} +async function renderGateways(){const d=await api('/api/admin/gateways');state.gateways=d.rows;$('#content').innerHTML=`

支付网关

配置官方商户参数和运行模式。密钥加密后写入本地数据库。

${d.rows.map(g=>`
${g.channel==='alipay'?'支':g.channel==='wechat'?'微':'M'}

${esc(g.name)}

${chName(g.channel)} · ${g.subject_type==='company'?'企业主体':'个人/个体主体'}

${g.enabled?'已启用':'已停用'}
运行模式
${g.mode==='live'?'正式环境':g.mode==='sandbox'?'沙箱环境':'本地模拟'}
配置状态
${g.channel==='mock'?'无需凭据':Object.values(g.configuredSecrets||{}).some(Boolean)?'已保存密钥':'待配置'}
`).join('')}
关于个人主体

系统支持个人/个体与企业主体分类,但真实自动回调必须使用支付宝或微信官方审核通过的商户能力。普通个人收款码不提供可靠的服务端支付通知。

`;$('#addGateway').onclick=()=>openGateway();document.querySelectorAll('[data-edit]').forEach(b=>b.onclick=()=>openGateway(state.gateways.find(g=>g.id===b.dataset.edit)))} +function openGateway(g={}){const isNew=!g.id;const c=g.config||{};$('#modalContent').innerHTML=`${isNew?'新增':'编辑'}支付通道

网关配置

`;const form=$('#gatewayForm');form.channel.value=g.channel||'alipay';form.subject_type.value=g.subject_type||'company';form.mode.value=g.mode||'live';const renderFields=()=>{const ch=form.channel.value;let html='';if(ch==='alipay')html=``;else if(ch==='wechat')html=``;else html='
本地模拟模式

无需配置商户凭据,扫码后可在模拟页面确认支付,用于完整测试回调和对账流程。

';$('#channelFields').innerHTML=html};form.channel.onchange=renderFields;renderFields();form.onsubmit=async e=>{e.preventDefault();const fd=new FormData(form);const basic=['id','name','channel','subject_type','mode','enabled'];const obj=Object.fromEntries(fd);const config={};for(const [k,v] of fd)if(!basic.includes(k)&&String(v).trim())config[k]=v;const id=obj.id;try{await api(`/api/admin/gateways/${encodeURIComponent(id)}`,{method:'PUT',body:JSON.stringify({...obj,enabled:fd.has('enabled'),config})});closeModal();toast('网关配置已保存');renderGateways()}catch(err){toast(err.message,'error')}};openModal()} +async function renderSettings(){const s=await api('/api/admin/settings');$('#content').innerHTML=`
基础配置

系统与订单

业务接入

接口信息

轮换后,业务系统必须同步更新密钥。回调签名为 HMAC-SHA256(timestamp + "." + 原始 JSON)。

账户安全

修改管理员密码

`;$('#systemForm').onsubmit=async e=>{e.preventDefault();const f=new FormData(e.target);await api('/api/admin/settings',{method:'PUT',body:JSON.stringify({...Object.fromEntries(f),require_order_signature:f.has('require_order_signature')})});toast('系统设置已保存')};$('#toggleSecret').onclick=()=>{$('#secret').type=$('#secret').type==='password'?'text':'password'};$('#rotateSecret').onclick=async()=>{if(!confirm('确认轮换密钥?现有业务系统的签名配置会立即失效。'))return;await api('/api/admin/settings',{method:'PUT',body:JSON.stringify({...s,rotate_secret:true})});toast('密钥已轮换');renderSettings()};$('#passwordForm').onsubmit=async e=>{e.preventDefault();try{await api('/api/admin/password',{method:'PUT',body:JSON.stringify(Object.fromEntries(new FormData(e.target)))});e.target.reset();toast('管理员密码已更新')}catch(err){toast(err.message,'error')}}} +function openModal(){$('#modal').classList.remove('hidden')}function closeModal(){$('#modal').classList.add('hidden')}document.querySelectorAll('[data-close]').forEach(x=>x.onclick=closeModal); +boot(); diff --git a/public/app.css b/public/app.css new file mode 100644 index 0000000..24d2d1f --- /dev/null +++ b/public/app.css @@ -0,0 +1,27 @@ +@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=Noto+Sans+SC:wght@400;500;600;700&display=swap'); +:root{--ink:#13232c;--muted:#74828a;--line:#e5e9e7;--bg:#f4f6f3;--card:#fff;--green:#0d7b64;--green2:#16a17f;--nav:#122b30;--orange:#ed7b35;--red:#ce4a4a;--blue:#1677ff;--shadow:0 18px 50px rgba(22,45,49,.09)} +*{box-sizing:border-box}html,body{margin:0;min-height:100%;font-family:'DM Sans','Noto Sans SC',sans-serif;color:var(--ink);background:var(--bg)}button,input,select,textarea{font:inherit}button{cursor:pointer}.hidden{display:none!important}.brand{display:flex;align-items:center;gap:12px;color:var(--ink);font-weight:700;text-decoration:none}.brand-mark{display:grid;place-items:center;width:36px;height:36px;border-radius:11px;background:var(--nav);color:#fff;font-weight:800}.brand-mark.light{background:#dff6ec;color:var(--green)}.eyebrow{font-size:11px;font-weight:700;letter-spacing:.16em;text-transform:uppercase;color:var(--green)} +.checkout-body{min-height:100vh;background:radial-gradient(circle at 15% 5%,#e4f2eb 0,transparent 30%),var(--bg)}.checkout-header{height:78px;display:flex;align-items:center;justify-content:space-between;max-width:1180px;margin:auto;padding:0 28px}.secure-pill{font-size:13px;color:#52636a;display:flex;gap:8px;align-items:center}.secure-pill i,.live-status i{width:8px;height:8px;border-radius:50%;background:#25a67f;box-shadow:0 0 0 4px #dff3ec}.checkout-shell{max-width:1120px;margin:34px auto 70px;display:grid;grid-template-columns:39% 61%;min-height:600px;background:#fff;border-radius:24px;overflow:hidden;box-shadow:var(--shadow);border:1px solid rgba(220,226,223,.7)}.order-panel{padding:62px 52px;color:#fff;background:linear-gradient(145deg,#102d31,#17463f);position:relative;overflow:hidden}.order-panel:after{content:'';position:absolute;width:330px;height:330px;border:1px solid rgba(255,255,255,.08);border-radius:50%;right:-190px;bottom:-130px;box-shadow:0 0 0 55px rgba(255,255,255,.03),0 0 0 110px rgba(255,255,255,.02)}.order-panel .eyebrow{color:#89d8bd}.order-panel h1{font-size:29px;margin:14px 0 8px}.order-number{font-size:13px;color:#9db7b4}.order-number span{font-family:monospace;color:#d6e3e0}.amount-block{margin:52px 0 32px;padding-bottom:32px;border-bottom:1px solid rgba(255,255,255,.13);position:relative;z-index:1}.amount-block>span{display:block;font-size:13px;color:#a9bfbc}.amount-block strong{display:block;margin-top:8px;font-size:28px;font-weight:500}.amount-block em{font-size:55px;font-style:normal;letter-spacing:-.04em}.order-panel .field{color:#c7d7d4}.order-panel input{background:rgba(255,255,255,.08)!important;border-color:rgba(255,255,255,.18)!important;color:white!important}.money-input{position:relative}.money-input span{position:absolute;left:15px;top:14px}.money-input input{padding-left:38px!important}.benefits{position:absolute;bottom:52px;left:52px;right:52px;display:grid;gap:14px;color:#c3d4d1;font-size:13px}.benefits div{display:flex;align-items:center;gap:10px}.benefits b{display:grid;place-items:center;width:20px;height:20px;background:rgba(88,214,170,.14);border-radius:50%;color:#78d9b7}.pay-panel{padding:58px 64px;position:relative}.panel-heading{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:34px}.panel-heading>div{display:flex;align-items:center;gap:13px}.panel-heading h2{margin:0;font-size:22px}.panel-heading p{font-size:12px;color:var(--muted)}.step{font-size:11px;font-weight:700;color:#7f918f;border:1px solid var(--line);border-radius:8px;padding:5px 7px}.gateway-list{display:grid;gap:13px;margin-bottom:28px}.gateway-card{width:100%;padding:18px 20px;background:#fff;border:1px solid var(--line);border-radius:13px;display:flex;align-items:center;text-align:left;gap:15px;transition:.18s}.gateway-card:hover{border-color:#a9c6bc;transform:translateY(-1px)}.gateway-card.selected{border-color:var(--green);box-shadow:0 0 0 3px #e3f4ee}.gateway-card>i{margin-left:auto;width:18px;height:18px;border:1px solid #cbd5d1;border-radius:50%}.gateway-card.selected>i{border:5px solid var(--green)}.gateway-card b,.gateway-card small{display:block}.gateway-card b{font-size:15px}.gateway-card small{color:var(--muted);margin-top:4px}.gateway-icon{width:42px;height:42px;border-radius:12px;display:grid;place-items:center;font-weight:700}.channel-alipay .gateway-icon,.c-alipay{background:#e8f3ff!important;color:#1677ff!important}.channel-wechat .gateway-icon,.c-wechat{background:#e7f8ef!important;color:#07a75a!important}.channel-mock .gateway-icon,.c-mock{background:#eef1f0!important;color:#334d51!important}.primary-btn,.secondary-btn,.danger-button{border:0;border-radius:10px;padding:12px 18px;font-weight:600;transition:.18s;text-align:center;text-decoration:none;display:inline-block}.primary-btn{background:var(--green);color:#fff;box-shadow:0 6px 18px rgba(13,123,100,.2)}.primary-btn:hover{background:#096d58}.primary-btn:disabled{opacity:.55;cursor:not-allowed}.secondary-btn{background:#fff;border:1px solid var(--line);color:var(--ink)}.danger-button{background:#fff1f0;color:var(--red);border:1px solid #f2d6d3}.wide{width:100%}.agreement{text-align:center;font-size:11px;color:#98a3a7}.skeleton-card{height:80px;border-radius:12px;background:linear-gradient(90deg,#f2f4f3,#fafafa,#f2f4f3);background-size:200%;animation:shimmer 1.2s infinite}.countdown{font:600 13px monospace;color:var(--orange);background:#fff3ea;padding:7px 10px;border-radius:8px}.qr-layout{display:flex;align-items:center;gap:34px}.qr-frame{width:230px;height:230px;padding:12px;border:1px solid var(--line);border-radius:16px;position:relative;flex:none}.qr-frame img{width:100%;height:100%}.qr-copy h3{margin:16px 0 7px}.qr-copy p{font-size:13px;line-height:1.7;color:var(--muted)}.channel-badge{display:inline-block;padding:5px 9px;border-radius:7px;font-size:11px;font-weight:700}.channel-badge.channel-alipay{background:#e8f3ff;color:#1677ff}.channel-badge.channel-wechat{background:#e7f8ef;color:#07a75a}.channel-badge.channel-mock{background:#edf1ef;color:#3b5a58}.text-link{font-size:13px;color:var(--green);font-weight:600}.status-line{margin:30px 0 18px;padding:13px;background:#f3f8f5;border-radius:10px;text-align:center;color:#46645d;font-size:13px}.loader{display:inline-block;width:13px;height:13px;border:2px solid #bbd2ca;border-top-color:var(--green);border-radius:50%;animation:spin .8s linear infinite;vertical-align:-2px;margin-right:6px}.result-view{text-align:center;padding-top:60px}.result-icon{width:74px;height:74px;border-radius:50%;display:grid;place-items:center;margin:auto;background:#ddf5e9;color:var(--green);font-size:34px}.result-view h2{font-size:26px}.result-view p{color:var(--muted)}.result-meta{margin:30px 0;padding:20px;background:#f7f9f7;border-radius:12px;display:grid;grid-template-columns:1fr 1fr;text-align:left;gap:13px;font-size:13px}.result-meta span{color:var(--muted)}.result-meta b{text-align:right}.error-box{position:absolute;left:64px;right:64px;bottom:24px;background:#fff1f0;color:#ae3838;padding:11px 14px;border-radius:9px;font-size:13px;border:1px solid #f2d4d1}.checkout-footer{max-width:1120px;margin:-45px auto 30px;display:flex;justify-content:space-between;color:#899496;font-size:11px}.mock-body{display:grid;place-items:center;min-height:100vh;background:radial-gradient(circle at 30% 10%,#dff3e9,transparent 40%),#f4f6f3}.mock-card{width:min(440px,calc(100% - 32px));background:white;border-radius:22px;padding:42px;text-align:center;box-shadow:var(--shadow)}.mock-card .brand-mark{margin:auto}.mock-card h1{margin:20px 0 8px}.mock-card p,.mock-meta{color:var(--muted);font-size:13px}.mock-amount{font-size:42px;font-weight:700;margin:32px}.mock-meta{margin-bottom:28px}.success-banner{background:#e5f6ed;color:var(--green);padding:12px;border-radius:10px} +.admin-body{background:#f5f7f5}.login-page{display:grid;grid-template-columns:48% 52%;min-height:100vh}.login-aside{background:linear-gradient(150deg,#102e32,#17463d);padding:56px 70px;color:white;display:flex;flex-direction:column;justify-content:space-between;position:relative;overflow:hidden}.login-aside:after{content:'';position:absolute;width:500px;height:500px;border:1px solid rgba(255,255,255,.08);border-radius:50%;right:-240px;bottom:-220px;box-shadow:0 0 0 80px rgba(255,255,255,.025),0 0 0 160px rgba(255,255,255,.018)}.login-brand{display:flex;align-items:center;gap:12px;font-weight:700}.light-text{color:#89d8bd}.login-aside h1{font-size:52px;line-height:1.16;letter-spacing:-.04em;margin:18px 0}.login-aside p{color:#acc2be;line-height:1.8;max-width:470px}.login-foot{color:#799a94;font-size:12px}.login-card{width:410px;align-self:center;justify-self:center}.login-card h2{font-size:30px;margin:12px 0 6px}.login-card>p{color:var(--muted);margin-bottom:32px}.field{display:block;font-size:12px;font-weight:600;color:#4f5e63;margin-bottom:18px}.field input,.field select,.field textarea,.filter-bar input,.filter-bar select{display:block;width:100%;margin-top:8px;border:1px solid #dce2df;background:#fff;border-radius:9px;padding:12px 13px;color:var(--ink);outline:none}.field textarea{min-height:95px;resize:vertical;font-family:monospace;font-size:12px}.field input:focus,.field select:focus,.field textarea:focus{border-color:var(--green);box-shadow:0 0 0 3px #e1f3ed}.form-error{color:var(--red);font-size:12px;margin-top:12px}.admin-app{display:grid;grid-template-columns:238px 1fr;min-height:100vh}.sidebar{position:fixed;inset:0 auto 0 0;width:238px;background:var(--nav);padding:30px 18px 22px;color:white;display:flex;flex-direction:column}.sidebar-brand{display:flex;align-items:center;gap:12px;font-weight:700;padding:0 10px 28px;border-bottom:1px solid rgba(255,255,255,.08)}.sidebar-brand small{display:block;color:#75918d;font-size:10px;font-weight:500;margin-top:2px}.sidebar nav{display:grid;gap:6px;margin-top:26px}.sidebar nav button{border:0;background:transparent;color:#a9bfbb;padding:11px 13px;text-align:left;border-radius:9px;display:flex;align-items:center;gap:12px;font-size:13px}.sidebar nav button span{width:18px;text-align:center}.sidebar nav button:hover,.sidebar nav button.active{background:rgba(111,211,177,.12);color:#dff6ed}.sidebar nav button.active{box-shadow:inset 3px 0 #5ed0a7}.sidebar-bottom{margin-top:auto}.admin-user{display:flex;align-items:center;gap:10px;padding:13px 8px;border-top:1px solid rgba(255,255,255,.08)}.admin-user>span{width:31px;height:31px;border-radius:9px;display:grid;place-items:center;background:#dff6ec;color:var(--green);font-weight:700}.admin-user b,.admin-user small{display:block;font-size:12px}.admin-user small{color:#78928e;font-size:10px;margin-top:3px}.logout-btn{border:0;background:transparent;color:#819995;font-size:11px;margin-left:49px}.admin-main{grid-column:2;padding:0 40px 50px;min-width:0}.admin-top{height:112px;display:flex;align-items:center;justify-content:space-between}.admin-top p{font-size:11px;color:var(--green);font-weight:700;margin:0 0 6px;text-transform:uppercase;letter-spacing:.12em}.admin-top h1{font-size:25px;margin:0}.live-status{display:flex;align-items:center;gap:10px;background:#fff;border:1px solid var(--line);border-radius:9px;padding:9px 13px;font-size:11px;color:#536660}.metric-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.metric-card{background:white;border:1px solid var(--line);border-radius:14px;padding:22px}.metric-card>span,.metric-card small{display:block;color:var(--muted);font-size:11px}.metric-card strong{display:block;font-size:28px;margin:15px 0 8px;letter-spacing:-.03em}.metric-card.accent{background:linear-gradient(145deg,#103b3a,#176450);color:white;border:0}.metric-card.accent>span,.metric-card.accent small{color:#a6cec3}.dashboard-grid{display:grid;grid-template-columns:minmax(0,1fr) 300px;gap:16px;margin-top:18px}.panel{background:#fff;border:1px solid var(--line);border-radius:14px;padding:22px}.panel-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px}.panel-title span{font-size:10px;color:var(--green);font-weight:700;letter-spacing:.08em;text-transform:uppercase}.panel-title h2{font-size:17px;margin:5px 0 0}.text-button,.table-action{border:0;background:none;color:var(--green);font-size:11px}.table-wrap{overflow:auto;margin:0 -22px -22px}.table-wrap table{border-collapse:collapse;width:100%;font-size:12px}.table-wrap th{padding:11px 16px;text-align:left;background:#f7f9f7;color:#84908e;font-size:10px;font-weight:600;white-space:nowrap}.table-wrap td{padding:14px 16px;border-top:1px solid #edf0ee;white-space:nowrap}.table-wrap td b,.table-wrap td small{display:block}.table-wrap td small{color:var(--muted);margin-top:4px;font-size:10px}.money-cell{font-weight:700}.channel-text{font-weight:600;background:transparent!important}.status-pill{display:inline-flex;align-items:center;gap:6px;padding:4px 8px;border-radius:20px;background:#f0f2f1;color:#64706e;font-size:10px}.status-pill i{width:5px;height:5px;border-radius:50%;background:currentColor}.s-paid,.s-success,.s-matched{background:#e5f6ed;color:#18815e}.s-pending{background:#fff2e4;color:#b56b2c}.s-failed,.s-mismatch{background:#fff0ef;color:#bd4949}.channel-stat{display:grid;grid-template-columns:40px 1fr auto;align-items:center;gap:12px;padding:15px 0;border-bottom:1px solid var(--line)}.channel-stat:last-child{border:0}.mini-channel{width:38px;height:38px;display:grid;place-items:center;border-radius:10px;font-weight:700}.channel-stat b,.channel-stat small{display:block}.channel-stat b{font-size:12px}.channel-stat small{font-size:10px;color:var(--muted);margin-top:4px}.channel-stat strong{font-size:12px}.filter-bar{display:flex;gap:11px;align-items:flex-end;padding:15px;background:white;border:1px solid var(--line);border-radius:13px;margin-bottom:16px}.filter-bar label{font-size:10px;color:var(--muted);min-width:115px}.filter-bar input,.filter-bar select{margin-top:5px;padding:9px;font-size:11px}.filter-bar button{padding:9px 18px}.section-lead{display:flex;justify-content:space-between;align-items:center;margin-bottom:20px}.section-lead h2{margin:0 0 7px;font-size:20px}.section-lead p{margin:0;color:var(--muted);font-size:12px}.gateway-admin-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}.gateway-admin-card{background:white;border:1px solid var(--line);border-radius:14px;padding:20px}.gateway-admin-head{display:grid;grid-template-columns:46px 1fr auto;align-items:center;gap:12px}.large-channel{width:44px;height:44px;border-radius:12px;display:grid;place-items:center;font-weight:700}.gateway-admin-head h3{font-size:14px;margin:0 0 5px}.gateway-admin-head p{font-size:10px;color:var(--muted);margin:0}.switch-label{font-size:9px;color:var(--muted);display:flex;gap:5px;align-items:center}.switch-label i{width:6px;height:6px;background:#aab3b0;border-radius:50%}.switch-label.on{color:var(--green)}.switch-label.on i{background:var(--green)}.gateway-admin-card dl{margin:22px 0}.gateway-admin-card dl div{display:flex;justify-content:space-between;padding:9px 0;border-bottom:1px solid #f0f2f1;font-size:11px}.gateway-admin-card dt{color:var(--muted)}.gateway-admin-card dd{margin:0;font-weight:600}.notice-card{margin-top:18px;padding:16px 18px;border-radius:12px;background:#edf6f2;border:1px solid #d8eae3;font-size:12px}.notice-card p{margin:5px 0 0;color:#60766f;line-height:1.6}.settings-grid{display:grid;grid-template-columns:1fr 1fr;gap:16px;align-items:start}.settings-grid .panel:last-child{grid-column:1/-1}.settings-form>.primary-btn,.settings-form>.secondary-btn{margin-top:6px}.inline-fields{display:grid;grid-template-columns:1fr 1fr;gap:14px}.toggle-field{display:flex;align-items:center;gap:10px;font-size:12px;margin:18px 0}.toggle-field input{display:none}.toggle-field span{width:35px;height:20px;border-radius:20px;background:#cfd7d4;position:relative}.toggle-field span:after{content:'';position:absolute;width:14px;height:14px;border-radius:50%;background:#fff;top:3px;left:3px;transition:.2s}.toggle-field input:checked+span{background:var(--green)}.toggle-field input:checked+span:after{left:18px}.copy-line{display:flex}.copy-line input{border-radius:9px 0 0 9px}.copy-line button{margin-top:8px;border:1px solid #dce2df;border-left:0;background:#f7f9f8;border-radius:0 9px 9px 0;font-size:11px}.help-text{color:var(--muted);font-size:11px;line-height:1.6}.modal{position:fixed;inset:0;z-index:20;display:grid;place-items:center}.modal-backdrop{position:absolute;inset:0;background:rgba(12,31,34,.55);backdrop-filter:blur(4px)}.modal-card{position:relative;background:white;border-radius:18px;padding:30px;width:min(720px,calc(100% - 30px));max-height:90vh;overflow:auto;box-shadow:0 30px 80px rgba(0,0,0,.25)}.modal-card h2{margin:10px 0 24px}.modal-close{position:absolute;right:18px;top:15px;border:0;background:none;font-size:24px;color:#81908d}.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:0 16px}.form-grid .full,.form-grid>.wide,.channel-fields{grid-column:1/-1}.channel-fields{display:grid;grid-template-columns:1fr 1fr;gap:0 16px}.toast{position:fixed;right:25px;bottom:25px;background:#153f3a;color:white;border-radius:10px;padding:12px 18px;font-size:12px;transform:translateY(30px);opacity:0;transition:.2s;z-index:40}.toast.show{transform:none;opacity:1}.toast.error{background:#9c3939}.page-loader,.table-empty,.empty-state{text-align:center;color:var(--muted);padding:45px;font-size:12px}.error-panel{background:#fff0ef;color:var(--red);padding:20px;border-radius:12px}.danger-text{color:var(--red)} +@keyframes spin{to{transform:rotate(360deg)}}@keyframes shimmer{to{background-position:-200%}} +@media(max-width:980px){.checkout-shell{margin:15px;grid-template-columns:1fr}.order-panel{padding:38px}.benefits{position:static;margin-top:35px}.pay-panel{padding:38px}.admin-app{grid-template-columns:76px 1fr}.sidebar{width:76px}.sidebar-brand>div,.sidebar nav button:not(.active)::after,.sidebar nav button{font-size:0}.sidebar-brand{padding:0 2px 24px}.sidebar nav button{justify-content:center}.sidebar nav button span{font-size:18px}.sidebar-bottom{display:none}.admin-main{padding:0 20px 40px}.metric-grid{grid-template-columns:1fr 1fr}.dashboard-grid{grid-template-columns:1fr}.gateway-admin-grid{grid-template-columns:1fr 1fr}} +@media(max-width:680px){.checkout-header{height:65px;padding:0 18px}.secure-pill{font-size:0}.checkout-shell{margin:8px;border-radius:17px}.order-panel{padding:30px}.amount-block{margin:30px 0}.amount-block em{font-size:44px}.pay-panel{padding:30px 24px}.panel-heading p{display:none}.qr-layout{display:block}.qr-frame{margin:auto}.qr-copy{text-align:center}.checkout-footer{display:none}.login-page{display:block;background:white}.login-aside{min-height:270px;padding:30px}.login-aside h1{font-size:34px}.login-aside p,.login-foot{display:none}.login-card{width:auto;padding:36px 28px}.metric-grid,.gateway-admin-grid,.settings-grid{grid-template-columns:1fr}.settings-grid .panel:last-child{grid-column:auto}.filter-bar{overflow:auto;align-items:flex-end}.admin-top .live-status{display:none}.form-grid,.channel-fields{grid-template-columns:1fr}.inline-fields{grid-template-columns:1fr}.gateway-admin-head{grid-template-columns:46px 1fr}.gateway-admin-head .switch-label{display:none}} + +/* User-aware recharge checkout */ +.user-gate{max-width:520px;margin:120px auto;background:#fff;border:1px solid var(--line);border-radius:15px;padding:25px;text-align:center;color:var(--muted);box-shadow:var(--shadow)} +.invalid-user{max-width:520px;margin:85px auto;background:#fff;border:1px solid var(--line);border-radius:20px;padding:48px;text-align:center;box-shadow:var(--shadow)} +.invalid-icon{width:64px;height:64px;margin:auto;display:grid;place-items:center;border-radius:50%;background:#fff1f0;color:var(--red);font-size:30px;font-weight:700} +.invalid-user h1{margin:20px 0 10px}.invalid-user p{color:var(--muted);line-height:1.7}.invalid-user code{display:inline-block;margin-top:10px;padding:8px 12px;border-radius:8px;background:#f4f6f5;color:#60716e} +.checkout-shell{margin-bottom:18px} +.checkout-user-card{display:flex;align-items:center;gap:14px;margin:28px 0;padding:16px;border:1px solid rgba(255,255,255,.12);border-radius:13px;background:rgba(255,255,255,.06)} +.checkout-user-card>span{width:44px;height:44px;border-radius:12px;display:grid;place-items:center;background:#dff6ec;color:var(--green);font-size:18px;font-weight:700} +.checkout-user-card small,.checkout-user-card h2,.checkout-user-card p{display:block;margin:0}.checkout-user-card small{font-size:10px;color:#91afaa}.checkout-user-card h2{font-size:16px;margin:4px 0}.checkout-user-card p{font-size:10px;color:#9eb8b4} +.points-balance{padding-bottom:22px;border-bottom:1px solid rgba(255,255,255,.13)}.points-balance span{display:block;font-size:11px;color:#a9bfbc}.points-balance strong{font-size:30px;margin-right:4px}.points-balance small{font-size:9px;color:#71c7aa} +.amount-block.compact{margin:25px 0 18px;padding-bottom:20px}.amount-block.compact em{font-size:40px}.amount-block.compact p{font-size:11px;color:#a9bfbc;margin:7px 0 0}.compact-benefits{position:static!important;margin-top:28px} +.package-list{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin-bottom:16px}.package-card{border:1px solid var(--line);background:#fff;border-radius:12px;padding:14px 10px;text-align:left;transition:.18s}.package-card:hover{border-color:#a9c6bc}.package-card.selected{border-color:var(--green);background:#eff9f5;box-shadow:0 0 0 2px #dff2eb}.package-card span,.package-card strong,.package-card small{display:block}.package-card span{font-size:10px;color:var(--muted)}.package-card strong{font-size:22px;margin:8px 0 5px}.package-card small{font-size:9px;color:#788783}.package-card small b{color:var(--green)} +.gateway-heading{margin:26px 0 14px}.package-empty{grid-column:1/-1;padding:18px} +.history-panel{max-width:1120px;margin:18px auto 0;background:#fff;border:1px solid var(--line);border-radius:18px;padding:25px 28px;box-shadow:0 12px 34px rgba(22,45,49,.06)}.history-head{display:flex;align-items:flex-end;justify-content:space-between;margin-bottom:18px}.history-head h2{font-size:18px;margin:5px 0 0}.history-head>span{font-size:11px;color:var(--muted)}.history-table-wrap{overflow:auto}.history-table-wrap table{width:100%;border-collapse:collapse;font-size:12px}.history-table-wrap th{text-align:left;padding:10px;background:#f6f8f6;color:#7f8c89;font-size:10px}.history-table-wrap td{padding:13px 10px;border-bottom:1px solid #edf0ee}.history-table-wrap code{color:#53645f}.points-cell{color:var(--green);font-weight:700}.checkout-footer{margin:18px auto 30px} +@media(max-width:680px){.package-list{grid-template-columns:1fr 1fr}.history-panel{margin:12px 8px;padding:20px}.history-table-wrap{margin:0 -20px}.invalid-user{margin:45px 15px;padding:35px 22px}} +.package-admin-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}.package-admin-card{background:#fff;border:1px solid var(--line);border-radius:15px;padding:22px}.package-admin-card.disabled{opacity:.58}.package-admin-card>span,.package-admin-card>strong,.package-admin-card>p,.package-admin-card>small{display:block}.package-admin-card>span{font-size:11px;color:var(--muted)}.package-admin-card>strong{font-size:28px;margin:10px 0}.package-admin-card>p{font-size:12px}.package-admin-card>p b{color:var(--green)}.package-admin-card>small{color:var(--muted);font-size:10px;margin:14px 0}.package-admin-card .secondary-btn{margin-top:8px}@media(max-width:980px){.package-admin-grid{grid-template-columns:1fr 1fr}}@media(max-width:680px){.package-admin-grid{grid-template-columns:1fr}} +.row-actions{display:flex;align-items:center;gap:8px}.refund-action{color:var(--red)}.refund-summary{display:grid;gap:6px;padding:16px 18px;margin:-8px 0 20px;border-radius:12px;background:#f7f9f7}.refund-summary span,.refund-summary small{font-size:11px;color:var(--muted)}.refund-summary strong{font-size:24px}.danger-button.wide{width:100%} +.closed-page{min-height:100vh;display:grid;place-content:center;justify-items:center;gap:12px;text-align:center;background:#f5f8f6}.closed-page h2,.closed-page p{margin:0}.closed-page p{color:var(--muted)} diff --git a/public/checkout.html b/public/checkout.html new file mode 100644 index 0000000..614b591 --- /dev/null +++ b/public/checkout.html @@ -0,0 +1,53 @@ + + + + + + + 安全收银台 + + + +
+ M聚合支付中心 + 安全加密收银台 +
+
正在验证用户身份…
+ +
+
+
账户充值
+
U
当前用户

—

+
可用积分0 积分
+
本次充值金额¥ 0.00

预计获得 0 积分

+
订单号 正在生成…
+
✓支付成功后积分自动到账
✓重复通知不会重复增加积分
+
+
+
+
01

选择充值套餐

套餐金额与积分由系统统一配置

+
+
02

选择支付方式

+
+

点击即表示你确认用户、套餐和支付金额

+
+ + + +
+
+ +
支付过程受签名验证与金额校验保护如有疑问请联系商户
+ + + diff --git a/public/checkout.js b/public/checkout.js new file mode 100644 index 0000000..d131516 --- /dev/null +++ b/public/checkout.js @@ -0,0 +1,116 @@ +const $ = (selector) => document.querySelector(selector); +const query = new URLSearchParams(location.search); +const state = { user: null, packages: [], selectedPackage: null, selectedGateway: null, currentOrder: null }; +let pollTimer = null; +const userId = query.get('user_id') || ''; +const amountParam = query.get('amount') || ''; +const orderNo = query.get('merchant_order_no') || `PAY${Date.now().toString().slice(-10)}`; +const subject = query.get('subject') || '账户充值'; +$('#orderNoText').textContent = orderNo; + +function showError(message) { const box = $('#errorBox'); box.textContent = message; box.classList.remove('hidden'); setTimeout(() => box.classList.add('hidden'), 5000); } +function showInvalidUser(value) { $('#userGate').classList.add('hidden'); $('#checkoutMain').classList.add('hidden'); $('#historyPanel').classList.add('hidden'); $('#invalidUserView').classList.remove('hidden'); $('#invalidUserId').textContent = value ? `用户 ID:${value}` : '未传入 user_id'; } +function channelName(channel) { return ({ alipay: '支付宝', wechat: '微信支付', mock: '本地模拟' })[channel] || channel; } +function channelIcon(channel) { return channel === 'alipay' ? '支' : channel === 'wechat' ? '微' : 'M'; } +function formatTime(value) { return new Date(value).toLocaleString('zh-CN', { hour12: false }); } + +function syncAmount() { + const amount = state.selectedPackage ? (state.selectedPackage.amount_cents / 100).toFixed(2) : '0.00'; + const points = state.selectedPackage ? state.selectedPackage.points : 0; + $('#amountText').textContent = Number(amount || 0).toFixed(2); + $('#pointsText').textContent = Number(points).toLocaleString('zh-CN'); + $('#createOrder').disabled = !state.selectedGateway || Number(amount) <= 0; +} + +function renderPackages() { + const list = $('#packageList'); list.innerHTML = ''; + state.packages.forEach((item) => { + const button = document.createElement('button'); button.className = 'package-card'; + button.innerHTML = `${item.name}¥ ${(item.amount_cents / 100).toFixed(2)}赠送 ${Number(item.points).toLocaleString('zh-CN')} 积分`; + button.onclick = () => { document.querySelectorAll('.package-card').forEach((card) => card.classList.remove('selected')); button.classList.add('selected'); state.selectedPackage = item; syncAmount(); }; + list.append(button); + }); + if (!state.packages.length) list.innerHTML = '
暂无可用充值套餐,请联系管理员配置。
'; + const matched = amountParam && state.packages.find((item) => item.amount_cents === Math.round(Number(amountParam) * 100)); + if (matched) list.children[state.packages.indexOf(matched)]?.click(); else if (state.packages.length) list.children[0]?.click(); +} + +function renderHistory(history) { + $('#historyCount').textContent = `${history.length} 笔记录`; + $('#historyBody').innerHTML = history.length ? history.map((row) => `${formatTime(row.paid_at)}${row.merchant_order_no}${channelName(row.channel)}¥ ${(row.amount_cents / 100).toFixed(2)}+${Number(row.points || 0).toLocaleString('zh-CN')}`).join('') : '
近六个月暂无充值记录
'; +} + +async function loadGateways() { + const data = await fetch('/api/checkout/config').then((response) => response.json()); $('#brandName').textContent = data.siteName; + const list = $('#gatewayList'); list.innerHTML = ''; + data.gateways.forEach((gateway, index) => { + const button = document.createElement('button'); button.className = `gateway-card channel-${gateway.channel}`; + button.innerHTML = `${channelIcon(gateway.channel)}${gateway.name}${gateway.subject_type === 'company' ? '企业主体' : '个人/个体主体'} · ${channelName(gateway.channel)}`; + button.onclick = () => { document.querySelectorAll('.gateway-card').forEach((card) => card.classList.remove('selected')); button.classList.add('selected'); state.selectedGateway = gateway; syncAmount(); }; + list.append(button); if (index === 0) button.click(); + }); + if (!data.gateways.length) list.innerHTML = '
暂无可用支付通道,请联系管理员配置。
'; +} + +async function init() { + if (!userId) return showInvalidUser(''); + try { + const response = await fetch(`/api/checkout/users/${encodeURIComponent(userId)}`); const data = await response.json(); + if (!response.ok) return showInvalidUser(userId); + state.user = data.user; state.packages = data.packages; + $('#userName').textContent = data.user.username || data.user.displayName; $('#userAvatar').textContent = (data.user.username || data.user.displayName || data.user.id).slice(0, 1).toUpperCase(); $('#pointsBalance').textContent = Number(data.user.quota ?? 0).toLocaleString('zh-CN'); + renderPackages(); renderHistory(data.history); await loadGateways(); syncAmount(); + $('#userGate').classList.add('hidden'); $('#checkoutMain').classList.remove('hidden'); $('#historyPanel').classList.remove('hidden'); + } catch { showInvalidUser(userId); } +} + +$('#createOrder').onclick = async () => { + if (!state.selectedPackage) return showError('请选择充值套餐'); + const amount = (state.selectedPackage.amount_cents / 100).toFixed(2); + const button = $('#createOrder'); button.disabled = true; button.textContent = '正在创建订单…'; + try { + const payload = { amount, user_id: state.user.id, package_id: state.selectedPackage?.id || '', merchant_order_no: orderNo, subject, category: 'recharge', gateway_id: state.selectedGateway.id, notify_url: query.get('notify_url') || '', return_url: query.get('return_url') || '', timestamp: query.get('timestamp') || '', sign: query.get('sign') || '' }; + const response = await fetch('/api/checkout/orders', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload) }); const data = await response.json(); + if (!response.ok) throw new Error(data.message || '创建订单失败'); + state.currentOrder = data.order; $('#amountText').textContent = state.currentOrder.amount; $('#pointsText').textContent = Number(state.currentOrder.points || 0).toLocaleString('zh-CN'); renderQr(); + } catch (error) { showError(error.message); button.disabled = false; button.textContent = '确认充值'; } +}; + +function renderQr() { + $('#chooseView').classList.add('hidden'); $('#qrView').classList.remove('hidden'); $('#qrImage').src = `/api/checkout/orders/${encodeURIComponent(state.currentOrder.id)}/qrcode?t=${Date.now()}`; + const badge = $('#channelBadge'); badge.className = `channel-badge channel-${state.currentOrder.channel}`; badge.textContent = channelName(state.currentOrder.channel); + const link = $('#paymentLink'); + if (state.currentOrder.paymentUrl) { link.href = state.currentOrder.paymentUrl; link.textContent = '打开支付宝官方收银台 →'; link.classList.remove('hidden'); $('.qr-copy h3').textContent = '打开官方收银台扫码'; $('.qr-copy p').textContent = '请在电脑上打开支付宝官方收银台,页面会展示付款二维码;支付完成后此页面会自动更新。'; } + else if (state.currentOrder.channel === 'mock') { link.href = `/mock-pay/${encodeURIComponent(state.currentOrder.id)}`; link.textContent = '打开模拟支付页 →'; link.classList.remove('hidden'); } + const expires = new Date(state.currentOrder.expiresAt).getTime(); + const tick = () => { const left = Math.max(0, Math.floor((expires - Date.now()) / 1000)); $('#countdown').textContent = `${String(Math.floor(left / 60)).padStart(2, '0')}:${String(left % 60).padStart(2, '0')}`; if (left <= 0) { clearInterval(pollTimer); $('#statusLine').textContent = '二维码已过期,请重新发起充值'; } }; + tick(); setInterval(tick, 1000); pollTimer = setInterval(checkStatus, 2000); +} + +async function checkStatus() { + try { const data = await fetch(`/api/checkout/orders/${encodeURIComponent(state.currentOrder.id)}`).then((response) => response.json()); if (data.order?.status === 'paid') { clearInterval(pollTimer); showSuccess(data.order); } else if (['failed', 'closed'].includes(data.order?.status)) { clearInterval(pollTimer); showError('订单已关闭或支付失败'); } } catch { /* keep polling */ } +} + +async function refreshUserBalance() { + try { + const data = await fetch(`/api/checkout/users/${encodeURIComponent(state.user.id)}`).then((response) => response.json()); + if (data.user) { state.user = { ...state.user, ...data.user }; $('#pointsBalance').textContent = Number(data.user.quota ?? 0).toLocaleString('zh-CN'); } + } catch { /* 保留最后一次已加载的额度 */ } +} + +function showSuccess(order) { + $('#qrView').classList.add('hidden'); $('#successView').classList.remove('hidden'); $('#successMeta').innerHTML = `订单号${order.merchantOrderNo}充值金额¥ ${order.amount}获得积分+${Number(order.points || 0).toLocaleString('zh-CN')}`; + refreshUserBalance(); +} + +$('#backChoose').onclick = () => location.reload(); +$('#returnButton').onclick = (event) => { + event.preventDefault(); + window.close(); + setTimeout(() => { + if (!window.closed) { + document.body.innerHTML = '
✓

充值已完成

浏览器限制了自动关闭,请直接关闭此页面。

'; + } + }, 200); +}; +init(); diff --git a/scripts/export-alipay-app-public-key.ts b/scripts/export-alipay-app-public-key.ts new file mode 100644 index 0000000..7a1a7c2 --- /dev/null +++ b/scripts/export-alipay-app-public-key.ts @@ -0,0 +1,32 @@ +import { createHash, createPrivateKey, createPublicKey } from "node:crypto"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { db } from "../src/db"; +import { decryptJson } from "../src/security"; + +const gatewayId = process.argv[2] || "alipay"; +const row = db.query("SELECT config_encrypted FROM gateways WHERE id=? AND channel='alipay'").get(gatewayId) as { config_encrypted: string } | null; +if (!row) throw new Error(`找不到支付宝网关:${gatewayId}`); + +const config = decryptJson>(row.config_encrypted); +const raw = config.privateKey?.trim(); +if (!raw) throw new Error("网关没有配置应用私钥"); +const privatePem = raw.includes("-----BEGIN") + ? raw.replace(/\\n/g, "\n") + : `-----BEGIN PRIVATE KEY-----\n${raw.replace(/\s+/g, "").match(/.{1,64}/g)?.join("\n")}\n-----END PRIVATE KEY-----`; + +const privateKey = createPrivateKey(privatePem); +const publicPem = createPublicKey(privateKey).export({ type: "spki", format: "pem" }).toString(); +const publicText = publicPem.replace(/-----BEGIN PUBLIC KEY-----|-----END PUBLIC KEY-----|\s+/g, ""); +const fingerprint = createHash("sha256").update(Buffer.from(publicText, "base64")).digest("hex"); + +mkdirSync("data", { recursive: true }); +writeFileSync("data/alipay_app_public_key.pem", publicPem, "utf8"); +writeFileSync("data/alipay_app_public_key.txt", publicText, "utf8"); + +console.log(JSON.stringify({ + gatewayId, + appIdConfigured: Boolean(config.appId), + pemFile: "data/alipay_app_public_key.pem", + textFile: "data/alipay_app_public_key.txt", + sha256Fingerprint: fingerprint +}, null, 2)); diff --git a/scripts/inspect-gateways.ts b/scripts/inspect-gateways.ts new file mode 100644 index 0000000..3b260e6 --- /dev/null +++ b/scripts/inspect-gateways.ts @@ -0,0 +1,33 @@ +import { db } from "../src/db"; +import { decryptJson } from "../src/security"; + +const rows = db.query(` + SELECT id, name, channel, subject_type, mode, enabled, config_encrypted, updated_at + FROM gateways + ORDER BY channel, id +`).all() as Array>; + +const safe = rows.map((row) => { + const config = decryptJson>(row.config_encrypted || ""); + let notifyHost = ""; + try { notifyHost = config.notifyUrl ? new URL(config.notifyUrl).host : ""; } catch { notifyHost = "INVALID_URL"; } + return { + id: row.id, + name: row.name, + channel: row.channel, + subjectType: row.subject_type, + mode: row.mode, + enabled: Boolean(row.enabled), + updatedAt: row.updated_at, + configured: row.channel === "alipay" ? { + appId: Boolean(config.appId), + merchantPid: Boolean(config.merchantPid), + privateKey: Boolean(config.privateKey), + alipayPublicKey: Boolean(config.alipayPublicKey) + } : undefined, + notifyHost, + customGateway: Boolean(config.gatewayUrl) + }; +}); + +console.log(JSON.stringify(safe, null, 2)); diff --git a/scripts/set-alipay-product.ts b/scripts/set-alipay-product.ts new file mode 100644 index 0000000..c18141a --- /dev/null +++ b/scripts/set-alipay-product.ts @@ -0,0 +1,13 @@ +import { db } from "../src/db"; +import { decryptJson, encryptJson } from "../src/security"; + +const gatewayId = process.argv[2] || "alipay"; +const product = process.argv[3] || "page"; +if (!['page', 'precreate'].includes(product)) throw new Error("产品必须是 page 或 precreate"); +const row = db.query("SELECT config_encrypted FROM gateways WHERE id=? AND channel='alipay'").get(gatewayId) as { config_encrypted: string } | null; +if (!row) throw new Error(`找不到支付宝网关:${gatewayId}`); +const config = decryptJson>(row.config_encrypted || ""); +config.paymentProduct = product; +db.query("UPDATE gateways SET config_encrypted=?, updated_at=? WHERE id=?") + .run(encryptJson(config), new Date().toISOString(), gatewayId); +console.log(JSON.stringify({ gatewayId, paymentProduct: product, updated: true })); diff --git a/src/db.ts b/src/db.ts new file mode 100644 index 0000000..e754800 --- /dev/null +++ b/src/db.ts @@ -0,0 +1,228 @@ +import { Database } from "bun:sqlite"; +import { mkdirSync } from "node:fs"; +import { randomBytes } from "node:crypto"; + +mkdirSync("data", { recursive: true }); + +export const db = new Database("data/multipay.sqlite", { create: true }); +db.run("PRAGMA journal_mode = WAL"); +db.run("PRAGMA foreign_keys = ON"); +db.run("PRAGMA busy_timeout = 5000"); + +export async function initializeDatabase() { + db.exec(` + CREATE TABLE IF NOT EXISTS admins ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL UNIQUE, + password_hash TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + admin_id INTEGER NOT NULL REFERENCES admins(id) ON DELETE CASCADE, + expires_at TEXT NOT NULL, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS gateways ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + channel TEXT NOT NULL CHECK(channel IN ('alipay','wechat','mock')), + subject_type TEXT NOT NULL CHECK(subject_type IN ('individual','company')), + mode TEXT NOT NULL CHECK(mode IN ('mock','sandbox','live')), + enabled INTEGER NOT NULL DEFAULT 0, + config_encrypted TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + display_name TEXT NOT NULL, + points_balance INTEGER NOT NULL DEFAULT 0 CHECK(points_balance >= 0), + enabled INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS recharge_packages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + amount_cents INTEGER NOT NULL CHECK(amount_cents > 0), + points INTEGER NOT NULL CHECK(points >= 0), + enabled INTEGER NOT NULL DEFAULT 1, + sort_order INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS orders ( + id TEXT PRIMARY KEY, + merchant_order_no TEXT NOT NULL UNIQUE, + amount_cents INTEGER NOT NULL CHECK(amount_cents > 0), + subject TEXT NOT NULL, + category TEXT NOT NULL DEFAULT 'recharge', + channel TEXT NOT NULL CHECK(channel IN ('alipay','wechat','mock')), + gateway_id TEXT NOT NULL REFERENCES gateways(id), + status TEXT NOT NULL CHECK(status IN ('pending','paid','closed','failed','refunded')), + qr_content TEXT, + provider_trade_no TEXT, + notify_url TEXT, + return_url TEXT, + client_ip TEXT, + provider_payload TEXT, + callback_status TEXT NOT NULL DEFAULT 'not_started', + callback_attempts INTEGER NOT NULL DEFAULT 0, + callback_response TEXT, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + paid_at TEXT, + updated_at TEXT NOT NULL + ); + + CREATE INDEX IF NOT EXISTS idx_orders_created_at ON orders(created_at DESC); + CREATE INDEX IF NOT EXISTS idx_orders_filters ON orders(channel, status, category, created_at DESC); + + CREATE TABLE IF NOT EXISTS callback_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + order_id TEXT NOT NULL REFERENCES orders(id) ON DELETE CASCADE, + target_url TEXT NOT NULL, + request_body TEXT NOT NULL, + response_status INTEGER, + response_body TEXT, + success INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS reconciliation ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + order_id TEXT NOT NULL UNIQUE REFERENCES orders(id) ON DELETE CASCADE, + channel TEXT NOT NULL, + category TEXT NOT NULL, + expected_cents INTEGER NOT NULL, + actual_cents INTEGER NOT NULL, + difference_cents INTEGER NOT NULL, + result TEXT NOT NULL CHECK(result IN ('matched','mismatch','pending','reviewed')), + provider_trade_no TEXT, + reconciled_at TEXT NOT NULL, + note TEXT NOT NULL DEFAULT '' + ); + + CREATE INDEX IF NOT EXISTS idx_reconciliation_filters + ON reconciliation(channel, result, category, reconciled_at DESC); + + CREATE TABLE IF NOT EXISTS audit_logs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + admin_id INTEGER, + action TEXT NOT NULL, + detail TEXT NOT NULL, + ip TEXT, + created_at TEXT NOT NULL + ); + `); + + const orderColumns = new Set( + (db.query("PRAGMA table_info(orders)").all() as Array<{ name: string }>).map((column) => column.name) + ); + if (!orderColumns.has("user_id")) db.run("ALTER TABLE orders ADD COLUMN user_id TEXT"); + if (!orderColumns.has("package_id")) db.run("ALTER TABLE orders ADD COLUMN package_id INTEGER"); + if (!orderColumns.has("points")) db.run("ALTER TABLE orders ADD COLUMN points INTEGER NOT NULL DEFAULT 0"); + if (!orderColumns.has("points_credited")) db.run("ALTER TABLE orders ADD COLUMN points_credited INTEGER NOT NULL DEFAULT 0"); + if (!orderColumns.has("payment_confirmed")) db.run("ALTER TABLE orders ADD COLUMN payment_confirmed INTEGER NOT NULL DEFAULT 0"); + if (!orderColumns.has("business_status")) db.run("ALTER TABLE orders ADD COLUMN business_status TEXT NOT NULL DEFAULT 'pending'"); + if (!orderColumns.has("business_attempts")) db.run("ALTER TABLE orders ADD COLUMN business_attempts INTEGER NOT NULL DEFAULT 0"); + if (!orderColumns.has("business_error")) db.run("ALTER TABLE orders ADD COLUMN business_error TEXT"); + if (!orderColumns.has("business_completed_at")) db.run("ALTER TABLE orders ADD COLUMN business_completed_at TEXT"); + if (!orderColumns.has("refund_status")) db.run("ALTER TABLE orders ADD COLUMN refund_status TEXT NOT NULL DEFAULT 'not_started'"); + if (!orderColumns.has("refund_request_no")) db.run("ALTER TABLE orders ADD COLUMN refund_request_no TEXT"); + if (!orderColumns.has("provider_refund_no")) db.run("ALTER TABLE orders ADD COLUMN provider_refund_no TEXT"); + if (!orderColumns.has("refund_points_enabled")) db.run("ALTER TABLE orders ADD COLUMN refund_points_enabled INTEGER NOT NULL DEFAULT 0"); + if (!orderColumns.has("refund_points")) db.run("ALTER TABLE orders ADD COLUMN refund_points INTEGER NOT NULL DEFAULT 0"); + if (!orderColumns.has("refund_error")) db.run("ALTER TABLE orders ADD COLUMN refund_error TEXT"); + if (!orderColumns.has("refund_payload")) db.run("ALTER TABLE orders ADD COLUMN refund_payload TEXT"); + if (!orderColumns.has("refund_requested_at")) db.run("ALTER TABLE orders ADD COLUMN refund_requested_at TEXT"); + if (!orderColumns.has("refunded_at")) db.run("ALTER TABLE orders ADD COLUMN refunded_at TEXT"); + db.run(`UPDATE orders SET payment_confirmed=1, business_status='success', + business_completed_at=COALESCE(business_completed_at, paid_at) + WHERE status='paid' AND payment_confirmed=0`); + db.exec(` + CREATE INDEX IF NOT EXISTS idx_orders_user_history ON orders(user_id, status, paid_at DESC); + CREATE INDEX IF NOT EXISTS idx_packages_enabled ON recharge_packages(enabled, sort_order, amount_cents); + + CREATE TABLE IF NOT EXISTS external_user_links ( + local_user_id TEXT PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + external_user_id TEXT NOT NULL UNIQUE, + external_username TEXT NOT NULL DEFAULT '', + last_synced_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS external_user_snapshots ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + external_user_id TEXT NOT NULL, + username TEXT NOT NULL, + quota INTEGER NOT NULL, + used_quota INTEGER NOT NULL, + synced_at TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_external_user_snapshots_user_time + ON external_user_snapshots(external_user_id, synced_at DESC); + `); + + const now = new Date().toISOString(); + const admin = db.query("SELECT id FROM admins LIMIT 1").get(); + if (!admin) { + const username = process.env.ADMIN_USERNAME || "admin"; + const password = process.env.ADMIN_PASSWORD || "admin123456"; + const passwordHash = await Bun.password.hash(password, { algorithm: "argon2id" }); + db.query("INSERT INTO admins (username, password_hash, created_at, updated_at) VALUES (?, ?, ?, ?)") + .run(username, passwordHash, now, now); + } + + const defaults: Record = { + site_name: "聚合支付中心", + merchant_secret: randomBytes(24).toString("hex"), + require_order_signature: "false", + order_expire_minutes: "15", + callback_max_attempts: "5" + }; + const insertSetting = db.query("INSERT OR IGNORE INTO settings (key, value, updated_at) VALUES (?, ?, ?)"); + for (const [key, value] of Object.entries(defaults)) insertSetting.run(key, value, now); + + const packageCount = (db.query("SELECT COUNT(*) count FROM recharge_packages").get() as { count: number }).count; + if (packageCount === 0) { + const insertPackage = db.query(`INSERT INTO recharge_packages + (name, amount_cents, points, enabled, sort_order, created_at, updated_at) + VALUES (?, ?, ?, 1, ?, ?, ?)`); + insertPackage.run("轻享充值", 1000, 100, 10, now, now); + insertPackage.run("超值充值", 5000, 520, 20, now, now); + insertPackage.run("尊享充值", 10000, 1100, 30, now, now); + } + + const mockExists = db.query("SELECT id FROM gateways WHERE id = 'mock-default'").get(); + if (!mockExists) { + db.query(`INSERT INTO gateways + (id, name, channel, subject_type, mode, enabled, config_encrypted, created_at, updated_at) + VALUES ('mock-default', '本地模拟支付', 'mock', 'individual', 'mock', 1, '', ?, ?)`) + .run(now, now); + } +} + +export function getSetting(key: string, fallback = ""): string { + const row = db.query("SELECT value FROM settings WHERE key = ?").get(key) as { value: string } | null; + return row?.value ?? fallback; +} + +export function setSetting(key: string, value: string) { + const now = new Date().toISOString(); + db.query(`INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`) + .run(key, value, now); +} diff --git a/src/external-db.ts b/src/external-db.ts new file mode 100644 index 0000000..446e351 --- /dev/null +++ b/src/external-db.ts @@ -0,0 +1,203 @@ +import pg from "pg"; + +const pool = new pg.Pool({ + host: process.env.EXTERNAL_POSTGRES_HOST || "localhost", + port: Number(process.env.EXTERNAL_POSTGRES_PORT || 5432), + database: process.env.EXTERNAL_POSTGRES_DATABASE || "new-api", + user: process.env.EXTERNAL_POSTGRES_USER || "root", + password: process.env.EXTERNAL_POSTGRES_PASSWORD || "123456", + ssl: false, + connectionTimeoutMillis: 3000, + idleTimeoutMillis: 20_000, + max: 5 +}); + +export type ExternalUser = { + id: string; + username: string; + quota: number; + usedQuota: number; +}; + +export type ExternalQuotaCredit = { + userId: string; + points: number; + orderId: string; + providerTradeNo: string; +}; + +export type ExternalQuotaCreditResult = { + credited: boolean; + quota: number; +}; + +export type ExternalQuotaRefund = { + userId: string; + points: number; + orderId: string; + providerRefundNo: string; +}; + +let creditTableReady: Promise | null = null; +let refundTableReady: Promise | null = null; + +function ensureCreditTable() { + creditTableReady ||= pool.query(` + CREATE TABLE IF NOT EXISTS multipay_recharge_credits ( + order_id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + quota_delta BIGINT NOT NULL CHECK (quota_delta >= 0), + provider_trade_no TEXT NOT NULL, + credited_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + `).catch((error) => { + creditTableReady = null; + throw error; + }); + return creditTableReady; +} + +function ensureRefundTable() { + refundTableReady ||= pool.query(` + CREATE TABLE IF NOT EXISTS multipay_refund_debits ( + order_id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + quota_delta BIGINT NOT NULL CHECK (quota_delta >= 0), + provider_refund_no TEXT NOT NULL, + debited_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + `).catch((error) => { + refundTableReady = null; + throw error; + }); + return refundTableReady; +} + +function toNumber(value: unknown) { + const number = Number(value ?? 0); + return Number.isFinite(number) ? number : 0; +} + +export async function getExternalUser(userId: string | number): Promise { + const result = await pool.query<{ id: string; username: string; quota: unknown; used_quota: unknown }>( + `SELECT id::text AS id, username, quota, used_quota + FROM users WHERE id::text = $1 LIMIT 1`, + [String(userId)] + ); + const row = result.rows[0]; + if (!row) return null; + return { id: row.id, username: row.username, quota: toNumber(row.quota), usedQuota: toNumber(row.used_quota) }; +} + +export async function searchExternalUsers(search = ""): Promise { + const keyword = String(search || "").trim(); + const result = keyword === "" + ? await pool.query<{ id: string; username: string; quota: unknown; used_quota: unknown }>( + "SELECT id::text AS id, username, quota, used_quota FROM users ORDER BY id LIMIT 100") + : await pool.query<{ id: string; username: string; quota: unknown; used_quota: unknown }>( + `SELECT id::text AS id, username, quota, used_quota FROM users + WHERE id::text ILIKE $1 OR username ILIKE $1 ORDER BY id LIMIT 100`, + [`%${keyword}%`]); + return result.rows.map((row) => ({ + id: row.id, + username: row.username, + quota: toNumber(row.quota), + usedQuota: toNumber(row.used_quota) + })); +} + +export async function creditExternalUserQuota(input: ExternalQuotaCredit): Promise { + if (!Number.isSafeInteger(input.points) || input.points < 0) throw new Error("充值积分必须是非负整数"); + if (!input.orderId || !input.providerTradeNo) throw new Error("业务入账缺少支付订单标识"); + await ensureCreditTable(); + const client = await pool.connect(); + try { + await client.query("BEGIN"); + const inserted = await client.query<{ + user_id: string; + quota_delta: unknown; + provider_trade_no: string; + }>(`INSERT INTO multipay_recharge_credits + (order_id, user_id, quota_delta, provider_trade_no) + VALUES ($1, $2, $3::bigint, $4) + ON CONFLICT (order_id) DO NOTHING + RETURNING user_id, quota_delta, provider_trade_no`, + [input.orderId, input.userId, input.points, input.providerTradeNo]); + + if (!inserted.rowCount) { + const existing = await client.query<{ + user_id: string; + quota_delta: unknown; + provider_trade_no: string; + }>(`SELECT user_id, quota_delta, provider_trade_no + FROM multipay_recharge_credits WHERE order_id = $1`, [input.orderId]); + const credit = existing.rows[0]; + if (!credit + || credit.user_id !== input.userId + || toNumber(credit.quota_delta) !== input.points + || credit.provider_trade_no !== input.providerTradeNo) { + throw new Error("订单已存在不一致的业务入账记录"); + } + const user = await client.query<{ quota: unknown }>( + "SELECT quota FROM users WHERE id::text = $1 LIMIT 1", [input.userId]); + if (!user.rows[0]) throw new Error("业务用户不存在"); + await client.query("COMMIT"); + return { credited: false, quota: toNumber(user.rows[0].quota) }; + } + + const updated = await client.query<{ quota: unknown }>( + `UPDATE users SET quota = COALESCE(quota, 0) + $2::bigint + WHERE id::text = $1 RETURNING quota`, [input.userId, input.points]); + if (!updated.rows[0]) throw new Error("业务用户不存在,积分未入账"); + await client.query("COMMIT"); + return { credited: true, quota: toNumber(updated.rows[0].quota) }; + } catch (error) { + await client.query("ROLLBACK").catch(() => {}); + throw error; + } finally { + client.release(); + } +} + +export async function refundExternalUserQuota(input: ExternalQuotaRefund): Promise { + if (!Number.isSafeInteger(input.points) || input.points < 0) throw new Error("回退积分必须是非负整数"); + if (!input.orderId || !input.providerRefundNo) throw new Error("积分回退缺少退款标识"); + await ensureRefundTable(); + const client = await pool.connect(); + try { + await client.query("BEGIN"); + const inserted = await client.query<{ user_id: string; quota_delta: unknown; provider_refund_no: string }>( + `INSERT INTO multipay_refund_debits (order_id, user_id, quota_delta, provider_refund_no) + VALUES ($1, $2, $3::bigint, $4) ON CONFLICT (order_id) DO NOTHING + RETURNING user_id, quota_delta, provider_refund_no`, + [input.orderId, input.userId, input.points, input.providerRefundNo]); + if (!inserted.rowCount) { + const existing = await client.query<{ user_id: string; quota_delta: unknown; provider_refund_no: string }>( + `SELECT user_id, quota_delta, provider_refund_no FROM multipay_refund_debits WHERE order_id=$1`, [input.orderId]); + const debit = existing.rows[0]; + if (!debit || debit.user_id !== input.userId || toNumber(debit.quota_delta) !== input.points + || debit.provider_refund_no !== input.providerRefundNo) { + throw new Error("订单已存在不一致的积分回退记录"); + } + const user = await client.query<{ quota: unknown }>("SELECT quota FROM users WHERE id::text=$1 LIMIT 1", [input.userId]); + if (!user.rows[0]) throw new Error("业务用户不存在"); + await client.query("COMMIT"); + return { credited: false, quota: toNumber(user.rows[0].quota) }; + } + const updated = await client.query<{ quota: unknown }>( + `UPDATE users SET quota=COALESCE(quota,0)-$2::bigint WHERE id::text=$1 RETURNING quota`, + [input.userId, input.points]); + if (!updated.rows[0]) throw new Error("业务用户不存在,积分未回退"); + await client.query("COMMIT"); + return { credited: true, quota: toNumber(updated.rows[0].quota) }; + } catch (error) { + await client.query("ROLLBACK").catch(() => {}); + throw error; + } finally { + client.release(); + } +} + +export async function closeExternalDatabase() { + await pool.end(); +} diff --git a/src/payments.ts b/src/payments.ts new file mode 100644 index 0000000..0f84a09 --- /dev/null +++ b/src/payments.ts @@ -0,0 +1,486 @@ +import { createDecipheriv, createSign, createVerify, randomBytes } from "node:crypto"; + +export type GatewayChannel = "alipay" | "wechat" | "mock"; + +export interface GatewayRecord { + id: string; + name: string; + channel: GatewayChannel; + subject_type: "individual" | "company"; + mode: "mock" | "sandbox" | "live"; + enabled: number; + config: Record; +} + +export interface PaymentOrderInput { + id: string; + merchantOrderNo: string; + amountCents: number; + subject: string; + expiresAt: string; + returnUrl?: string; +} + +export interface ProviderPaymentResult { + qrContent: string; + providerPayload: unknown; +} + +export interface ProviderCallbackResult { + merchantOrderNo: string; + providerTradeNo: string; + amountCents: number; + paidAt: string; + raw: unknown; +} + +export interface ProviderRefundResult { + status: "success" | "processing"; + providerRefundNo: string; + raw: unknown; +} + +export interface ProviderRefundOrder { + merchantOrderNo: string; + amountCents: number; +} + +function required(config: Record, keys: string[]) { + const missing = keys.filter((key) => !config[key]?.trim()); + if (missing.length) throw new Error(`网关缺少配置:${missing.join("、")}`); +} + +function normalizePem(value: string, label: "PRIVATE KEY" | "PUBLIC KEY"): string { + const clean = value.trim(); + if (clean.includes("-----BEGIN")) return clean.replace(/\\n/g, "\n"); + const body = clean.replace(/\s+/g, "").match(/.{1,64}/g)?.join("\n") || clean; + return `-----BEGIN ${label}-----\n${body}\n-----END ${label}-----`; +} + +function alipayTimestamp(): string { + const parts = new Intl.DateTimeFormat("zh-CN", { + timeZone: "Asia/Shanghai", year: "numeric", month: "2-digit", day: "2-digit", + hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" + }).formatToParts(new Date()); + const get = (type: string) => parts.find((item) => item.type === type)?.value || ""; + return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")}:${get("second")}`; +} + +function canonicalAlipay(params: Record): string { + return Object.keys(params).filter((key) => key !== "sign" && params[key] !== "") + .sort().map((key) => `${key}=${params[key]}`).join("&"); +} + +function alipaySign(params: Record, privateKey: string): string { + const signer = createSign("RSA-SHA256"); + signer.update(canonicalAlipay(params), "utf8"); + signer.end(); + return signer.sign(normalizePem(privateKey, "PRIVATE KEY"), "base64"); +} + +function alipayVerify(content: string, signature: string, publicKey: string): boolean { + const verifier = createVerify("RSA-SHA256"); + verifier.update(content, "utf8"); + verifier.end(); + return verifier.verify(normalizePem(publicKey, "PUBLIC KEY"), signature, "base64"); +} + +function extractJsonObject(raw: string, field: string): string | null { + const marker = `"${field}"`; + const at = raw.indexOf(marker); + if (at < 0) return null; + let start = raw.indexOf("{", at + marker.length); + if (start < 0) return null; + let depth = 0; + let inString = false; + let escaped = false; + for (let i = start; i < raw.length; i++) { + const char = raw[i]; + if (inString) { + if (escaped) escaped = false; + else if (char === "\\") escaped = true; + else if (char === '"') inString = false; + continue; + } + if (char === '"') inString = true; + else if (char === "{") depth++; + else if (char === "}" && --depth === 0) return raw.slice(start, i + 1); + } + return null; +} + +async function createAlipayPayment(gateway: GatewayRecord, order: PaymentOrderInput, baseUrl: string): Promise { + const config = gateway.config; + required(config, ["appId", "privateKey", "alipayPublicKey"]); + const gatewayUrl = config.gatewayUrl || (gateway.mode === "sandbox" + ? "https://openapi-sandbox.dl.alipaydev.com/gateway.do" + : "https://openapi.alipay.com/gateway.do"); + const notifyUrl = config.notifyUrl || `${baseUrl}/api/callbacks/alipay`; + if (config.paymentProduct === "page") { + const returnUrl = order.returnUrl || `${baseUrl}/pay?merchant_order_no=${encodeURIComponent(order.merchantOrderNo)}&payment_return=1`; + const pageParams: Record = { + app_id: config.appId, + method: "alipay.trade.page.pay", + format: "JSON", + charset: "utf-8", + sign_type: "RSA2", + timestamp: alipayTimestamp(), + version: "1.0", + notify_url: notifyUrl, + return_url: returnUrl, + biz_content: JSON.stringify({ + out_trade_no: order.merchantOrderNo, + product_code: "FAST_INSTANT_TRADE_PAY", + total_amount: (order.amountCents / 100).toFixed(2), + subject: order.subject, + timeout_express: "15m", + qr_pay_mode: "0" + }) + }; + pageParams.sign = alipaySign(pageParams, config.privateKey); + const paymentUrl = `${gatewayUrl}?${new URLSearchParams(pageParams).toString()}`; + return { + qrContent: paymentUrl, + providerPayload: { flow: "redirect", payment_product: "page", redirect_url: paymentUrl } + }; + } + const params: Record = { + app_id: config.appId, + method: "alipay.trade.precreate", + format: "JSON", + charset: "utf-8", + sign_type: "RSA2", + timestamp: alipayTimestamp(), + version: "1.0", + notify_url: notifyUrl, + biz_content: JSON.stringify({ + out_trade_no: order.merchantOrderNo, + total_amount: (order.amountCents / 100).toFixed(2), + subject: order.subject, + timeout_express: "15m" + }) + }; + params.sign = alipaySign(params, config.privateKey); + const response = await fetch(gatewayUrl, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded;charset=utf-8" }, + body: new URLSearchParams(params), + signal: AbortSignal.timeout(12_000) + }); + const raw = await response.text(); + if (!response.ok) throw new Error(`支付宝网关 HTTP ${response.status}`); + const payload = JSON.parse(raw); + const result = payload.alipay_trade_precreate_response; + if (!result || result.code !== "10000" || !result.qr_code) { + const code = [result?.code, result?.sub_code].filter(Boolean).join("/"); + const message = result?.sub_msg || result?.msg || "支付宝预下单失败"; + throw new Error(`支付宝预下单失败${code ? ` [${code}]` : ""}:${message}`); + } + const signedContent = extractJsonObject(raw, "alipay_trade_precreate_response"); + if (!payload.sign || !signedContent || !alipayVerify(signedContent, payload.sign, config.alipayPublicKey)) { + throw new Error("支付宝响应验签失败"); + } + return { qrContent: result.qr_code, providerPayload: payload }; +} + +async function queryAlipayPayment(gateway: GatewayRecord, merchantOrderNo: string): Promise { + const config = gateway.config; + required(config, ["appId", "privateKey", "alipayPublicKey"]); + const gatewayUrl = config.gatewayUrl || (gateway.mode === "sandbox" + ? "https://openapi-sandbox.dl.alipaydev.com/gateway.do" + : "https://openapi.alipay.com/gateway.do"); + const params: Record = { + app_id: config.appId, + method: "alipay.trade.query", + format: "JSON", + charset: "utf-8", + sign_type: "RSA2", + timestamp: alipayTimestamp(), + version: "1.0", + biz_content: JSON.stringify({ out_trade_no: merchantOrderNo }) + }; + params.sign = alipaySign(params, config.privateKey); + const response = await fetch(gatewayUrl, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded;charset=utf-8" }, + body: new URLSearchParams(params), + signal: AbortSignal.timeout(12_000) + }); + const raw = await response.text(); + if (!response.ok) throw new Error(`支付宝查单 HTTP ${response.status}`); + const payload = JSON.parse(raw); + const result = payload.alipay_trade_query_response; + const signedContent = extractJsonObject(raw, "alipay_trade_query_response"); + if (!payload.sign || !signedContent || !alipayVerify(signedContent, payload.sign, config.alipayPublicKey)) { + throw new Error("支付宝查单响应验签失败"); + } + if (result?.code !== "10000") { + if (result?.sub_code === "ACQ.TRADE_NOT_EXIST") return null; + throw new Error(result?.sub_msg || result?.msg || "支付宝查单失败"); + } + if (!['TRADE_SUCCESS', 'TRADE_FINISHED'].includes(result.trade_status)) return null; + return { + merchantOrderNo: result.out_trade_no, + providerTradeNo: result.trade_no, + amountCents: Math.round(Number(result.total_amount) * 100), + paidAt: result.send_pay_date + ? new Date(`${result.send_pay_date.replace(" ", "T")}+08:00`).toISOString() + : new Date().toISOString(), + raw: result + }; +} + +function verifyWechatSignature(headers: Headers, body: string, publicKey: string): boolean { + const timestamp = headers.get("wechatpay-timestamp") || ""; + const nonce = headers.get("wechatpay-nonce") || ""; + const signature = headers.get("wechatpay-signature") || ""; + if (!timestamp || !nonce || !signature) return false; + if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false; + const verifier = createVerify("RSA-SHA256"); + verifier.update(`${timestamp}\n${nonce}\n${body}\n`, "utf8"); + verifier.end(); + return verifier.verify(normalizePem(publicKey, "PUBLIC KEY"), signature, "base64"); +} + +async function createWechatPayment(gateway: GatewayRecord, order: PaymentOrderInput, baseUrl: string): Promise { + const config = gateway.config; + required(config, ["appId", "mchId", "merchantSerialNo", "merchantPrivateKey", "wechatPublicKey"]); + const path = "/v3/pay/transactions/native"; + const body = JSON.stringify({ + appid: config.appId, + mchid: config.mchId, + description: order.subject.slice(0, 127), + out_trade_no: order.merchantOrderNo, + time_expire: order.expiresAt, + notify_url: config.notifyUrl || `${baseUrl}/api/callbacks/wechat`, + amount: { total: order.amountCents, currency: "CNY" } + }); + const timestamp = Math.floor(Date.now() / 1000).toString(); + const nonce = randomBytes(16).toString("hex"); + const message = `POST\n${path}\n${timestamp}\n${nonce}\n${body}\n`; + const signer = createSign("RSA-SHA256"); + signer.update(message, "utf8"); + signer.end(); + const signature = signer.sign(normalizePem(config.merchantPrivateKey, "PRIVATE KEY"), "base64"); + const token = `mchid="${config.mchId}",nonce_str="${nonce}",timestamp="${timestamp}",serial_no="${config.merchantSerialNo}",signature="${signature}"`; + const response = await fetch(`https://api.mch.weixin.qq.com${path}`, { + method: "POST", + headers: { + accept: "application/json", + "content-type": "application/json", + authorization: `WECHATPAY2-SHA256-RSA2048 ${token}` + }, + body, + signal: AbortSignal.timeout(12_000) + }); + const raw = await response.text(); + if (!verifyWechatSignature(response.headers, raw, config.wechatPublicKey)) { + throw new Error("微信支付响应验签失败"); + } + const payload = JSON.parse(raw || "{}"); + if (!response.ok || !payload.code_url) throw new Error(payload.message || `微信支付网关 HTTP ${response.status}`); + return { qrContent: payload.code_url, providerPayload: payload }; +} + +async function queryWechatPayment(gateway: GatewayRecord, merchantOrderNo: string): Promise { + const config = gateway.config; + required(config, ["mchId", "merchantSerialNo", "merchantPrivateKey", "wechatPublicKey"]); + const path = `/v3/pay/transactions/out-trade-no/${encodeURIComponent(merchantOrderNo)}?mchid=${encodeURIComponent(config.mchId)}`; + const timestamp = Math.floor(Date.now() / 1000).toString(); + const nonce = randomBytes(16).toString("hex"); + const signer = createSign("RSA-SHA256"); + signer.update(`GET\n${path}\n${timestamp}\n${nonce}\n\n`, "utf8"); + signer.end(); + const signature = signer.sign(normalizePem(config.merchantPrivateKey, "PRIVATE KEY"), "base64"); + const token = `mchid="${config.mchId}",nonce_str="${nonce}",timestamp="${timestamp}",serial_no="${config.merchantSerialNo}",signature="${signature}"`; + const response = await fetch(`https://api.mch.weixin.qq.com${path}`, { + headers: { accept: "application/json", authorization: `WECHATPAY2-SHA256-RSA2048 ${token}` }, + signal: AbortSignal.timeout(12_000) + }); + const raw = await response.text(); + if (!verifyWechatSignature(response.headers, raw, config.wechatPublicKey)) { + throw new Error("微信支付查单响应验签失败"); + } + const payload = JSON.parse(raw || "{}"); + if (!response.ok) { + if (response.status === 404 || payload.code === "ORDER_NOT_EXIST") return null; + throw new Error(payload.message || `微信支付查单 HTTP ${response.status}`); + } + if (payload.trade_state !== "SUCCESS") return null; + return { + merchantOrderNo: payload.out_trade_no, + providerTradeNo: payload.transaction_id, + amountCents: Number(payload.amount?.total), + paidAt: payload.success_time ? new Date(payload.success_time).toISOString() : new Date().toISOString(), + raw: payload + }; +} + +async function createAlipayRefund(gateway: GatewayRecord, order: ProviderRefundOrder, refundRequestNo: string): Promise { + const config = gateway.config; + required(config, ["appId", "privateKey", "alipayPublicKey"]); + const gatewayUrl = config.gatewayUrl || (gateway.mode === "sandbox" + ? "https://openapi-sandbox.dl.alipaydev.com/gateway.do" : "https://openapi.alipay.com/gateway.do"); + const params: Record = { + app_id: config.appId, + method: "alipay.trade.refund", + format: "JSON", + charset: "utf-8", + sign_type: "RSA2", + timestamp: alipayTimestamp(), + version: "1.0", + biz_content: JSON.stringify({ + out_trade_no: order.merchantOrderNo, + refund_amount: (order.amountCents / 100).toFixed(2), + out_request_no: refundRequestNo, + refund_reason: "管理员发起充值退款" + }) + }; + params.sign = alipaySign(params, config.privateKey); + const response = await fetch(gatewayUrl, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded;charset=utf-8" }, + body: new URLSearchParams(params), + signal: AbortSignal.timeout(12_000) + }); + const raw = await response.text(); + if (!response.ok) throw new Error(`支付宝退款 HTTP ${response.status}`); + const payload = JSON.parse(raw); + const result = payload.alipay_trade_refund_response; + const signedContent = extractJsonObject(raw, "alipay_trade_refund_response"); + if (!payload.sign || !signedContent || !alipayVerify(signedContent, payload.sign, config.alipayPublicKey)) { + throw new Error("支付宝退款响应验签失败"); + } + if (!result || result.code !== "10000") throw new Error(result?.sub_msg || result?.msg || "支付宝退款失败"); + return { status: "success", providerRefundNo: result.trade_no || refundRequestNo, raw: result }; +} + +async function wechatRefundRequest(gateway: GatewayRecord, method: "GET" | "POST", path: string, body = "") { + const config = gateway.config; + required(config, ["mchId", "merchantSerialNo", "merchantPrivateKey", "wechatPublicKey"]); + const timestamp = Math.floor(Date.now() / 1000).toString(); + const nonce = randomBytes(16).toString("hex"); + const signer = createSign("RSA-SHA256"); + signer.update(`${method}\n${path}\n${timestamp}\n${nonce}\n${body}\n`, "utf8"); + signer.end(); + const signature = signer.sign(normalizePem(config.merchantPrivateKey, "PRIVATE KEY"), "base64"); + const token = `mchid="${config.mchId}",nonce_str="${nonce}",timestamp="${timestamp}",serial_no="${config.merchantSerialNo}",signature="${signature}"`; + const response = await fetch(`https://api.mch.weixin.qq.com${path}`, { + method, + headers: { accept: "application/json", authorization: `WECHATPAY2-SHA256-RSA2048 ${token}`, + ...(body ? { "content-type": "application/json" } : {}) }, + body: body || undefined, + signal: AbortSignal.timeout(12_000) + }); + const raw = await response.text(); + if (!verifyWechatSignature(response.headers, raw, config.wechatPublicKey)) throw new Error("微信退款响应验签失败"); + const payload = JSON.parse(raw || "{}"); + if (!response.ok) throw new Error(payload.message || `微信退款 HTTP ${response.status}`); + return payload; +} + +function normalizeWechatRefund(payload: Record, refundRequestNo: string): ProviderRefundResult { + if (payload.status === "SUCCESS") return { + status: "success", providerRefundNo: payload.refund_id || refundRequestNo, raw: payload + }; + if (["PROCESSING", "ABNORMAL"].includes(payload.status)) return { + status: "processing", providerRefundNo: payload.refund_id || refundRequestNo, raw: payload + }; + throw new Error(`微信退款状态异常:${payload.status || "UNKNOWN"}`); +} + +async function createWechatRefund(gateway: GatewayRecord, order: ProviderRefundOrder, refundRequestNo: string): Promise { + const body = JSON.stringify({ + out_trade_no: order.merchantOrderNo, + out_refund_no: refundRequestNo, + reason: "管理员发起充值退款", + amount: { refund: order.amountCents, total: order.amountCents, currency: "CNY" } + }); + const payload = await wechatRefundRequest(gateway, "POST", "/v3/refund/domestic/refunds", body); + return normalizeWechatRefund(payload, refundRequestNo); +} + +async function queryWechatRefund(gateway: GatewayRecord, refundRequestNo: string): Promise { + const payload = await wechatRefundRequest(gateway, "GET", `/v3/refund/domestic/refunds/${encodeURIComponent(refundRequestNo)}`); + return normalizeWechatRefund(payload, refundRequestNo); +} + +export async function createProviderPayment(gateway: GatewayRecord, order: PaymentOrderInput, baseUrl: string): Promise { + if (gateway.channel === "mock" || gateway.mode === "mock") { + return { qrContent: `${baseUrl}/mock-pay/${encodeURIComponent(order.id)}`, providerPayload: { mode: "mock" } }; + } + if (gateway.channel === "alipay") return createAlipayPayment(gateway, order, baseUrl); + return createWechatPayment(gateway, order, baseUrl); +} + +export async function queryProviderPayment(gateway: GatewayRecord, merchantOrderNo: string): Promise { + if (gateway.channel === "alipay" && gateway.mode !== "mock") { + return queryAlipayPayment(gateway, merchantOrderNo); + } + if (gateway.channel === "wechat" && gateway.mode !== "mock") { + return queryWechatPayment(gateway, merchantOrderNo); + } + return null; +} + +export async function createProviderRefund(gateway: GatewayRecord, order: ProviderRefundOrder, refundRequestNo: string): Promise { + if (gateway.channel === "mock" || gateway.mode === "mock") { + return { status: "success", providerRefundNo: `mock_${refundRequestNo}`, raw: { mode: "mock", refunded: true } }; + } + if (gateway.channel === "alipay") return createAlipayRefund(gateway, order, refundRequestNo); + return createWechatRefund(gateway, order, refundRequestNo); +} + +export async function queryProviderRefund(gateway: GatewayRecord, order: ProviderRefundOrder, refundRequestNo: string): Promise { + if (gateway.channel === "mock" || gateway.mode === "mock") { + return { status: "success", providerRefundNo: `mock_${refundRequestNo}`, raw: { mode: "mock", refunded: true } }; + } + if (gateway.channel === "alipay") return createAlipayRefund(gateway, order, refundRequestNo); + return queryWechatRefund(gateway, refundRequestNo); +} + +export function parseAlipayCallback(body: URLSearchParams, gateway: GatewayRecord): ProviderCallbackResult { + const config = gateway.config; + required(config, ["appId", "alipayPublicKey"]); + const params: Record = {}; + body.forEach((value, key) => { params[key] = value; }); + const signature = params.sign || ""; + if (!signature || !alipayVerify(canonicalAlipay(params), signature, config.alipayPublicKey)) { + throw new Error("支付宝通知验签失败"); + } + if (params.app_id !== config.appId) throw new Error("支付宝 app_id 不匹配"); + if (config.merchantPid && params.seller_id !== config.merchantPid) throw new Error("支付宝 seller_id 不匹配"); + if (!['TRADE_SUCCESS', 'TRADE_FINISHED'].includes(params.trade_status)) throw new Error("支付宝交易尚未成功"); + return { + merchantOrderNo: params.out_trade_no, + providerTradeNo: params.trade_no, + amountCents: Math.round(Number(params.total_amount) * 100), + paidAt: params.gmt_payment ? new Date(`${params.gmt_payment.replace(" ", "T")}+08:00`).toISOString() : new Date().toISOString(), + raw: params + }; +} + +export function parseWechatCallback(raw: string, headers: Headers, gateway: GatewayRecord): ProviderCallbackResult { + const config = gateway.config; + required(config, ["wechatPublicKey", "apiV3Key"]); + if (!verifyWechatSignature(headers, raw, config.wechatPublicKey)) throw new Error("微信支付通知验签失败"); + const envelope = JSON.parse(raw); + const resource = envelope.resource; + if (!resource?.ciphertext || !resource?.nonce) throw new Error("微信支付通知格式错误"); + const key = Buffer.from(config.apiV3Key, "utf8"); + if (key.length !== 32) throw new Error("微信 APIv3 密钥必须为 32 字节"); + const encrypted = Buffer.from(resource.ciphertext, "base64"); + const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(resource.nonce, "utf8")); + decipher.setAuthTag(encrypted.subarray(encrypted.length - 16)); + if (resource.associated_data) decipher.setAAD(Buffer.from(resource.associated_data, "utf8")); + const plain = Buffer.concat([decipher.update(encrypted.subarray(0, -16)), decipher.final()]).toString("utf8"); + const data = JSON.parse(plain); + if (data.trade_state !== "SUCCESS") throw new Error("微信支付交易尚未成功"); + return { + merchantOrderNo: data.out_trade_no, + providerTradeNo: data.transaction_id, + amountCents: Number(data.amount?.total), + paidAt: data.success_time ? new Date(data.success_time).toISOString() : new Date().toISOString(), + raw: data + }; +} diff --git a/src/security.ts b/src/security.ts new file mode 100644 index 0000000..aecb10d --- /dev/null +++ b/src/security.ts @@ -0,0 +1,51 @@ +import { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; + +function loadMasterKey(): Buffer { + const envKey = process.env.PAY_MASTER_KEY?.trim(); + if (envKey) { + const key = /^[0-9a-f]{64}$/i.test(envKey) ? Buffer.from(envKey, "hex") : Buffer.from(envKey, "base64"); + if (key.length !== 32) throw new Error("PAY_MASTER_KEY 必须是 32 字节(64 位十六进制或 Base64)"); + return key; + } + mkdirSync("data", { recursive: true }); + const keyPath = "data/.master-key"; + if (existsSync(keyPath)) return Buffer.from(readFileSync(keyPath, "utf8").trim(), "hex"); + const key = randomBytes(32); + writeFileSync(keyPath, key.toString("hex"), { mode: 0o600 }); + return key; +} + +const masterKey = loadMasterKey(); + +export function encryptJson(value: unknown): string { + const iv = randomBytes(12); + const cipher = createCipheriv("aes-256-gcm", masterKey, iv); + const encrypted = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final()]); + const tag = cipher.getAuthTag(); + return Buffer.concat([iv, tag, encrypted]).toString("base64"); +} + +export function decryptJson(encoded: string): T { + if (!encoded) return {} as T; + const data = Buffer.from(encoded, "base64"); + const iv = data.subarray(0, 12); + const tag = data.subarray(12, 28); + const decipher = createDecipheriv("aes-256-gcm", masterKey, iv); + decipher.setAuthTag(tag); + return JSON.parse(Buffer.concat([decipher.update(data.subarray(28)), decipher.final()]).toString("utf8")); +} + +export function hmacHex(secret: string, content: string): string { + return createHmac("sha256", secret).update(content).digest("hex"); +} + +export function safeEqual(a: string, b: string): boolean { + const aa = Buffer.from(a); + const bb = Buffer.from(b); + return aa.length === bb.length && timingSafeEqual(aa, bb); +} + +export function randomId(prefix: string): string { + return `${prefix}_${Date.now().toString(36)}_${randomBytes(8).toString("hex")}`; +} diff --git a/src/server.ts b/src/server.ts new file mode 100644 index 0000000..d5ae63a --- /dev/null +++ b/src/server.ts @@ -0,0 +1,843 @@ +import QRCode from "qrcode"; +import { db, getSetting, initializeDatabase, setSetting } from "./db"; +import { decryptJson, encryptJson, hmacHex, randomId, safeEqual } from "./security"; +import { + createProviderPayment, createProviderRefund, parseAlipayCallback, parseWechatCallback, + queryProviderPayment, queryProviderRefund, + type GatewayRecord, type ProviderCallbackResult +} from "./payments"; +import { isIP } from "node:net"; +import { lookup } from "node:dns/promises"; +import { creditExternalUserQuota, getExternalUser, refundExternalUserQuota, searchExternalUsers, type ExternalUser } from "./external-db"; + +await initializeDatabase(); + +const host = process.env.HOST || "0.0.0.0"; +const port = Number(process.env.PORT || 3000); +const appBaseUrl = (process.env.APP_BASE_URL || `http://localhost:${port}`).replace(/\/$/, ""); +const publicDir = `${process.cwd()}\\public`; +const providerQueryTimes = new Map(); + +type Row = Record; + +function json(data: unknown, status = 200, headers: HeadersInit = {}) { + return Response.json(data, { status, headers: { "cache-control": "no-store", ...headers } }); +} + +function errorJson(message: string, status = 400) { + return json({ ok: false, message }, status); +} + +function clientIp(request: Request): string { + return request.headers.get("x-forwarded-for")?.split(",")[0].trim() + || request.headers.get("x-real-ip") || "local"; +} + +function cookies(request: Request): Record { + const result: Record = {}; + for (const part of (request.headers.get("cookie") || "").split(";")) { + const at = part.indexOf("="); + if (at > 0) result[part.slice(0, at).trim()] = decodeURIComponent(part.slice(at + 1)); + } + return result; +} + +function currentAdmin(request: Request): Row | null { + const sessionId = cookies(request).mp_session; + if (!sessionId) return null; + return db.query(`SELECT a.id, a.username FROM sessions s JOIN admins a ON a.id = s.admin_id + WHERE s.id = ? AND s.expires_at > ?`).get(sessionId, new Date().toISOString()) as Row | null; +} + +function requireAdmin(request: Request): Row | Response { + const admin = currentAdmin(request); + return admin || errorJson("登录已失效,请重新登录", 401); +} + +function mutationAllowed(request: Request): boolean { + if (["GET", "HEAD", "OPTIONS"].includes(request.method)) return true; + const origin = request.headers.get("origin"); + if (!origin) return true; + try { return new URL(origin).host === new URL(request.url).host; } catch { return false; } +} + +function audit(adminId: number | null, action: string, detail: unknown, request: Request) { + db.query("INSERT INTO audit_logs (admin_id, action, detail, ip, created_at) VALUES (?, ?, ?, ?, ?)") + .run(adminId, action, JSON.stringify(detail), clientIp(request), new Date().toISOString()); +} + +function gatewayFromRow(row: Row): GatewayRecord { + return { ...row, config: decryptJson>(row.config_encrypted || "") } as GatewayRecord; +} + +function getGateway(id: string): GatewayRecord | null { + const row = db.query("SELECT * FROM gateways WHERE id = ?").get(id) as Row | null; + return row ? gatewayFromRow(row) : null; +} + +function syncExternalUser(user: ExternalUser) { + const now = new Date().toISOString(); + db.transaction(() => { + db.query(`INSERT INTO users (id, display_name, points_balance, enabled, created_at, updated_at) + VALUES (?, ?, 0, 1, ?, ?) ON CONFLICT(id) DO UPDATE SET + display_name=excluded.display_name, updated_at=excluded.updated_at`) + .run(user.id, user.username, now, now); + db.query(`INSERT INTO external_user_links + (local_user_id, external_user_id, external_username, last_synced_at) + VALUES (?, ?, ?, ?) ON CONFLICT(local_user_id) DO UPDATE SET + external_user_id=excluded.external_user_id, + external_username=excluded.external_username, + last_synced_at=excluded.last_synced_at`) + .run(user.id, user.id, user.username, now); + db.query(`INSERT INTO external_user_snapshots + (external_user_id, username, quota, used_quota, synced_at) + VALUES (?, ?, ?, ?, ?)`).run(user.id, user.username, user.quota, user.usedQuota, now); + })(); +} + +function moneyToCents(value: unknown): number { + const text = String(value ?? "").trim(); + if (!/^(0|[1-9]\d{0,6})(\.\d{1,2})?$/.test(text)) throw new Error("金额格式不正确,最多保留两位小数"); + const cents = Math.round(Number(text) * 100); + if (cents < 1 || cents > 99_999_999) throw new Error("金额必须在 0.01 至 999999.99 元之间"); + return cents; +} + +function normalizeOrderNo(value: unknown): string { + const orderNo = String(value || "").trim(); + if (!/^[A-Za-z0-9_-]{6,32}$/.test(orderNo)) throw new Error("业务订单号需为 6-32 位字母、数字、下划线或短横线"); + return orderNo; +} + +function normalizeUserId(value: unknown): string { + const userId = String(value || "").trim(); + if (!/^[A-Za-z0-9@._:-]{1,64}$/.test(userId)) throw new Error("用户 ID 格式不正确"); + return userId; +} + +function publicOrder(row: Row) { + let provider: Record = {}; + try { provider = row.provider_payload ? JSON.parse(row.provider_payload) : {}; } catch { /* ignore malformed legacy payload */ } + return { + id: row.id, + merchantOrderNo: row.merchant_order_no, + amount: (row.amount_cents / 100).toFixed(2), + subject: row.subject, + category: row.category, + channel: row.channel, + status: row.status, + expiresAt: row.expires_at, + paidAt: row.paid_at, + returnUrl: row.return_url, + paymentUrl: provider.flow === "redirect" ? provider.redirect_url : null, + userId: row.user_id, + packageId: row.package_id, + points: Number(row.points || 0), + pointsCredited: Boolean(row.points_credited), + businessStatus: row.business_status || "pending" + }; +} + +async function validateCallbackTarget(rawUrl: string) { + const url = new URL(rawUrl); + if (!["http:", "https:"].includes(url.protocol)) throw new Error("业务回调地址仅支持 HTTP/HTTPS"); + if (process.env.ALLOW_PRIVATE_CALLBACKS === "true") return; + const blocked = (ip: string) => { + if (ip === "127.0.0.1" || ip === "::1" || ip === "0.0.0.0") return true; + if (ip.startsWith("10.") || ip.startsWith("192.168.") || ip.startsWith("169.254.")) return true; + const m = ip.match(/^172\.(\d+)\./); + if (m && Number(m[1]) >= 16 && Number(m[1]) <= 31) return true; + return ip.startsWith("fc") || ip.startsWith("fd") || ip.startsWith("fe80:"); + }; + const addresses = isIP(url.hostname) ? [{ address: url.hostname }] : await lookup(url.hostname, { all: true }); + if (!addresses.length || addresses.some((item) => blocked(item.address))) throw new Error("生产模式不允许回调到本机或内网地址"); +} + +async function deliverBusinessCallback(order: Row) { + if (!order.notify_url || order.callback_status === "success") return; + const maxAttempts = Math.max(1, Number(getSetting("callback_max_attempts", "5")) || 5); + if (order.callback_attempts >= maxAttempts) return; + const event = { + event: "payment.succeeded", + event_id: `evt_${order.id}`, + order_id: order.id, + merchant_order_no: order.merchant_order_no, + channel: order.channel, + amount: (order.amount_cents / 100).toFixed(2), + user_id: order.user_id, + package_id: order.package_id, + points: Number(order.points || 0), + status: "paid", + provider_trade_no: order.provider_trade_no, + paid_at: order.paid_at + }; + const body = JSON.stringify(event); + const timestamp = Math.floor(Date.now() / 1000).toString(); + const signature = hmacHex(getSetting("merchant_secret"), `${timestamp}.${body}`); + let responseStatus: number | null = null; + let responseBody = ""; + let success = false; + try { + await validateCallbackTarget(order.notify_url); + const response = await fetch(order.notify_url, { + method: "POST", + headers: { + "content-type": "application/json", + "x-pay-timestamp": timestamp, + "x-pay-signature": signature, + "x-pay-event-id": event.event_id + }, + body, + redirect: "error", + signal: AbortSignal.timeout(8_000) + }); + responseStatus = response.status; + responseBody = (await response.text()).slice(0, 2000); + success = response.ok; + } catch (error) { + responseBody = error instanceof Error ? error.message : String(error); + } + const now = new Date().toISOString(); + db.transaction(() => { + db.query(`INSERT INTO callback_logs + (order_id, target_url, request_body, response_status, response_body, success, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`) + .run(order.id, order.notify_url, body, responseStatus, responseBody, success ? 1 : 0, now); + db.query(`UPDATE orders SET callback_attempts = callback_attempts + 1, + callback_status = ?, callback_response = ?, updated_at = ? WHERE id = ?`) + .run(success ? "success" : "failed", responseBody, now, order.id); + })(); +} + +async function completePayment(order: Row, result: ProviderCallbackResult) { + order = db.query("SELECT * FROM orders WHERE id=?").get(order.id) as Row; + if (order.status === "paid") { + if (order.provider_trade_no && order.provider_trade_no !== result.providerTradeNo) throw new Error("重复通知的支付单号不一致"); + return false; + } + const difference = result.amountCents - order.amount_cents; + const now = new Date().toISOString(); + if (difference !== 0) { + db.query(`INSERT INTO reconciliation + (order_id, channel, category, expected_cents, actual_cents, difference_cents, result, provider_trade_no, reconciled_at, note) + VALUES (?, ?, ?, ?, ?, ?, 'mismatch', ?, ?, '支付金额与订单金额不一致') + ON CONFLICT(order_id) DO UPDATE SET actual_cents=excluded.actual_cents, + difference_cents=excluded.difference_cents, result='mismatch', reconciled_at=excluded.reconciled_at`) + .run(order.id, order.channel, order.category, order.amount_cents, result.amountCents, difference, result.providerTradeNo, now); + throw new Error("支付金额与订单金额不一致"); + } + if (!order.user_id) throw new Error("订单未绑定业务用户,无法入账"); + if (order.payment_confirmed) { + if (order.provider_trade_no !== result.providerTradeNo) throw new Error("支付渠道单号与已确认记录不一致"); + } else { + db.query(`UPDATE orders SET payment_confirmed=1, provider_trade_no=?, provider_payload=?, paid_at=?, + business_status='pending', business_error=NULL, updated_at=? WHERE id=? AND status <> 'paid'`) + .run(result.providerTradeNo, JSON.stringify(result.raw), result.paidAt, now, order.id); + } + + try { + await creditExternalUserQuota({ + userId: String(order.user_id), + points: Number(order.points || 0), + orderId: String(order.id), + providerTradeNo: result.providerTradeNo + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + db.query(`UPDATE orders SET business_status='failed', business_attempts=business_attempts+1, + business_error=?, updated_at=? WHERE id=? AND status <> 'paid'`) + .run(message.slice(0, 2000), new Date().toISOString(), order.id); + throw new Error(`支付已确认,业务积分入账失败:${message}`); + } + + const completedAt = new Date().toISOString(); + let paymentCompleted = false; + db.transaction(() => { + const paymentUpdate = db.query(`UPDATE orders SET status='paid', points_credited=1, + business_status='success', business_attempts=business_attempts+1, business_error=NULL, + business_completed_at=?, callback_status=CASE WHEN notify_url IS NULL OR notify_url='' THEN 'not_required' ELSE 'pending' END, + updated_at=? WHERE id=? AND status <> 'paid'`) + .run(completedAt, completedAt, order.id); + paymentCompleted = paymentUpdate.changes > 0; + db.query(`INSERT INTO reconciliation + (order_id, channel, category, expected_cents, actual_cents, difference_cents, result, provider_trade_no, reconciled_at) + VALUES (?, ?, ?, ?, ?, 0, 'matched', ?, ?) + ON CONFLICT(order_id) DO NOTHING`) + .run(order.id, order.channel, order.category, order.amount_cents, result.amountCents, result.providerTradeNo, now); + })(); + return paymentCompleted; +} + +async function refundPayment(order: Row, rollbackPoints: boolean, requestedPoints: unknown) { + order = db.query("SELECT * FROM orders WHERE id=?").get(order.id) as Row; + if (order.status === "refunded") return { completed: true, pending: false }; + if (order.status !== "paid") throw new Error("只有已支付订单可以退款"); + const points = rollbackPoints ? Number(requestedPoints) : 0; + if (!Number.isSafeInteger(points) || points < 0) throw new Error("回退积分必须是非负整数"); + if (rollbackPoints && points > 0) { + if (!order.user_id || !await getExternalUser(String(order.user_id))) throw new Error("订单绑定的业务用户不存在,不能回退积分"); + } + const existingStarted = order.refund_status && order.refund_status !== "not_started"; + if (existingStarted && (Boolean(order.refund_points_enabled) !== rollbackPoints || Number(order.refund_points) !== points)) { + throw new Error("退款已经开始,不能修改积分回退设置"); + } + const gateway = getGateway(order.gateway_id); + if (!gateway) throw new Error("原支付网关不存在,无法退款"); + const refundRequestNo = order.refund_request_no || `refund_${order.id}`; + const now = new Date().toISOString(); + if (!existingStarted) { + db.query(`UPDATE orders SET refund_status='requesting', refund_request_no=?, refund_points_enabled=?, + refund_points=?, refund_requested_at=?, refund_error=NULL, updated_at=? WHERE id=?`) + .run(refundRequestNo, rollbackPoints ? 1 : 0, points, now, now, order.id); + order.refund_status = "requesting"; + } + + let refundResult; + if (["provider_success", "business_failed"].includes(order.refund_status) && order.provider_refund_no) { + refundResult = { status: "success" as const, providerRefundNo: order.provider_refund_no, raw: {} }; + } else if (order.refund_status === "processing") { + refundResult = await queryProviderRefund(gateway, { + merchantOrderNo: order.merchant_order_no, amountCents: order.amount_cents + }, refundRequestNo); + } else { + refundResult = await createProviderRefund(gateway, { + merchantOrderNo: order.merchant_order_no, amountCents: order.amount_cents + }, refundRequestNo); + } + + if (refundResult.status === "processing") { + db.query(`UPDATE orders SET refund_status='processing', provider_refund_no=?, refund_payload=?, + refund_error=NULL, updated_at=? WHERE id=?`) + .run(refundResult.providerRefundNo, JSON.stringify(refundResult.raw), new Date().toISOString(), order.id); + return { completed: false, pending: true }; + } + + db.query(`UPDATE orders SET refund_status='provider_success', provider_refund_no=?, refund_payload=?, + refund_error=NULL, updated_at=? WHERE id=?`) + .run(refundResult.providerRefundNo, JSON.stringify(refundResult.raw), new Date().toISOString(), order.id); + if (rollbackPoints && points > 0) { + try { + await refundExternalUserQuota({ + userId: String(order.user_id), points, orderId: String(order.id), + providerRefundNo: refundResult.providerRefundNo + }); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + db.query(`UPDATE orders SET refund_status='business_failed', refund_error=?, updated_at=? WHERE id=?`) + .run(message.slice(0, 2000), new Date().toISOString(), order.id); + throw new Error(`渠道退款成功,但积分回退失败:${message}`); + } + } + const completedAt = new Date().toISOString(); + db.query(`UPDATE orders SET status='refunded', refund_status='success', refund_error=NULL, + refunded_at=?, updated_at=? WHERE id=? AND status='paid'`).run(completedAt, completedAt, order.id); + return { completed: true, pending: false }; +} + +function queryPage(url: URL, baseSql: string, countSql: string, allowedFilters: Record, params: unknown[] = []) { + const where: string[] = []; + const queryParams = [...params]; + for (const [key, column] of Object.entries(allowedFilters)) { + const value = url.searchParams.get(key); + if (value) { where.push(`${column} = ?`); queryParams.push(value); } + } + const start = url.searchParams.get("start"); + const end = url.searchParams.get("end"); + if (start) { where.push("created_at >= ?"); queryParams.push(new Date(`${start}T00:00:00+08:00`).toISOString()); } + if (end) { where.push("created_at <= ?"); queryParams.push(new Date(`${end}T23:59:59+08:00`).toISOString()); } + const clause = where.length ? ` WHERE ${where.join(" AND ")}` : ""; + const page = Math.max(1, Number(url.searchParams.get("page") || 1)); + const pageSize = Math.min(100, Math.max(1, Number(url.searchParams.get("page_size") || 20))); + const rows = db.query(`${baseSql}${clause} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...queryParams, pageSize, (page - 1) * pageSize) as Row[]; + const count = db.query(`${countSql}${clause}`).get(...queryParams) as { total: number }; + return { rows, total: count.total, page, pageSize }; +} + +async function serveStatic(pathname: string): Promise { + const map: Record = { + "/": "checkout.html", + "/pay": "checkout.html", + "/admin": "admin.html", + "/admin/": "admin.html", + "/assets/app.css": "app.css", + "/assets/checkout.js": "checkout.js", + "/assets/admin.js": "admin.js" + }; + const name = map[pathname]; + if (!name) return new Response("Not found", { status: 404 }); + const file = Bun.file(`${publicDir}\\${name}`); + if (!(await file.exists())) return new Response("Not found", { status: 404 }); + return new Response(file, { headers: { "cache-control": name.endsWith(".html") ? "no-store" : "public, max-age=3600" } }); +} + +const server = Bun.serve({ + hostname: host, + port, + async fetch(request) { + const url = new URL(request.url); + const path = url.pathname; + try { + if (!mutationAllowed(request)) return errorJson("请求来源校验失败", 403); + + if (path === "/api/health") return json({ ok: true, time: new Date().toISOString() }); + + const checkoutUserMatch = path.match(/^\/api\/checkout\/users\/([^/]+)$/); + if (checkoutUserMatch && request.method === "GET") { + const userId = normalizeUserId(decodeURIComponent(checkoutUserMatch[1])); + const externalUser = await getExternalUser(userId); + if (!externalUser) return errorJson("不存在的用户", 404); + syncExternalUser(externalUser); + const sixMonthsAgo = new Date(); + sixMonthsAgo.setMonth(sixMonthsAgo.getMonth() - 6); + const history = db.query(`SELECT id, merchant_order_no, amount_cents, points, channel, paid_at + FROM orders WHERE user_id=? AND status='paid' AND paid_at>=? + ORDER BY paid_at DESC LIMIT 50`).all(userId, sixMonthsAgo.toISOString()); + const packages = db.query(`SELECT id, name, amount_cents, points + FROM recharge_packages WHERE enabled=1 ORDER BY sort_order, amount_cents, id`).all(); + return json({ + user: { + id: externalUser.id, + displayName: externalUser.username, + username: externalUser.username, + pointsBalance: externalUser.quota, + quota: externalUser.quota, + usedQuota: externalUser.usedQuota + }, + packages, + history, + historyStart: sixMonthsAgo.toISOString() + }); + } + + if (path === "/api/checkout/config" && request.method === "GET") { + const gateways = db.query(`SELECT id, name, channel, subject_type FROM gateways WHERE enabled=1 ORDER BY channel`).all(); + return json({ siteName: getSetting("site_name", "聚合支付中心"), gateways }); + } + + if (path === "/api/checkout/orders" && request.method === "POST") { + const input = await request.json() as Row; + const userId = normalizeUserId(input.user_id); + const externalUser = await getExternalUser(userId); + if (!externalUser) return errorJson("不存在的用户", 404); + syncExternalUser(externalUser); + const user = db.query("SELECT id, display_name FROM users WHERE id=? AND enabled=1").get(userId) as Row | null; + if (!user) return errorJson("用户关联失败", 500); + const packageId = Number(input.package_id); + if (!Number.isInteger(packageId) || packageId < 1) return errorJson("请选择充值套餐", 400); + const selectedPackage = db.query("SELECT * FROM recharge_packages WHERE id=? AND enabled=1") + .get(packageId) as Row | null; + if (!selectedPackage) return errorJson("充值套餐不存在或已停用", 400); + const amountCents = Number(selectedPackage.amount_cents); + if (input.amount && moneyToCents(input.amount) !== amountCents) throw new Error("套餐金额校验失败"); + const points = Number(selectedPackage.points); + const merchantOrderNo = normalizeOrderNo(input.merchant_order_no); + const subject = String(input.subject || selectedPackage.name || "账户充值").trim().slice(0, 80) || "账户充值"; + const category = ["recharge", "purchase", "service", "other"].includes(input.category) ? input.category : "recharge"; + const notifyUrl = input.notify_url ? String(input.notify_url).slice(0, 500) : ""; + const returnUrl = input.return_url ? String(input.return_url).slice(0, 500) : ""; + if (notifyUrl) new URL(notifyUrl); + if (returnUrl) new URL(returnUrl); + if (getSetting("require_order_signature") === "true") { + const timestamp = String(input.timestamp || ""); + if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) throw new Error("订单链接已过期"); + const content = `amount=${(amountCents / 100).toFixed(2)}&merchant_order_no=${merchantOrderNo}¬ify_url=${notifyUrl}&package_id=${selectedPackage.id}×tamp=${timestamp}&user_id=${userId}`; + const expected = hmacHex(getSetting("merchant_secret"), content); + if (!safeEqual(expected, String(input.sign || ""))) throw new Error("订单签名不正确"); + } + const existing = db.query("SELECT * FROM orders WHERE merchant_order_no = ?").get(merchantOrderNo) as Row | null; + if (existing) { + if (existing.amount_cents !== amountCents) throw new Error("该业务订单号已存在且金额不同"); + if (existing.user_id !== userId) throw new Error("该业务订单号属于其他用户"); + return json({ ok: true, order: publicOrder(existing) }); + } + const gateway = getGateway(String(input.gateway_id || "")); + if (!gateway || !gateway.enabled) throw new Error("所选支付方式当前不可用"); + const now = new Date(); + const expiresAt = new Date(now.getTime() + Math.max(1, Number(getSetting("order_expire_minutes", "15"))) * 60_000).toISOString(); + const id = randomId("pay"); + db.query(`INSERT INTO orders + (id, merchant_order_no, amount_cents, subject, category, channel, gateway_id, status, + notify_url, return_url, client_ip, created_at, expires_at, updated_at, user_id, package_id, points) + VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?, ?, ?)`) + .run(id, merchantOrderNo, amountCents, subject, category, gateway.channel, gateway.id, + notifyUrl, returnUrl, clientIp(request), now.toISOString(), expiresAt, now.toISOString(), + userId, selectedPackage.id, points); + try { + const result = await createProviderPayment(gateway, { + id, merchantOrderNo, amountCents, subject, expiresAt, returnUrl + }, appBaseUrl); + db.query("UPDATE orders SET qr_content=?, provider_payload=?, updated_at=? WHERE id=?") + .run(result.qrContent, JSON.stringify(result.providerPayload), new Date().toISOString(), id); + } catch (error) { + db.query("UPDATE orders SET status='failed', callback_response=?, updated_at=? WHERE id=?") + .run(error instanceof Error ? error.message : String(error), new Date().toISOString(), id); + throw error; + } + const row = db.query("SELECT * FROM orders WHERE id = ?").get(id) as Row; + return json({ ok: true, order: publicOrder(row) }, 201); + } + + const publicOrderMatch = path.match(/^\/api\/checkout\/orders\/([^/]+)$/); + if (publicOrderMatch && request.method === "GET") { + let row = db.query("SELECT * FROM orders WHERE id = ?").get(decodeURIComponent(publicOrderMatch[1])) as Row | null; + if (row?.status === "pending") { + const lastQuery = providerQueryTimes.get(row.id) || 0; + if (Date.now() - lastQuery >= 3_000) { + providerQueryTimes.set(row.id, Date.now()); + try { + let result: ProviderCallbackResult | null = null; + if (row.payment_confirmed && row.provider_trade_no) { + let raw: unknown = {}; + try { raw = JSON.parse(row.provider_payload || "{}"); } catch { /* use empty retry payload */ } + result = { + merchantOrderNo: row.merchant_order_no, + providerTradeNo: row.provider_trade_no, + amountCents: row.amount_cents, + paidAt: row.paid_at || new Date().toISOString(), + raw + }; + } else { + const gateway = getGateway(row.gateway_id); + if (gateway) result = await queryProviderPayment(gateway, row.merchant_order_no); + } + if (result) { + await completePayment(row, result); + row = db.query("SELECT * FROM orders WHERE id = ?").get(row.id) as Row; + if (row.status === "paid") void deliverBusinessCallback(row); + } + } catch (error) { + console.error(`[ALIPAY QUERY] ${row.merchant_order_no}`, error); + } + } + } + return row ? json({ ok: true, order: publicOrder(row) }) : errorJson("订单不存在", 404); + } + + const qrMatch = path.match(/^\/api\/checkout\/orders\/([^/]+)\/qrcode$/); + if (qrMatch && request.method === "GET") { + const row = db.query("SELECT qr_content, status FROM orders WHERE id = ?").get(decodeURIComponent(qrMatch[1])) as Row | null; + if (!row?.qr_content) return new Response("QR code unavailable", { status: 404 }); + const svg = await QRCode.toString(row.qr_content, { type: "svg", margin: 2, width: 320, color: { dark: "#12212b", light: "#ffffff" } }); + return new Response(svg, { headers: { "content-type": "image/svg+xml", "cache-control": "no-store" } }); + } + + const mockGet = path.match(/^\/mock-pay\/([^/]+)$/); + if (mockGet && request.method === "GET") { + const row = db.query("SELECT * FROM orders WHERE id = ? AND channel='mock'").get(decodeURIComponent(mockGet[1])) as Row | null; + if (!row) return new Response("订单不存在", { status: 404 }); + const escaped = (value: string) => value.replace(/[&<>"']/g, (c) => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]!)); + return new Response(`模拟支付
M

模拟付款确认

此页面仅用于本地联调,不会产生真实扣款。

¥ ${escaped((row.amount_cents/100).toFixed(2))}
${escaped(row.subject)} · ${escaped(row.merchant_order_no)}
${row.status === 'paid' ? '
该订单已支付
' : ``}
`, { headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" } }); + } + + const mockPost = path.match(/^\/api\/mock-pay\/([^/]+)$/); + if (mockPost && request.method === "POST") { + const row = db.query("SELECT * FROM orders WHERE id = ? AND channel='mock'").get(decodeURIComponent(mockPost[1])) as Row | null; + if (!row) return errorJson("模拟订单不存在", 404); + if (row.status === "paid") return json({ ok: true, message: "订单已经支付" }); + const gateway = getGateway(row.gateway_id); + if (!gateway || gateway.mode !== "mock") return errorJson("该订单不允许模拟支付", 403); + await completePayment(row, { + merchantOrderNo: row.merchant_order_no, + providerTradeNo: randomId("mocktrade"), + amountCents: row.amount_cents, + paidAt: new Date().toISOString(), + raw: { mode: "mock", confirmed_ip: clientIp(request) } + }); + const updated = db.query("SELECT * FROM orders WHERE id=?").get(row.id) as Row; + void deliverBusinessCallback(updated); + return json({ ok: true, message: "模拟支付成功" }); + } + + if (path === "/api/callbacks/alipay" && request.method === "POST") { + const params = new URLSearchParams(await request.text()); + let result: ProviderCallbackResult | null = null; + let matchedGateway: GatewayRecord | null = null; + for (const row of db.query("SELECT * FROM gateways WHERE channel='alipay' AND enabled=1").all() as Row[]) { + try { matchedGateway = gatewayFromRow(row); result = parseAlipayCallback(params, matchedGateway); break; } catch { /* try next configured app */ } + } + if (!result || !matchedGateway) return new Response("failure", { status: 400 }); + const order = db.query("SELECT * FROM orders WHERE merchant_order_no=? AND gateway_id=?").get(result.merchantOrderNo, matchedGateway.id) as Row | null; + if (!order) return new Response("failure", { status: 404 }); + await completePayment(order, result); + const updated = db.query("SELECT * FROM orders WHERE id=?").get(order.id) as Row; + void deliverBusinessCallback(updated); + return new Response("success", { headers: { "content-type": "text/plain" } }); + } + + if (path === "/api/callbacks/wechat" && request.method === "POST") { + const raw = await request.text(); + let result: ProviderCallbackResult | null = null; + let matchedGateway: GatewayRecord | null = null; + for (const row of db.query("SELECT * FROM gateways WHERE channel='wechat' AND enabled=1").all() as Row[]) { + try { matchedGateway = gatewayFromRow(row); result = parseWechatCallback(raw, request.headers, matchedGateway); break; } catch { /* try next configured merchant */ } + } + if (!result || !matchedGateway) return json({ code: "FAIL", message: "签名或通知无效" }, 401); + const order = db.query("SELECT * FROM orders WHERE merchant_order_no=? AND gateway_id=?").get(result.merchantOrderNo, matchedGateway.id) as Row | null; + if (!order) return json({ code: "FAIL", message: "订单不存在" }, 404); + await completePayment(order, result); + const updated = db.query("SELECT * FROM orders WHERE id=?").get(order.id) as Row; + void deliverBusinessCallback(updated); + return json({ code: "SUCCESS", message: "成功" }); + } + + if (path === "/api/admin/session" && request.method === "GET") { + const admin = currentAdmin(request); + return admin ? json({ authenticated: true, admin }) : json({ authenticated: false }, 401); + } + + if (path === "/api/admin/login" && request.method === "POST") { + const input = await request.json() as Row; + const admin = db.query("SELECT * FROM admins WHERE username = ?").get(String(input.username || "")) as Row | null; + const valid = admin && await Bun.password.verify(String(input.password || ""), admin.password_hash); + if (!valid) { audit(admin?.id || null, "login_failed", { username: input.username }, request); return errorJson("账户或密码错误", 401); } + const sessionId = randomId("sess"); + const now = new Date(); + db.query("INSERT INTO sessions (id, admin_id, expires_at, created_at) VALUES (?, ?, ?, ?)") + .run(sessionId, admin.id, new Date(now.getTime() + 12 * 60 * 60_000).toISOString(), now.toISOString()); + audit(admin.id, "login_success", {}, request); + return json({ ok: true, admin: { id: admin.id, username: admin.username } }, 200, { + "set-cookie": `mp_session=${encodeURIComponent(sessionId)}; HttpOnly; SameSite=Strict; Path=/; Max-Age=43200${url.protocol === "https:" ? "; Secure" : ""}` + }); + } + + if (path.startsWith("/api/admin/")) { + const auth = requireAdmin(request); + if (auth instanceof Response) return auth; + const admin = auth; + + if (path === "/api/admin/logout" && request.method === "POST") { + const sessionId = cookies(request).mp_session; + if (sessionId) db.query("DELETE FROM sessions WHERE id=?").run(sessionId); + return json({ ok: true }, 200, { "set-cookie": "mp_session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0" }); + } + + if (path === "/api/admin/dashboard" && request.method === "GET") { + const todayStart = new Date(); + todayStart.setHours(0, 0, 0, 0); + const stats = db.query(`SELECT + COUNT(*) total_orders, + SUM(CASE WHEN status='paid' THEN 1 ELSE 0 END) paid_orders, + COALESCE(SUM(CASE WHEN status='paid' THEN amount_cents ELSE 0 END),0) paid_cents, + SUM(CASE WHEN status='pending' THEN 1 ELSE 0 END) pending_orders + FROM orders WHERE created_at >= ?`).get(todayStart.toISOString()); + const recent = db.query("SELECT * FROM orders ORDER BY created_at DESC LIMIT 8").all(); + const channels = db.query(`SELECT channel, COUNT(*) count, + COALESCE(SUM(CASE WHEN status='paid' THEN amount_cents ELSE 0 END),0) amount_cents + FROM orders GROUP BY channel`).all(); + return json({ stats, recent, channels }); + } + + if (path === "/api/admin/orders" && request.method === "GET") { + const result = queryPage(url, "SELECT * FROM orders", "SELECT COUNT(*) total FROM orders", { + channel: "channel", status: "status", category: "category", user_id: "user_id" + }); + return json(result); + } + + if (path === "/api/admin/users" && request.method === "GET") { + const search = String(url.searchParams.get("search") || "").trim(); + const externalUsers = await searchExternalUsers(search); + const rows = externalUsers.map((user) => { + syncExternalUser(user); + const stats = db.query(`SELECT + COUNT(CASE WHEN status='paid' THEN 1 END) paid_orders, + COALESCE(SUM(CASE WHEN status='paid' THEN amount_cents ELSE 0 END),0) paid_cents + FROM orders WHERE user_id=?`).get(user.id) as Row; + const link = db.query("SELECT last_synced_at FROM external_user_links WHERE external_user_id=?") + .get(user.id) as Row | null; + return { + id: user.id, + display_name: user.username, + username: user.username, + points_balance: user.quota, + quota: user.quota, + used_quota: user.usedQuota, + enabled: 1, + updated_at: link?.last_synced_at || new Date().toISOString(), + paid_orders: stats.paid_orders, + paid_cents: stats.paid_cents + }; + }); + return json({ rows }); + } + + const userAdminMatch = path.match(/^\/api\/admin\/users\/([^/]+)$/); + if (userAdminMatch && ["PUT", "POST", "DELETE"].includes(request.method)) { + return errorJson("用户数据来自 PostgreSQL,仅允许查询", 405); + } + + if (path === "/api/admin/packages" && request.method === "GET") { + const rows = db.query("SELECT * FROM recharge_packages ORDER BY sort_order, amount_cents, id").all(); + return json({ rows }); + } + + const packageAdminMatch = path.match(/^\/api\/admin\/packages\/([^/]+)$/); + if (packageAdminMatch && request.method === "PUT") { + const input = await request.json() as Row; + const name = String(input.name || "充值套餐").trim().slice(0, 60); + const amountCents = moneyToCents(input.amount); + const points = Math.max(0, Math.floor(Number(input.points) || 0)); + const sortOrder = Math.floor(Number(input.sort_order) || 0); + const now = new Date().toISOString(); + const rawId = decodeURIComponent(packageAdminMatch[1]); + if (rawId === "new") { + const result = db.query(`INSERT INTO recharge_packages + (name,amount_cents,points,enabled,sort_order,created_at,updated_at) VALUES (?,?,?,?,?,?,?)`) + .run(name, amountCents, points, input.enabled ? 1 : 0, sortOrder, now, now); + audit(admin.id, "create_package", { id: result.lastInsertRowid, amountCents, points }, request); + } else { + const id = Number(rawId); + if (!Number.isInteger(id) || id < 1) throw new Error("套餐 ID 不正确"); + const result = db.query(`UPDATE recharge_packages SET name=?, amount_cents=?, points=?, + enabled=?, sort_order=?, updated_at=? WHERE id=?`) + .run(name, amountCents, points, input.enabled ? 1 : 0, sortOrder, now, id); + if (!result.changes) return errorJson("套餐不存在", 404); + audit(admin.id, "save_package", { id, amountCents, points, enabled: Boolean(input.enabled) }, request); + } + return json({ ok: true }); + } + + const refundMatch = path.match(/^\/api\/admin\/orders\/([^/]+)\/refund$/); + if (refundMatch && request.method === "POST") { + const order = db.query("SELECT * FROM orders WHERE id=?").get(decodeURIComponent(refundMatch[1])) as Row | null; + if (!order) return errorJson("订单不存在", 404); + const input = await request.json() as Row; + const rollbackPoints = Boolean(input.rollback_points); + const points = rollbackPoints ? input.points : 0; + const result = await refundPayment(order, rollbackPoints, points); + audit(admin.id, "refund_order", { + orderId: order.id, + amountCents: order.amount_cents, + rollbackPoints, + points: rollbackPoints ? Number(points) : 0, + pending: result.pending + }, request); + return json({ + ok: true, + pending: result.pending, + message: result.pending ? "退款已受理,等待支付渠道确认" : "退款完成" + }); + } + + const retryMatch = path.match(/^\/api\/admin\/orders\/([^/]+)\/retry-callback$/); + if (retryMatch && request.method === "POST") { + const row = db.query("SELECT * FROM orders WHERE id=? AND status='paid'").get(decodeURIComponent(retryMatch[1])) as Row | null; + if (!row) return errorJson("已支付订单不存在", 404); + db.query("UPDATE orders SET callback_status='pending', callback_attempts=0 WHERE id=?").run(row.id); + const fresh = db.query("SELECT * FROM orders WHERE id=?").get(row.id) as Row; + await deliverBusinessCallback(fresh); + audit(admin.id, "retry_callback", { orderId: row.id }, request); + return json({ ok: true }); + } + + if (path === "/api/admin/reconciliation" && request.method === "GET") { + const proxy = new URL(url); + const filters: string[] = []; + const params: unknown[] = []; + for (const [key, col] of Object.entries({ channel: "r.channel", result: "r.result", category: "r.category" })) { + const value = proxy.searchParams.get(key); if (value) { filters.push(`${col}=?`); params.push(value); } + } + const start = proxy.searchParams.get("start"); const end = proxy.searchParams.get("end"); + if (start) { filters.push("r.reconciled_at>=?"); params.push(new Date(`${start}T00:00:00+08:00`).toISOString()); } + if (end) { filters.push("r.reconciled_at<=?"); params.push(new Date(`${end}T23:59:59+08:00`).toISOString()); } + const clause = filters.length ? ` WHERE ${filters.join(" AND ")}` : ""; + const page = Math.max(1, Number(proxy.searchParams.get("page") || 1)); const pageSize = 20; + const rows = db.query(`SELECT r.*, o.merchant_order_no, o.subject, r.reconciled_at created_at + FROM reconciliation r JOIN orders o ON o.id=r.order_id${clause} + ORDER BY r.reconciled_at DESC LIMIT ? OFFSET ?`).all(...params, pageSize, (page-1)*pageSize); + const count = db.query(`SELECT COUNT(*) total FROM reconciliation r${clause}`).get(...params) as {total:number}; + return json({ rows, total: count.total, page, pageSize }); + } + + if (path === "/api/admin/gateways" && request.method === "GET") { + const rows = (db.query("SELECT * FROM gateways ORDER BY channel, created_at").all() as Row[]).map((row) => { + const config = decryptJson>(row.config_encrypted || ""); + const secrets = ["privateKey", "alipayPublicKey", "merchantPrivateKey", "wechatPublicKey", "apiV3Key"]; + const safeConfig = { ...config }; + for (const key of secrets) if (safeConfig[key]) safeConfig[key] = ""; + return { ...row, config: safeConfig, configuredSecrets: Object.fromEntries(secrets.map((key) => [key, Boolean(config[key])])), config_encrypted: undefined }; + }); + return json({ rows }); + } + + const gatewayMatch = path.match(/^\/api\/admin\/gateways\/([^/]+)$/); + if (gatewayMatch && request.method === "PUT") { + const id = decodeURIComponent(gatewayMatch[1]); + const input = await request.json() as Row; + if (!/^[a-z0-9_-]{3,40}$/i.test(id)) throw new Error("网关 ID 格式不正确"); + if (!['alipay','wechat','mock'].includes(input.channel)) throw new Error("支付渠道不正确"); + if (!['individual','company'].includes(input.subject_type)) throw new Error("主体类型不正确"); + if (!['mock','sandbox','live'].includes(input.mode)) throw new Error("运行模式不正确"); + const existing = getGateway(id); + const oldConfig = existing?.config || {}; + const nextConfig = { ...oldConfig }; + for (const [key, value] of Object.entries(input.config || {})) { + if (typeof value === "string" && value.trim()) nextConfig[key] = value.trim(); + } + const now = new Date().toISOString(); + db.query(`INSERT INTO gateways + (id,name,channel,subject_type,mode,enabled,config_encrypted,created_at,updated_at) + VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name, channel=excluded.channel, + subject_type=excluded.subject_type, mode=excluded.mode, enabled=excluded.enabled, + config_encrypted=excluded.config_encrypted, updated_at=excluded.updated_at`) + .run(id, String(input.name || id).slice(0,60), input.channel, input.subject_type, input.mode, + input.enabled ? 1 : 0, encryptJson(nextConfig), existing ? (db.query("SELECT created_at FROM gateways WHERE id=?").get(id) as Row).created_at : now, now); + audit(admin.id, "save_gateway", { id, channel: input.channel, mode: input.mode, enabled: Boolean(input.enabled) }, request); + return json({ ok: true }); + } + + if (path === "/api/admin/settings" && request.method === "GET") { + return json({ + site_name: getSetting("site_name"), + require_order_signature: getSetting("require_order_signature") === "true", + order_expire_minutes: Number(getSetting("order_expire_minutes", "15")), + callback_max_attempts: Number(getSetting("callback_max_attempts", "5")), + merchant_secret: getSetting("merchant_secret"), + base_url: appBaseUrl + }); + } + + if (path === "/api/admin/settings" && request.method === "PUT") { + const input = await request.json() as Row; + setSetting("site_name", String(input.site_name || "聚合支付中心").slice(0, 40)); + setSetting("require_order_signature", input.require_order_signature ? "true" : "false"); + setSetting("order_expire_minutes", String(Math.min(120, Math.max(1, Number(input.order_expire_minutes) || 15)))); + setSetting("callback_max_attempts", String(Math.min(10, Math.max(1, Number(input.callback_max_attempts) || 5)))); + if (input.rotate_secret) setSetting("merchant_secret", randomId("secret").replaceAll("_", "")); + audit(admin.id, "save_settings", { rotateSecret: Boolean(input.rotate_secret) }, request); + return json({ ok: true }); + } + + if (path === "/api/admin/password" && request.method === "PUT") { + const input = await request.json() as Row; + const row = db.query("SELECT * FROM admins WHERE id=?").get(admin.id) as Row; + if (!await Bun.password.verify(String(input.current_password || ""), row.password_hash)) return errorJson("当前密码不正确", 403); + const password = String(input.new_password || ""); + if (password.length < 10) return errorJson("新密码至少 10 位"); + const hash = await Bun.password.hash(password, { algorithm: "argon2id" }); + db.query("UPDATE admins SET password_hash=?, updated_at=? WHERE id=?").run(hash, new Date().toISOString(), admin.id); + db.query("DELETE FROM sessions WHERE admin_id=? AND id<>?").run(admin.id, cookies(request).mp_session || ""); + audit(admin.id, "change_password", {}, request); + return json({ ok: true }); + } + + return errorJson("接口不存在", 404); + } + + return serveStatic(path); + } catch (error) { + console.error(`[${request.method}] ${path}`, error); + return errorJson(error instanceof Error ? error.message : "服务器处理失败", 400); + } + } +}); + +setInterval(() => { + const rows = db.query(`SELECT * FROM orders WHERE status='paid' AND callback_status IN ('pending','failed') + AND callback_attempts < ? ORDER BY updated_at LIMIT 10`).all(Number(getSetting("callback_max_attempts", "5"))) as Row[]; + for (const row of rows) void deliverBusinessCallback(row); + db.query("DELETE FROM sessions WHERE expires_at <= ?").run(new Date().toISOString()); +}, 30_000); + +console.log(`MultiPay 已启动:http://${host === "0.0.0.0" ? "localhost" : host}:${server.port}`); +console.log(`管理后台:http://localhost:${server.port}/admin`); diff --git a/start.ps1 b/start.ps1 new file mode 100644 index 0000000..4e7a65d --- /dev/null +++ b/start.ps1 @@ -0,0 +1,10 @@ +$bun = Get-Command bun -ErrorAction SilentlyContinue +if (-not $bun) { + $bunPath = 'C:\Users\11937\.bun\bin\bun.exe' + if (-not (Test-Path -LiteralPath $bunPath)) { + throw '未找到 Bun,请先安装 Bun 1.1 或更高版本。' + } + & $bunPath run start +} else { + bun run start +} diff --git a/tests/security.test.ts b/tests/security.test.ts new file mode 100644 index 0000000..6aebc02 --- /dev/null +++ b/tests/security.test.ts @@ -0,0 +1,18 @@ +import { describe, expect, test } from "bun:test"; +import { decryptJson, encryptJson, hmacHex, safeEqual } from "../src/security"; + +describe("security helpers", () => { + test("encrypts and decrypts gateway configuration", () => { + const value = { appId: "demo", privateKey: "secret" }; + const encrypted = encryptJson(value); + expect(encrypted).not.toContain("secret"); + expect(decryptJson(encrypted)).toEqual(value); + }); + + test("creates deterministic HMAC and constant-time comparison", () => { + const signature = hmacHex("key", "message"); + expect(signature).toHaveLength(64); + expect(safeEqual(signature, signature)).toBe(true); + expect(safeEqual(signature, signature.slice(1))).toBe(false); + }); +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..cd710c7 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "allowJs": false, + "skipLibCheck": true, + "types": ["bun-types"] + }, + "include": ["src/**/*.ts", "tests/**/*.ts"] +}