From ede8c3c212b5485a65190a0c25dfb46898bcf6f2 Mon Sep 17 00:00:00 2001 From: MaliniakovaKarin Date: Tue, 30 Mar 2021 21:29:04 +0200 Subject: [PATCH] PW-35 Add new zapisnice --- node_modules/.bin/prettier | 15 + node_modules/.bin/prettier.cmd | 17 + node_modules/.bin/prettier.ps1 | 18 + node_modules/.bin/rimraf | 15 + node_modules/.bin/rimraf.cmd | 17 + node_modules/.bin/rimraf.ps1 | 18 + node_modules/@types/node/LICENSE | 21 + node_modules/@types/node/README.md | 16 + node_modules/@types/node/assert.d.ts | 91 + node_modules/@types/node/async_hooks.d.ts | 144 + node_modules/@types/node/base.d.ts | 19 + node_modules/@types/node/buffer.d.ts | 16 + node_modules/@types/node/child_process.d.ts | 367 + node_modules/@types/node/cluster.d.ts | 260 + node_modules/@types/node/console.d.ts | 3 + node_modules/@types/node/constants.d.ts | 315 + node_modules/@types/node/crypto.d.ts | 569 + node_modules/@types/node/dgram.d.ts | 102 + node_modules/@types/node/dns.d.ts | 366 + node_modules/@types/node/domain.d.ts | 16 + node_modules/@types/node/events.d.ts | 39 + node_modules/@types/node/fs.d.ts | 2297 + node_modules/@types/node/globals.d.ts | 1144 + node_modules/@types/node/http.d.ts | 282 + node_modules/@types/node/http2.d.ts | 959 + node_modules/@types/node/https.d.ts | 53 + node_modules/@types/node/index.d.ts | 47 + node_modules/@types/node/inspector.d.ts | 3257 + node_modules/@types/node/module.d.ts | 3 + node_modules/@types/node/net.d.ts | 249 + node_modules/@types/node/os.d.ts | 205 + node_modules/@types/node/package.json | 212 + node_modules/@types/node/path.d.ts | 159 + node_modules/@types/node/perf_hooks.d.ts | 232 + node_modules/@types/node/process.d.ts | 3 + node_modules/@types/node/punycode.d.ts | 68 + node_modules/@types/node/querystring.d.ts | 29 + node_modules/@types/node/readline.d.ts | 137 + node_modules/@types/node/repl.d.ts | 390 + node_modules/@types/node/stream.d.ts | 310 + node_modules/@types/node/string_decoder.d.ts | 9 + node_modules/@types/node/timers.d.ts | 16 + node_modules/@types/node/tls.d.ts | 398 + node_modules/@types/node/trace_events.d.ts | 61 + node_modules/@types/node/ts3.6/assert.d.ts | 69 + node_modules/@types/node/ts3.6/base.d.ts | 54 + node_modules/@types/node/ts3.6/index.d.ts | 6 + node_modules/@types/node/tty.d.ts | 52 + node_modules/@types/node/url.d.ts | 104 + node_modules/@types/node/util.d.ts | 181 + node_modules/@types/node/v8.d.ts | 50 + node_modules/@types/node/vm.d.ts | 64 + node_modules/@types/node/worker_threads.d.ts | 143 + node_modules/@types/node/zlib.d.ts | 353 + node_modules/balanced-match/.npmignore | 5 + node_modules/balanced-match/LICENSE.md | 21 + node_modules/balanced-match/README.md | 91 + node_modules/balanced-match/index.js | 59 + node_modules/balanced-match/package.json | 81 + node_modules/brace-expansion/LICENSE | 21 + node_modules/brace-expansion/README.md | 129 + node_modules/brace-expansion/index.js | 201 + node_modules/brace-expansion/package.json | 79 + node_modules/concat-map/.travis.yml | 4 + node_modules/concat-map/LICENSE | 18 + node_modules/concat-map/README.markdown | 62 + node_modules/concat-map/example/map.js | 6 + node_modules/concat-map/index.js | 13 + node_modules/concat-map/package.json | 92 + node_modules/concat-map/test/map.js | 39 + node_modules/core-util-is/LICENSE | 19 + node_modules/core-util-is/README.md | 3 + node_modules/core-util-is/float.patch | 604 + node_modules/core-util-is/lib/util.js | 107 + node_modules/core-util-is/package.json | 66 + node_modules/core-util-is/test.js | 68 + node_modules/fs-extra/.npmignore | 8 + node_modules/fs-extra/CHANGELOG.md | 733 + node_modules/fs-extra/LICENSE | 15 + node_modules/fs-extra/README.md | 251 + node_modules/fs-extra/docs/copy-sync.md | 37 + node_modules/fs-extra/docs/copy.md | 48 + node_modules/fs-extra/docs/emptyDir-sync.md | 16 + node_modules/fs-extra/docs/emptyDir.md | 21 + node_modules/fs-extra/docs/ensureDir-sync.md | 17 + node_modules/fs-extra/docs/ensureDir.md | 20 + node_modules/fs-extra/docs/ensureFile-sync.md | 17 + node_modules/fs-extra/docs/ensureFile.md | 20 + node_modules/fs-extra/docs/ensureLink-sync.md | 17 + node_modules/fs-extra/docs/ensureLink.md | 20 + .../fs-extra/docs/ensureSymlink-sync.md | 18 + node_modules/fs-extra/docs/ensureSymlink.md | 21 + node_modules/fs-extra/docs/move-sync.md | 24 + node_modules/fs-extra/docs/move.md | 33 + node_modules/fs-extra/docs/outputFile-sync.md | 19 + node_modules/fs-extra/docs/outputFile.md | 23 + node_modules/fs-extra/docs/outputJson-sync.md | 22 + node_modules/fs-extra/docs/outputJson.md | 26 + node_modules/fs-extra/docs/readJson-sync.md | 33 + node_modules/fs-extra/docs/readJson.md | 40 + node_modules/fs-extra/docs/remove-sync.md | 16 + node_modules/fs-extra/docs/remove.md | 25 + node_modules/fs-extra/docs/writeJson-sync.md | 21 + node_modules/fs-extra/docs/writeJson.md | 27 + .../fs-extra/lib/copy-sync/copy-file-sync.js | 41 + .../fs-extra/lib/copy-sync/copy-sync.js | 62 + node_modules/fs-extra/lib/copy-sync/index.js | 3 + node_modules/fs-extra/lib/copy/copy.js | 52 + node_modules/fs-extra/lib/copy/index.js | 3 + node_modules/fs-extra/lib/copy/ncp.js | 234 + node_modules/fs-extra/lib/empty/index.js | 47 + node_modules/fs-extra/lib/ensure/file.js | 45 + node_modules/fs-extra/lib/ensure/index.js | 23 + node_modules/fs-extra/lib/ensure/link.js | 60 + .../fs-extra/lib/ensure/symlink-paths.js | 97 + .../fs-extra/lib/ensure/symlink-type.js | 31 + node_modules/fs-extra/lib/ensure/symlink.js | 64 + node_modules/fs-extra/lib/index.js | 37 + node_modules/fs-extra/lib/json/index.js | 11 + node_modules/fs-extra/lib/json/jsonfile.js | 16 + .../fs-extra/lib/json/output-json-sync.js | 18 + node_modules/fs-extra/lib/json/output-json.js | 26 + node_modules/fs-extra/lib/mkdirs/index.js | 9 + .../fs-extra/lib/mkdirs/mkdirs-sync.js | 59 + node_modules/fs-extra/lib/mkdirs/mkdirs.js | 63 + node_modules/fs-extra/lib/mkdirs/win32.js | 25 + node_modules/fs-extra/lib/move-sync/index.js | 117 + node_modules/fs-extra/lib/move/index.js | 161 + node_modules/fs-extra/lib/output/index.js | 37 + node_modules/fs-extra/lib/remove/index.js | 17 + node_modules/fs-extra/lib/remove/rimraf.js | 296 + node_modules/fs-extra/lib/util/assign.js | 16 + node_modules/fs-extra/lib/util/utimes.js | 72 + node_modules/fs-extra/package.json | 96 + node_modules/fs.realpath/LICENSE | 43 + node_modules/fs.realpath/README.md | 33 + node_modules/fs.realpath/index.js | 66 + node_modules/fs.realpath/old.js | 303 + node_modules/fs.realpath/package.json | 63 + node_modules/glob/LICENSE | 21 + node_modules/glob/README.md | 375 + node_modules/glob/changelog.md | 67 + node_modules/glob/common.js | 240 + node_modules/glob/glob.js | 790 + node_modules/glob/package.json | 83 + node_modules/glob/sync.js | 486 + node_modules/graceful-fs/LICENSE | 15 + node_modules/graceful-fs/README.md | 133 + node_modules/graceful-fs/clone.js | 19 + node_modules/graceful-fs/graceful-fs.js | 354 + node_modules/graceful-fs/legacy-streams.js | 118 + node_modules/graceful-fs/package.json | 84 + node_modules/graceful-fs/polyfills.js | 342 + node_modules/inflight/LICENSE | 15 + node_modules/inflight/README.md | 37 + node_modules/inflight/inflight.js | 54 + node_modules/inflight/package.json | 62 + node_modules/inherits/LICENSE | 16 + node_modules/inherits/README.md | 42 + node_modules/inherits/inherits.js | 9 + node_modules/inherits/inherits_browser.js | 27 + node_modules/inherits/package.json | 67 + node_modules/isarray/.npmignore | 1 + node_modules/isarray/.travis.yml | 4 + node_modules/isarray/Makefile | 6 + node_modules/isarray/README.md | 60 + node_modules/isarray/component.json | 19 + node_modules/isarray/index.js | 5 + node_modules/isarray/package.json | 77 + node_modules/isarray/test.js | 20 + node_modules/jsonfile/.npmignore | 2 + node_modules/jsonfile/CHANGELOG.md | 126 + node_modules/jsonfile/LICENSE | 15 + node_modules/jsonfile/README.md | 162 + node_modules/jsonfile/appveyor.yml | 28 + node_modules/jsonfile/index.js | 133 + node_modules/jsonfile/package.json | 73 + node_modules/minimatch/LICENSE | 15 + node_modules/minimatch/README.md | 209 + node_modules/minimatch/minimatch.js | 923 + node_modules/minimatch/package.json | 67 + node_modules/node-latex/.prettierrc | 5 + node_modules/node-latex/index.d.ts | 58 + node_modules/node-latex/index.js | 204 + node_modules/node-latex/license | 21 + node_modules/node-latex/package.json | 70 + node_modules/node-latex/readme.md | 50 + node_modules/once/LICENSE | 15 + node_modules/once/README.md | 79 + node_modules/once/once.js | 42 + node_modules/once/package.json | 71 + node_modules/path-is-absolute/index.js | 20 + node_modules/path-is-absolute/license | 21 + node_modules/path-is-absolute/package.json | 79 + node_modules/path-is-absolute/readme.md | 59 + node_modules/prettier/LICENSE | 7 + node_modules/prettier/README.md | 111 + node_modules/prettier/bin-prettier.js | 16523 +++++ node_modules/prettier/doc.js | 3779 ++ node_modules/prettier/index.js | 54762 ++++++++++++++++ node_modules/prettier/package.json | 61 + node_modules/prettier/parser-angular.js | 46 + node_modules/prettier/parser-babel.js | 1 + node_modules/prettier/parser-flow.js | 1 + node_modules/prettier/parser-glimmer.js | 1 + node_modules/prettier/parser-graphql.js | 1 + node_modules/prettier/parser-html.js | 113 + node_modules/prettier/parser-markdown.js | 19 + node_modules/prettier/parser-postcss.js | 8 + node_modules/prettier/parser-typescript.js | 14 + node_modules/prettier/parser-yaml.js | 15 + node_modules/prettier/standalone.js | 15 + node_modules/prettier/third-party.js | 10583 +++ node_modules/process-nextick-args/index.js | 45 + node_modules/process-nextick-args/license.md | 19 + .../process-nextick-args/package.json | 54 + node_modules/process-nextick-args/readme.md | 18 + node_modules/readable-stream/.travis.yml | 34 + node_modules/readable-stream/CONTRIBUTING.md | 38 + node_modules/readable-stream/GOVERNANCE.md | 136 + node_modules/readable-stream/LICENSE | 47 + node_modules/readable-stream/README.md | 58 + .../doc/wg-meetings/2015-01-30.md | 60 + .../readable-stream/duplex-browser.js | 1 + node_modules/readable-stream/duplex.js | 1 + .../readable-stream/lib/_stream_duplex.js | 131 + .../lib/_stream_passthrough.js | 47 + .../readable-stream/lib/_stream_readable.js | 1019 + .../readable-stream/lib/_stream_transform.js | 214 + .../readable-stream/lib/_stream_writable.js | 687 + .../lib/internal/streams/BufferList.js | 79 + .../lib/internal/streams/destroy.js | 74 + .../lib/internal/streams/stream-browser.js | 1 + .../lib/internal/streams/stream.js | 1 + node_modules/readable-stream/package.json | 86 + node_modules/readable-stream/passthrough.js | 1 + .../readable-stream/readable-browser.js | 7 + node_modules/readable-stream/readable.js | 19 + node_modules/readable-stream/transform.js | 1 + .../readable-stream/writable-browser.js | 1 + node_modules/readable-stream/writable.js | 8 + node_modules/rimraf/LICENSE | 15 + node_modules/rimraf/README.md | 101 + node_modules/rimraf/bin.js | 50 + node_modules/rimraf/package.json | 71 + node_modules/rimraf/rimraf.js | 364 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 584 + node_modules/safe-buffer/index.d.ts | 187 + node_modules/safe-buffer/index.js | 62 + node_modules/safe-buffer/package.json | 67 + node_modules/string-to-stream/LICENSE | 20 + node_modules/string-to-stream/README.md | 34 + node_modules/string-to-stream/index.js | 23 + node_modules/string-to-stream/package.json | 86 + node_modules/string_decoder/.travis.yml | 50 + node_modules/string_decoder/LICENSE | 48 + node_modules/string_decoder/README.md | 47 + .../string_decoder/lib/string_decoder.js | 296 + node_modules/string_decoder/package.json | 63 + node_modules/temp/LICENSE | 20 + node_modules/temp/README.md | 295 + node_modules/temp/lib/temp.js | 314 + node_modules/temp/package.json | 84 + node_modules/through2/LICENSE.md | 9 + node_modules/through2/README.md | 134 + node_modules/through2/package.json | 70 + node_modules/through2/through2.js | 96 + node_modules/util-deprecate/History.md | 16 + node_modules/util-deprecate/LICENSE | 24 + node_modules/util-deprecate/README.md | 53 + node_modules/util-deprecate/browser.js | 67 + node_modules/util-deprecate/node.js | 6 + node_modules/util-deprecate/package.json | 60 + node_modules/wrappy/LICENSE | 15 + node_modules/wrappy/README.md | 36 + node_modules/wrappy/package.json | 63 + node_modules/wrappy/wrappy.js | 33 + 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 | 90 + node_modules/xtend/test.js | 103 + out/zapisnice/zapisnica15.pdf | Bin 130 -> 130 bytes out/zapisnice/zapisnica16_16.pdf | Bin 0 -> 130 bytes out/zapisnice/zapisnica17.pdf | Bin 0 -> 130 bytes out/zapisnice/zapisnica17_17.pdf | Bin 0 -> 130 bytes src/zapisnice/zapisnica15.tex | 2 +- src/zapisnice/zapisnica16_16.tex | 78 + src/zapisnice/zapisnica17.tex | 61 + src/zapisnice/zapisnica17_17.tex | 77 + 293 files changed, 119016 insertions(+), 1 deletion(-) create mode 100644 node_modules/.bin/prettier create mode 100644 node_modules/.bin/prettier.cmd create mode 100644 node_modules/.bin/prettier.ps1 create mode 100644 node_modules/.bin/rimraf create mode 100644 node_modules/.bin/rimraf.cmd create mode 100644 node_modules/.bin/rimraf.ps1 create mode 100644 node_modules/@types/node/LICENSE create mode 100644 node_modules/@types/node/README.md create mode 100644 node_modules/@types/node/assert.d.ts create mode 100644 node_modules/@types/node/async_hooks.d.ts create mode 100644 node_modules/@types/node/base.d.ts create mode 100644 node_modules/@types/node/buffer.d.ts create mode 100644 node_modules/@types/node/child_process.d.ts create mode 100644 node_modules/@types/node/cluster.d.ts create mode 100644 node_modules/@types/node/console.d.ts create mode 100644 node_modules/@types/node/constants.d.ts create mode 100644 node_modules/@types/node/crypto.d.ts create mode 100644 node_modules/@types/node/dgram.d.ts create mode 100644 node_modules/@types/node/dns.d.ts create mode 100644 node_modules/@types/node/domain.d.ts create mode 100644 node_modules/@types/node/events.d.ts create mode 100644 node_modules/@types/node/fs.d.ts create mode 100644 node_modules/@types/node/globals.d.ts create mode 100644 node_modules/@types/node/http.d.ts create mode 100644 node_modules/@types/node/http2.d.ts create mode 100644 node_modules/@types/node/https.d.ts create mode 100644 node_modules/@types/node/index.d.ts create mode 100644 node_modules/@types/node/inspector.d.ts create mode 100644 node_modules/@types/node/module.d.ts create mode 100644 node_modules/@types/node/net.d.ts create mode 100644 node_modules/@types/node/os.d.ts create mode 100644 node_modules/@types/node/package.json create mode 100644 node_modules/@types/node/path.d.ts create mode 100644 node_modules/@types/node/perf_hooks.d.ts create mode 100644 node_modules/@types/node/process.d.ts create mode 100644 node_modules/@types/node/punycode.d.ts create mode 100644 node_modules/@types/node/querystring.d.ts create mode 100644 node_modules/@types/node/readline.d.ts create mode 100644 node_modules/@types/node/repl.d.ts create mode 100644 node_modules/@types/node/stream.d.ts create mode 100644 node_modules/@types/node/string_decoder.d.ts create mode 100644 node_modules/@types/node/timers.d.ts create mode 100644 node_modules/@types/node/tls.d.ts create mode 100644 node_modules/@types/node/trace_events.d.ts create mode 100644 node_modules/@types/node/ts3.6/assert.d.ts create mode 100644 node_modules/@types/node/ts3.6/base.d.ts create mode 100644 node_modules/@types/node/ts3.6/index.d.ts create mode 100644 node_modules/@types/node/tty.d.ts create mode 100644 node_modules/@types/node/url.d.ts create mode 100644 node_modules/@types/node/util.d.ts create mode 100644 node_modules/@types/node/v8.d.ts create mode 100644 node_modules/@types/node/vm.d.ts create mode 100644 node_modules/@types/node/worker_threads.d.ts create mode 100644 node_modules/@types/node/zlib.d.ts create mode 100644 node_modules/balanced-match/.npmignore create mode 100644 node_modules/balanced-match/LICENSE.md create mode 100644 node_modules/balanced-match/README.md create mode 100644 node_modules/balanced-match/index.js create mode 100644 node_modules/balanced-match/package.json create mode 100644 node_modules/brace-expansion/LICENSE create mode 100644 node_modules/brace-expansion/README.md create mode 100644 node_modules/brace-expansion/index.js create mode 100644 node_modules/brace-expansion/package.json create mode 100644 node_modules/concat-map/.travis.yml create mode 100644 node_modules/concat-map/LICENSE create mode 100644 node_modules/concat-map/README.markdown create mode 100644 node_modules/concat-map/example/map.js create mode 100644 node_modules/concat-map/index.js create mode 100644 node_modules/concat-map/package.json create mode 100644 node_modules/concat-map/test/map.js create mode 100644 node_modules/core-util-is/LICENSE create mode 100644 node_modules/core-util-is/README.md create mode 100644 node_modules/core-util-is/float.patch create mode 100644 node_modules/core-util-is/lib/util.js create mode 100644 node_modules/core-util-is/package.json create mode 100644 node_modules/core-util-is/test.js create mode 100644 node_modules/fs-extra/.npmignore create mode 100644 node_modules/fs-extra/CHANGELOG.md create mode 100644 node_modules/fs-extra/LICENSE create mode 100644 node_modules/fs-extra/README.md create mode 100644 node_modules/fs-extra/docs/copy-sync.md create mode 100644 node_modules/fs-extra/docs/copy.md create mode 100644 node_modules/fs-extra/docs/emptyDir-sync.md create mode 100644 node_modules/fs-extra/docs/emptyDir.md create mode 100644 node_modules/fs-extra/docs/ensureDir-sync.md create mode 100644 node_modules/fs-extra/docs/ensureDir.md create mode 100644 node_modules/fs-extra/docs/ensureFile-sync.md create mode 100644 node_modules/fs-extra/docs/ensureFile.md create mode 100644 node_modules/fs-extra/docs/ensureLink-sync.md create mode 100644 node_modules/fs-extra/docs/ensureLink.md create mode 100644 node_modules/fs-extra/docs/ensureSymlink-sync.md create mode 100644 node_modules/fs-extra/docs/ensureSymlink.md create mode 100644 node_modules/fs-extra/docs/move-sync.md create mode 100644 node_modules/fs-extra/docs/move.md create mode 100644 node_modules/fs-extra/docs/outputFile-sync.md create mode 100644 node_modules/fs-extra/docs/outputFile.md create mode 100644 node_modules/fs-extra/docs/outputJson-sync.md create mode 100644 node_modules/fs-extra/docs/outputJson.md create mode 100644 node_modules/fs-extra/docs/readJson-sync.md create mode 100644 node_modules/fs-extra/docs/readJson.md create mode 100644 node_modules/fs-extra/docs/remove-sync.md create mode 100644 node_modules/fs-extra/docs/remove.md create mode 100644 node_modules/fs-extra/docs/writeJson-sync.md create mode 100644 node_modules/fs-extra/docs/writeJson.md create mode 100644 node_modules/fs-extra/lib/copy-sync/copy-file-sync.js create mode 100644 node_modules/fs-extra/lib/copy-sync/copy-sync.js create mode 100644 node_modules/fs-extra/lib/copy-sync/index.js create mode 100644 node_modules/fs-extra/lib/copy/copy.js create mode 100644 node_modules/fs-extra/lib/copy/index.js create mode 100644 node_modules/fs-extra/lib/copy/ncp.js create mode 100644 node_modules/fs-extra/lib/empty/index.js create mode 100644 node_modules/fs-extra/lib/ensure/file.js create mode 100644 node_modules/fs-extra/lib/ensure/index.js create mode 100644 node_modules/fs-extra/lib/ensure/link.js create mode 100644 node_modules/fs-extra/lib/ensure/symlink-paths.js create mode 100644 node_modules/fs-extra/lib/ensure/symlink-type.js create mode 100644 node_modules/fs-extra/lib/ensure/symlink.js create mode 100644 node_modules/fs-extra/lib/index.js create mode 100644 node_modules/fs-extra/lib/json/index.js create mode 100644 node_modules/fs-extra/lib/json/jsonfile.js create mode 100644 node_modules/fs-extra/lib/json/output-json-sync.js create mode 100644 node_modules/fs-extra/lib/json/output-json.js create mode 100644 node_modules/fs-extra/lib/mkdirs/index.js create mode 100644 node_modules/fs-extra/lib/mkdirs/mkdirs-sync.js create mode 100644 node_modules/fs-extra/lib/mkdirs/mkdirs.js create mode 100644 node_modules/fs-extra/lib/mkdirs/win32.js create mode 100644 node_modules/fs-extra/lib/move-sync/index.js create mode 100644 node_modules/fs-extra/lib/move/index.js create mode 100644 node_modules/fs-extra/lib/output/index.js create mode 100644 node_modules/fs-extra/lib/remove/index.js create mode 100644 node_modules/fs-extra/lib/remove/rimraf.js create mode 100644 node_modules/fs-extra/lib/util/assign.js create mode 100644 node_modules/fs-extra/lib/util/utimes.js create mode 100644 node_modules/fs-extra/package.json create mode 100644 node_modules/fs.realpath/LICENSE create mode 100644 node_modules/fs.realpath/README.md create mode 100644 node_modules/fs.realpath/index.js create mode 100644 node_modules/fs.realpath/old.js create mode 100644 node_modules/fs.realpath/package.json create mode 100644 node_modules/glob/LICENSE create mode 100644 node_modules/glob/README.md create mode 100644 node_modules/glob/changelog.md create mode 100644 node_modules/glob/common.js create mode 100644 node_modules/glob/glob.js create mode 100644 node_modules/glob/package.json create mode 100644 node_modules/glob/sync.js create mode 100644 node_modules/graceful-fs/LICENSE create mode 100644 node_modules/graceful-fs/README.md create mode 100644 node_modules/graceful-fs/clone.js create mode 100644 node_modules/graceful-fs/graceful-fs.js create mode 100644 node_modules/graceful-fs/legacy-streams.js create mode 100644 node_modules/graceful-fs/package.json create mode 100644 node_modules/graceful-fs/polyfills.js create mode 100644 node_modules/inflight/LICENSE create mode 100644 node_modules/inflight/README.md create mode 100644 node_modules/inflight/inflight.js create mode 100644 node_modules/inflight/package.json create mode 100644 node_modules/inherits/LICENSE create mode 100644 node_modules/inherits/README.md create mode 100644 node_modules/inherits/inherits.js create mode 100644 node_modules/inherits/inherits_browser.js create mode 100644 node_modules/inherits/package.json create mode 100644 node_modules/isarray/.npmignore create mode 100644 node_modules/isarray/.travis.yml create mode 100644 node_modules/isarray/Makefile create mode 100644 node_modules/isarray/README.md create mode 100644 node_modules/isarray/component.json create mode 100644 node_modules/isarray/index.js create mode 100644 node_modules/isarray/package.json create mode 100644 node_modules/isarray/test.js create mode 100644 node_modules/jsonfile/.npmignore create mode 100644 node_modules/jsonfile/CHANGELOG.md create mode 100644 node_modules/jsonfile/LICENSE create mode 100644 node_modules/jsonfile/README.md create mode 100644 node_modules/jsonfile/appveyor.yml create mode 100644 node_modules/jsonfile/index.js create mode 100644 node_modules/jsonfile/package.json create mode 100644 node_modules/minimatch/LICENSE create mode 100644 node_modules/minimatch/README.md create mode 100644 node_modules/minimatch/minimatch.js create mode 100644 node_modules/minimatch/package.json create mode 100644 node_modules/node-latex/.prettierrc create mode 100644 node_modules/node-latex/index.d.ts create mode 100644 node_modules/node-latex/index.js create mode 100644 node_modules/node-latex/license create mode 100644 node_modules/node-latex/package.json create mode 100644 node_modules/node-latex/readme.md create mode 100644 node_modules/once/LICENSE create mode 100644 node_modules/once/README.md create mode 100644 node_modules/once/once.js create mode 100644 node_modules/once/package.json create mode 100644 node_modules/path-is-absolute/index.js create mode 100644 node_modules/path-is-absolute/license create mode 100644 node_modules/path-is-absolute/package.json create mode 100644 node_modules/path-is-absolute/readme.md create mode 100644 node_modules/prettier/LICENSE create mode 100644 node_modules/prettier/README.md create mode 100644 node_modules/prettier/bin-prettier.js create mode 100644 node_modules/prettier/doc.js create mode 100644 node_modules/prettier/index.js create mode 100644 node_modules/prettier/package.json create mode 100644 node_modules/prettier/parser-angular.js create mode 100644 node_modules/prettier/parser-babel.js create mode 100644 node_modules/prettier/parser-flow.js create mode 100644 node_modules/prettier/parser-glimmer.js create mode 100644 node_modules/prettier/parser-graphql.js create mode 100644 node_modules/prettier/parser-html.js create mode 100644 node_modules/prettier/parser-markdown.js create mode 100644 node_modules/prettier/parser-postcss.js create mode 100644 node_modules/prettier/parser-typescript.js create mode 100644 node_modules/prettier/parser-yaml.js create mode 100644 node_modules/prettier/standalone.js create mode 100644 node_modules/prettier/third-party.js create mode 100644 node_modules/process-nextick-args/index.js create mode 100644 node_modules/process-nextick-args/license.md create mode 100644 node_modules/process-nextick-args/package.json create mode 100644 node_modules/process-nextick-args/readme.md create mode 100644 node_modules/readable-stream/.travis.yml create mode 100644 node_modules/readable-stream/CONTRIBUTING.md create mode 100644 node_modules/readable-stream/GOVERNANCE.md create mode 100644 node_modules/readable-stream/LICENSE create mode 100644 node_modules/readable-stream/README.md create mode 100644 node_modules/readable-stream/doc/wg-meetings/2015-01-30.md create mode 100644 node_modules/readable-stream/duplex-browser.js create mode 100644 node_modules/readable-stream/duplex.js create mode 100644 node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 node_modules/readable-stream/lib/_stream_readable.js create mode 100644 node_modules/readable-stream/lib/_stream_transform.js create mode 100644 node_modules/readable-stream/lib/_stream_writable.js create mode 100644 node_modules/readable-stream/lib/internal/streams/BufferList.js create mode 100644 node_modules/readable-stream/lib/internal/streams/destroy.js create mode 100644 node_modules/readable-stream/lib/internal/streams/stream-browser.js create mode 100644 node_modules/readable-stream/lib/internal/streams/stream.js create mode 100644 node_modules/readable-stream/package.json create mode 100644 node_modules/readable-stream/passthrough.js create mode 100644 node_modules/readable-stream/readable-browser.js create mode 100644 node_modules/readable-stream/readable.js create mode 100644 node_modules/readable-stream/transform.js create mode 100644 node_modules/readable-stream/writable-browser.js create mode 100644 node_modules/readable-stream/writable.js create mode 100644 node_modules/rimraf/LICENSE create mode 100644 node_modules/rimraf/README.md create mode 100644 node_modules/rimraf/bin.js create mode 100644 node_modules/rimraf/package.json create mode 100644 node_modules/rimraf/rimraf.js create mode 100644 node_modules/safe-buffer/LICENSE create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json create mode 100644 node_modules/string-to-stream/LICENSE create mode 100644 node_modules/string-to-stream/README.md create mode 100644 node_modules/string-to-stream/index.js create mode 100644 node_modules/string-to-stream/package.json create mode 100644 node_modules/string_decoder/.travis.yml create mode 100644 node_modules/string_decoder/LICENSE create mode 100644 node_modules/string_decoder/README.md create mode 100644 node_modules/string_decoder/lib/string_decoder.js create mode 100644 node_modules/string_decoder/package.json create mode 100644 node_modules/temp/LICENSE create mode 100644 node_modules/temp/README.md create mode 100644 node_modules/temp/lib/temp.js create mode 100644 node_modules/temp/package.json create mode 100644 node_modules/through2/LICENSE.md create mode 100644 node_modules/through2/README.md create mode 100644 node_modules/through2/package.json create mode 100644 node_modules/through2/through2.js create mode 100644 node_modules/util-deprecate/History.md create mode 100644 node_modules/util-deprecate/LICENSE create mode 100644 node_modules/util-deprecate/README.md create mode 100644 node_modules/util-deprecate/browser.js create mode 100644 node_modules/util-deprecate/node.js create mode 100644 node_modules/util-deprecate/package.json create mode 100644 node_modules/wrappy/LICENSE create mode 100644 node_modules/wrappy/README.md create mode 100644 node_modules/wrappy/package.json create mode 100644 node_modules/wrappy/wrappy.js 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 out/zapisnice/zapisnica16_16.pdf create mode 100644 out/zapisnice/zapisnica17.pdf create mode 100644 out/zapisnice/zapisnica17_17.pdf create mode 100644 src/zapisnice/zapisnica16_16.tex create mode 100644 src/zapisnice/zapisnica17.tex create mode 100644 src/zapisnice/zapisnica17_17.tex diff --git a/node_modules/.bin/prettier b/node_modules/.bin/prettier new file mode 100644 index 0000000..7ae541e --- /dev/null +++ b/node_modules/.bin/prettier @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../prettier/bin-prettier.js" "$@" + ret=$? +else + node "$basedir/../prettier/bin-prettier.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/prettier.cmd b/node_modules/.bin/prettier.cmd new file mode 100644 index 0000000..0890963 --- /dev/null +++ b/node_modules/.bin/prettier.cmd @@ -0,0 +1,17 @@ +@ECHO off +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +"%_prog%" "%dp0%\..\prettier\bin-prettier.js" %* +ENDLOCAL +EXIT /b %errorlevel% +:find_dp0 +SET dp0=%~dp0 +EXIT /b diff --git a/node_modules/.bin/prettier.ps1 b/node_modules/.bin/prettier.ps1 new file mode 100644 index 0000000..7b06a86 --- /dev/null +++ b/node_modules/.bin/prettier.ps1 @@ -0,0 +1,18 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + & "$basedir/node$exe" "$basedir/../prettier/bin-prettier.js" $args + $ret=$LASTEXITCODE +} else { + & "node$exe" "$basedir/../prettier/bin-prettier.js" $args + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/rimraf b/node_modules/.bin/rimraf new file mode 100644 index 0000000..a3e9f71 --- /dev/null +++ b/node_modules/.bin/rimraf @@ -0,0 +1,15 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + "$basedir/node" "$basedir/../rimraf/bin.js" "$@" + ret=$? +else + node "$basedir/../rimraf/bin.js" "$@" + ret=$? +fi +exit $ret diff --git a/node_modules/.bin/rimraf.cmd b/node_modules/.bin/rimraf.cmd new file mode 100644 index 0000000..698f4ba --- /dev/null +++ b/node_modules/.bin/rimraf.cmd @@ -0,0 +1,17 @@ +@ECHO off +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +"%_prog%" "%dp0%\..\rimraf\bin.js" %* +ENDLOCAL +EXIT /b %errorlevel% +:find_dp0 +SET dp0=%~dp0 +EXIT /b diff --git a/node_modules/.bin/rimraf.ps1 b/node_modules/.bin/rimraf.ps1 new file mode 100644 index 0000000..a244a80 --- /dev/null +++ b/node_modules/.bin/rimraf.ps1 @@ -0,0 +1,18 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + & "$basedir/node$exe" "$basedir/../rimraf/bin.js" $args + $ret=$LASTEXITCODE +} else { + & "node$exe" "$basedir/../rimraf/bin.js" $args + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000..eaa5847 --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,16 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for Node.js (http://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node/v11. + +### Additional Details + * Last updated: Wed, 28 Oct 2020 18:55:46 GMT + * Dependencies: none + * Global values: `Buffer`, `NodeJS`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout` + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [DefinitelyTyped](https://github.com/DefinitelyTyped), [Alberto Schiabel](https://github.com/jkomyno), [Alexander T.](https://github.com/a-tarasyuk), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Bruno Scheufler](https://github.com/brunoscheufler), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Flarna](https://github.com/Flarna), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Hoàng Văn Khải](https://github.com/KSXGitHub), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nicolas Even](https://github.com/n-e), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Simon Schick](https://github.com/SimonSchick), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Zane Hannan AU](https://github.com/ZaneHannanAU), [Jeremie Rodriguez](https://github.com/jeremiergz), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Jordi Oliveras Rovira](https://github.com/j-oliveras), [Thanik Bhongbhibhat](https://github.com/bhongy), [Ivan Sieder](https://github.com/ivansieder), [Minh Son Nguyen](https://github.com/nguymin4), and [ExE Boss](https://github.com/ExE-Boss). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..0d6679c --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,91 @@ +declare module 'assert' { + function assert(value: any, message?: string | Error): asserts value; + namespace assert { + class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + message?: string; + actual?: any; + expected?: any; + operator?: string; + stackStartFn?: Function; + }); + } + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: any, + expected: any, + message?: string | Error, + operator?: string, + stackStartFn?: Function, + ): never; + function ok(value: any, message?: string | Error): asserts value; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + function strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; + function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; + function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + function throws(block: () => any, message?: string | Error): void; + function throws(block: () => any, error: RegExp | Function | Object | Error, message?: string | Error): void; + function doesNotThrow(block: () => any, message?: string | Error): void; + function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; + + function ifError(value: any): asserts value is null | undefined; + + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: RegExp | Function | Object | Error, + message?: string | Error, + ): Promise; + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: RegExp | Function, + message?: string | Error, + ): Promise; + + const strict: Omit< + typeof assert, + | 'strict' + | 'deepEqual' + | 'notDeepEqual' + | 'equal' + | 'notEqual' + | 'ok' + | 'strictEqual' + | 'deepStrictEqual' + | 'ifError' + > & { + (value: any, message?: string | Error): asserts value; + strict: typeof strict; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + ok(value: any, message?: string | Error): asserts value; + strictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; + deepStrictEqual(actual: any, expected: T, message?: string | Error): asserts actual is T; + ifError(value: any): asserts value is null | undefined; + }; + } + + export = assert; +} diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..2c77932 --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,144 @@ +/** + * Async Hooks module: https://nodejs.org/api/async_hooks.html + */ +declare module "async_hooks" { + /** + * Returns the asyncId of the current execution context. + */ + function executionAsyncId(): number; + + /** + * Returns the ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerAsyncId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: Object): void; + + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + + /** + * Registers functions to be called for different lifetime events of each async operation. + * @param options the callbacks to register + * @return an AsyncHooks instance used for disabling and enabling hooks + */ + function createHook(options: HookCallbacks): AsyncHook; + + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * Default: `executionAsyncId()` + */ + triggerAsyncId?: number; + + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * Default: `false` + */ + requireManualDestroy?: boolean; + } + + /** + * The class AsyncResource was designed to be extended by the embedder's async resources. + * Using this users can easily trigger the lifetime events of their own resources. + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since 9.3) + */ + constructor(type: string, triggerAsyncId?: number|AsyncResourceOptions); + + /** + * Call AsyncHooks before callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitBefore(): void; + + /** + * Call AsyncHooks after callbacks. + * @deprecated since 9.6 - Use asyncResource.runInAsyncScope() instead. + */ + emitAfter(): void; + + /** + * Call the provided function with the provided arguments in the + * execution context of the async resource. This will establish the + * context, trigger the AsyncHooks before callbacks, call the function, + * trigger the AsyncHooks after callbacks, and then restore the original + * execution context. + * @param fn The function to call in the execution context of this + * async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope(fn: (this: This, ...args: any[]) => Result, thisArg?: This, ...args: any[]): Result; + + /** + * Call AsyncHooks destroy callbacks. + */ + emitDestroy(): void; + + /** + * @return the unique ID assigned to this AsyncResource instance. + */ + asyncId(): number; + + /** + * @return the trigger ID for this AsyncResource instance. + */ + triggerAsyncId(): number; + } +} diff --git a/node_modules/@types/node/base.d.ts b/node_modules/@types/node/base.d.ts new file mode 100644 index 0000000..fa67179 --- /dev/null +++ b/node_modules/@types/node/base.d.ts @@ -0,0 +1,19 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.7. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.7/base.d.ts - Definitions specific to TypeScript 3.7 +// - ~/ts3.7/index.d.ts - Definitions specific to TypeScript 3.7 with assert pulled in + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// + +// TypeScript 3.7-specific augmentations: +/// diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..0fe668b --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,16 @@ +declare module "buffer" { + export const INSPECT_MAX_BYTES: number; + const BuffType: typeof Buffer; + + export type TranscodeEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "latin1" | "binary"; + + export function transcode(source: Buffer | Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + + export const SlowBuffer: { + /** @deprecated since v6.0.0, use Buffer.allocUnsafeSlow() */ + new(size: number): Buffer; + prototype: Buffer; + }; + + export { BuffType as Buffer }; +} diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..eb5d92c --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,367 @@ +declare module "child_process" { + import * as events from "events"; + import * as net from "net"; + import { Writable, Readable, Stream, Pipe } from "stream"; + + interface ChildProcess extends events.EventEmitter { + stdin: Writable | null; + stdout: Readable | null; + stderr: Readable | null; + readonly channel?: Pipe | null; + readonly stdio: [ + Writable | null, // stdin + Readable | null, // stdout + Readable | null, // stderr + Readable | Writable | null | undefined, // extra + Readable | Writable | null | undefined // extra + ]; + readonly killed: boolean; + readonly pid: number; + readonly connected: boolean; + kill(signal?: string): void; + send(message: any, callback?: (error: Error | null) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, callback?: (error: Error | null) => void): boolean; + send(message: any, sendHandle?: net.Socket | net.Server, options?: MessageOptions, callback?: (error: Error | null) => void): boolean; + disconnect(): void; + unref(): void; + ref(): void; + + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number, signal: string) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number, signal: string): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: string | null): boolean; + emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number, signal: string) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number, signal: string) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number, signal: string) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; + prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; + } + + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, // stdin + Readable, // stdout + Readable, // stderr + Readable | Writable | null | undefined, // extra, no modification + Readable | Writable | null | undefined // extra, no modification + ]; + } + + interface MessageOptions { + keepOpen?: boolean; + } + + type StdioOptions = "pipe" | "ignore" | "inherit" | Array<("pipe" | "ipc" | "ignore" | "inherit" | Stream | number | null | undefined)>; + + interface ProcessEnvOptions { + uid?: number; + gid?: number; + cwd?: string; + env?: NodeJS.ProcessEnv; + } + + interface CommonOptions extends ProcessEnvOptions { + /** + * @default true + */ + windowsHide?: boolean; + /** + * @default 0 + */ + timeout?: number; + } + + interface SpawnOptions extends CommonOptions { + argv0?: string; + stdio?: StdioOptions; + detached?: boolean; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + } + + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: 'pipe' | Array; + } + + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, options: SpawnOptions): ChildProcess; + function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn(command: string, args: ReadonlyArray, options: SpawnOptions): ChildProcess; + + interface ExecOptions extends CommonOptions { + shell?: string; + maxBuffer?: number; + killSignal?: string; + } + + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: string | null; // specify `null`. + } + + interface ExecException extends Error { + cmd?: string; + killed?: boolean; + code?: number; + signal?: string; + } + + // no `options` definitely means stdout/stderr are `string`. + function exec(command: string, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec(command: string, options: ExecOptions, callback?: (error: ExecException | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: ({ encoding?: string | null } & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exec { + function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ExecFileOptions extends CommonOptions { + maxBuffer?: number; + killSignal?: string; + windowsVerbatimArguments?: boolean; + shell?: boolean | string; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: 'buffer' | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: string; + } + + function execFile(file: string): ChildProcess; + function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + function execFile(file: string, args?: ReadonlyArray | null): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + + // no `options` definitely means stdout/stderr are `string`. + function execFile(file: string, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile(file: string, options: ExecFileOptionsWithBufferEncoding, callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: Error | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptionsWithStringEncoding, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: Error | null, stdout: string, stderr: string) => void, + ): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile(file: string, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + function execFile(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions, callback: (error: Error | null, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + function execFile( + file: string, + args: ReadonlyArray | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + callback: ((error: Error | null, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null, + ): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace execFile { + function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithBufferEncoding): Promise<{ stdout: Buffer, stderr: Buffer }>; + function __promisify__(file: string, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithStringEncoding): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptionsWithOtherEncoding): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, args: ReadonlyArray | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + function __promisify__( + file: string, + args: ReadonlyArray | undefined | null, + options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, + ): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + + interface ForkOptions extends ProcessEnvOptions { + execPath?: string; + execArgv?: string[]; + silent?: boolean; + stdio?: StdioOptions; + detached?: boolean; + windowsVerbatimArguments?: boolean; + } + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: ReadonlyArray, options?: ForkOptions): ChildProcess; + + interface SpawnSyncOptions extends CommonOptions { + argv0?: string; // Not specified in the docs + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + windowsVerbatimArguments?: boolean; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding: string; // specify `null`. + } + interface SpawnSyncReturns { + pid: number; + output: string[]; + stdout: T; + stderr: T; + status: number | null; + signal: string | null; + error?: Error; + } + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, args?: ReadonlyArray, options?: SpawnSyncOptions): SpawnSyncReturns; + + interface ExecSyncOptions extends CommonOptions { + input?: string | Buffer | Uint8Array; + stdio?: StdioOptions; + shell?: string; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding: string; // specify `null`. + } + function execSync(command: string): Buffer; + function execSync(command: string, options?: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options?: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): Buffer; + + interface ExecFileSyncOptions extends CommonOptions { + input?: string | Buffer | NodeJS.TypedArray | DataView; + stdio?: StdioOptions; + killSignal?: string | number; + maxBuffer?: number; + encoding?: string; + shell?: boolean | string; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding: string; // specify `null`. + } + function execFileSync(command: string): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, options?: ExecFileSyncOptions): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(command: string, args?: ReadonlyArray, options?: ExecFileSyncOptions): Buffer; +} diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..43340ff --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,260 @@ +declare module "cluster" { + import * as child from "child_process"; + import * as events from "events"; + import * as net from "net"; + + // interfaces + interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv + exec?: string; + args?: string[]; + silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + inspectPort?: number | (() => number); + } + + interface Address { + address: string; + port: number; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" + } + + class Worker extends events.EventEmitter { + id: number; + process: child.ChildProcess; + send(message: any, sendHandle?: any, callback?: (error: Error | null) => void): boolean; + kill(signal?: string): void; + destroy(signal?: string): void; + disconnect(): void; + isConnected(): boolean; + isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + + interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: () => void): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSettings): void; + worker?: Worker; + workers?: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + + function disconnect(callback?: () => void): void; + function fork(env?: any): Worker; + const isMaster: boolean; + const isWorker: boolean; + // TODO: cluster.schedulingPolicy + const settings: ClusterSettings; + function setupMaster(settings?: ClusterSettings): void; + const worker: Worker; + const workers: { + [index: string]: Worker | undefined + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + function addListener(event: string, listener: (...args: any[]) => void): Cluster; + function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + function addListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function emit(event: string | symbol, ...args: any[]): boolean; + function emit(event: "disconnect", worker: Worker): boolean; + function emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + function emit(event: "fork", worker: Worker): boolean; + function emit(event: "listening", worker: Worker, address: Address): boolean; + function emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + function emit(event: "online", worker: Worker): boolean; + function emit(event: "setup", settings: ClusterSettings): boolean; + + function on(event: string, listener: (...args: any[]) => void): Cluster; + function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function on(event: "fork", listener: (worker: Worker) => void): Cluster; + function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function on(event: "online", listener: (worker: Worker) => void): Cluster; + function on(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function once(event: string, listener: (...args: any[]) => void): Cluster; + function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function once(event: "fork", listener: (worker: Worker) => void): Cluster; + function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + function once(event: "online", listener: (worker: Worker) => void): Cluster; + function once(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function removeListener(event: string, listener: (...args: any[]) => void): Cluster; + function removeAllListeners(event?: string): Cluster; + function setMaxListeners(n: number): Cluster; + function getMaxListeners(): number; + function listeners(event: string): Function[]; + function listenerCount(type: string): number; + + function prependListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function prependOnceListener(event: string, listener: (...args: any[]) => void): Cluster; + function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + // the handle is a net.Socket or net.Server object, or undefined. + function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; + function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + function prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): Cluster; + + function eventNames(): string[]; +} diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..d30d13f --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,3 @@ +declare module "console" { + export = console; +} diff --git a/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..5144887 --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,315 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module "constants" { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGHUP` instead. */ + const SIGHUP: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGINT` instead. */ + const SIGINT: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGILL` instead. */ + const SIGILL: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGABRT` instead. */ + const SIGABRT: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGFPE` instead. */ + const SIGFPE: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGKILL` instead. */ + const SIGKILL: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGSEGV` instead. */ + const SIGSEGV: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGTERM` instead. */ + const SIGTERM: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGBREAK` instead. */ + const SIGBREAK: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGWINCH` instead. */ + const SIGWINCH: number; + const SSL_OP_ALL: number; + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + const SSL_OP_CISCO_ANYCONNECT: number; + const SSL_OP_COOKIE_EXCHANGE: number; + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + const SSL_OP_EPHEMERAL_RSA: number; + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + const SSL_OP_SINGLE_DH_USE: number; + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_ECDH: number; + const ENGINE_METHOD_ECDSA: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_STORE: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const NPN_ENABLED: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + const O_RDONLY: number; + const O_WRONLY: number; + const O_RDWR: number; + const S_IFMT: number; + const S_IFREG: number; + const S_IFDIR: number; + const S_IFCHR: number; + const S_IFBLK: number; + const S_IFIFO: number; + const S_IFSOCK: number; + const S_IRWXU: number; + const S_IRUSR: number; + const S_IWUSR: number; + const S_IXUSR: number; + const S_IRWXG: number; + const S_IRGRP: number; + const S_IWGRP: number; + const S_IXGRP: number; + const S_IRWXO: number; + const S_IROTH: number; + const S_IWOTH: number; + const S_IXOTH: number; + const S_IFLNK: number; + const O_CREAT: number; + const O_EXCL: number; + const O_NOCTTY: number; + const O_DIRECTORY: number; + const O_NOATIME: number; + const O_NOFOLLOW: number; + const O_SYNC: number; + const O_DSYNC: number; + const O_SYMLINK: number; + const O_DIRECT: number; + const O_NONBLOCK: number; + const O_TRUNC: number; + const O_APPEND: number; + const F_OK: number; + const R_OK: number; + const W_OK: number; + const X_OK: number; + const COPYFILE_EXCL: number; + const COPYFILE_FICLONE: number; + const COPYFILE_FICLONE_FORCE: number; + const UV_UDP_REUSEADDR: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGQUIT` instead. */ + const SIGQUIT: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGTRAP` instead. */ + const SIGTRAP: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGIOT` instead. */ + const SIGIOT: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGBUS` instead. */ + const SIGBUS: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGUSR1` instead. */ + const SIGUSR1: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGUSR2` instead. */ + const SIGUSR2: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGPIPE` instead. */ + const SIGPIPE: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGALRM` instead. */ + const SIGALRM: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGCHLD` instead. */ + const SIGCHLD: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGSTKFLT` instead. */ + const SIGSTKFLT: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGCONT` instead. */ + const SIGCONT: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGSTOP` instead. */ + const SIGSTOP: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGTSTP` instead. */ + const SIGTSTP: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGTTIN` instead. */ + const SIGTTIN: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGTTOU` instead. */ + const SIGTTOU: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGURG` instead. */ + const SIGURG: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGXCPU` instead. */ + const SIGXCPU: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGXFSZ` instead. */ + const SIGXFSZ: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGVTALRM` instead. */ + const SIGVTALRM: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGPROF` instead. */ + const SIGPROF: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGIO` instead. */ + const SIGIO: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGPOLL` instead. */ + const SIGPOLL: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGPWR` instead. */ + const SIGPWR: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGSYS` instead. */ + const SIGSYS: number; + /** @deprecated since v6.3.0 - use `os.constants.signals.SIGUNUSED` instead. */ + const SIGUNUSED: number; + const defaultCoreCipherList: string; + const defaultCipherList: string; + const ENGINE_METHOD_RSA: number; + const ALPN_ENABLED: number; +} diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..d9ae86f --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,569 @@ +declare module "crypto" { + import * as stream from "stream"; + + interface Certificate { + exportChallenge(spkac: BinaryLike): Buffer; + exportPublicKey(spkac: BinaryLike): Buffer; + verifySpkac(spkac: Binary): boolean; + } + const Certificate: { + new(): Certificate; + (): Certificate; + }; + + namespace constants { // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants + const OPENSSL_VERSION_NUMBER: number; + + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */ + const SSL_OP_EPHEMERAL_RSA: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number; + const SSL_OP_MICROSOFT_SESS_ID_BUG: number; + /** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */ + const SSL_OP_MSIE_SSLV2_RSA_PADDING: number; + const SSL_OP_NETSCAPE_CA_DN_BUG: number; + const SSL_OP_NETSCAPE_CHALLENGE_BUG: number; + const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number; + const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + const SSL_OP_NO_SSLv2: number; + const SSL_OP_NO_SSLv3: number; + const SSL_OP_NO_TICKET: number; + const SSL_OP_NO_TLSv1: number; + const SSL_OP_NO_TLSv1_1: number; + const SSL_OP_NO_TLSv1_2: number; + const SSL_OP_PKCS1_CHECK_1: number; + const SSL_OP_PKCS1_CHECK_2: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */ + const SSL_OP_SINGLE_DH_USE: number; + /** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */ + const SSL_OP_SINGLE_ECDH_USE: number; + const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number; + const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number; + const SSL_OP_TLS_BLOCK_PADDING_BUG: number; + const SSL_OP_TLS_D5_BUG: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + + const ALPN_ENABLED: number; + + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + + /** @deprecated since v10.0.0 */ + const fips: boolean; + + function createHash(algorithm: string, options?: stream.TransformOptions): Hash; + function createHmac(algorithm: string, key: BinaryLike, options?: stream.TransformOptions): Hmac; + + type Utf8AsciiLatin1Encoding = "utf8" | "ascii" | "latin1"; + type HexBase64Latin1Encoding = "latin1" | "hex" | "base64"; + type Utf8AsciiBinaryEncoding = "utf8" | "ascii" | "binary"; + type HexBase64BinaryEncoding = "binary" | "base64" | "hex"; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + + class Hash extends stream.Transform { + private constructor(); + update(data: BinaryLike): Hash; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hash; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + class Hmac extends stream.Transform { + private constructor(); + update(data: BinaryLike): Hmac; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Hmac; + digest(): Buffer; + digest(encoding: HexBase64Latin1Encoding): string; + } + + export type KeyObjectType = 'secret' | 'public' | 'private'; + + interface KeyExportOptions { + type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1'; + format: T; + cipher?: string; + passphrase?: string | Buffer; + } + + class KeyObject { + private constructor(); + asymmetricKeyType?: KeyType; + export(options: KeyExportOptions<'pem'>): string | Buffer; + export(options?: KeyExportOptions<'der'>): Buffer; + symmetricSize?: number; + type: KeyObjectType; + } + + type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm'; + type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm'; + + type Binary = Buffer | NodeJS.TypedArray | DataView; + type BinaryLike = string | Binary; + + type CipherKey = BinaryLike | KeyObject; + + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number; + } + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use createCipheriv() */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike | null, + options: CipherCCMOptions + ): CipherCCM; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike | null, + options?: CipherGCMOptions + ): CipherGCM; + function createCipheriv( + algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions + ): Cipher; + + class Cipher extends stream.Transform { + private constructor(); + update(data: BinaryLike): Buffer; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding): Buffer; + update(data: Binary, input_encoding: undefined, output_encoding: HexBase64BinaryEncoding): string; + update(data: string, input_encoding: Utf8AsciiBinaryEncoding | undefined, output_encoding: HexBase64BinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // getAuthTag(): Buffer; + // setAAD(buffer: Buffer): this; // docs only say buffer + } + interface CipherCCM extends Cipher { + setAAD(buffer: Buffer, options: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD(buffer: Buffer, options?: { plaintextLength: number }): this; + getAuthTag(): Buffer; + } + /** @deprecated since v10.0.0 use createDecipheriv() */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use createDecipheriv() */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use createDecipheriv() */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + + function createDecipheriv( + algorithm: CipherCCMTypes, + key: BinaryLike, + iv: BinaryLike | null, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: BinaryLike, + iv: BinaryLike | null, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv(algorithm: string, key: BinaryLike, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher; + + class Decipher extends stream.Transform { + private constructor(); + update(data: Binary): Buffer; + update(data: string, input_encoding: HexBase64BinaryEncoding): Buffer; + update(data: Binary, input_encoding: undefined, output_encoding: Utf8AsciiBinaryEncoding): string; + update(data: string, input_encoding: HexBase64BinaryEncoding | undefined, output_encoding: Utf8AsciiBinaryEncoding): string; + final(): Buffer; + final(output_encoding: string): string; + setAutoPadding(auto_padding?: boolean): this; + // setAuthTag(tag: Binary): this; + // setAAD(buffer: Binary): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: Binary): this; + setAAD(buffer: Binary, options: { plaintextLength: number }): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: Binary): this; + setAAD(buffer: Binary, options?: { plaintextLength: number }): this; + } + + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat; + type?: 'pkcs1' | 'pkcs8' | 'sec1'; + passphrase?: string | Buffer; + } + + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat; + type?: 'pkcs1' | 'spki'; + } + + function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject; + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject; + function createSecretKey(key: Buffer): KeyObject; + + function createSign(algorithm: string, options?: stream.WritableOptions): Signer; + + interface SignPrivateKeyInput extends PrivateKeyInput { + padding?: number; + saltLength?: number; + } + + type KeyLike = string | Buffer | KeyObject; + + class Signer extends stream.Writable { + private constructor(); + + update(data: BinaryLike): Signer; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; + sign(private_key: SignPrivateKeyInput | KeyLike): Buffer; + sign(private_key: SignPrivateKeyInput | KeyLike, output_format: HexBase64Latin1Encoding): string; + } + + function createVerify(algorith: string, options?: stream.WritableOptions): Verify; + class Verify extends stream.Writable { + private constructor(); + + update(data: BinaryLike): Verify; + update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Verify; + verify(object: Object | KeyLike, signature: Binary): boolean; + verify(object: Object | KeyLike, signature: string, signature_format?: HexBase64Latin1Encoding): boolean; + // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format + // The signature field accepts a TypedArray type, but it is only available starting ES2017 + } + function createDiffieHellman(prime_length: number, generator?: number | Binary): DiffieHellman; + function createDiffieHellman(prime: Binary): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: number | Binary): DiffieHellman; + function createDiffieHellman(prime: string, prime_encoding: HexBase64Latin1Encoding, generator: string, generator_encoding: HexBase64Latin1Encoding): DiffieHellman; + class DiffieHellman { + private constructor(); + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: Binary): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Binary, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrime(): Buffer; + getPrime(encoding: HexBase64Latin1Encoding): string; + getGenerator(): Buffer; + getGenerator(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + setPublicKey(public_key: Binary): void; + setPublicKey(public_key: string, encoding: string): void; + setPrivateKey(private_key: Binary): void; + setPrivateKey(private_key: string, encoding: string): void; + verifyError: number; + } + function getDiffieHellman(group_name: string): DiffieHellman; + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => any, + ): void; + function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer; + + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + + function randomFillSync(buffer: T, offset?: number, size?: number): T; + function randomFill(buffer: T, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void; + function randomFill(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void; + + interface ScryptOptions { + N?: number; + r?: number; + p?: number; + maxmem?: number; + } + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + + interface RsaPublicKey { + key: KeyLike; + padding?: number; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string; + padding?: number; + } + function publicEncrypt(public_key: RsaPublicKey | KeyLike, buffer: Binary): Buffer; + function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: Binary): Buffer; + function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: Binary): Buffer; + function publicDecrypt(public_key: RsaPublicKey | KeyLike, buffer: Binary): Buffer; + function getCiphers(): string[]; + function getCurves(): string[]; + function getFips(): 1 | 0; + function getHashes(): string[]; + class ECDH { + private constructor(); + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: HexBase64Latin1Encoding, + outputEncoding?: "latin1" | "hex" | "base64", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + generateKeys(): Buffer; + generateKeys(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + computeSecret(other_public_key: Binary): Buffer; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding): Buffer; + computeSecret(other_public_key: Binary, output_encoding: HexBase64Latin1Encoding): string; + computeSecret(other_public_key: string, input_encoding: HexBase64Latin1Encoding, output_encoding: HexBase64Latin1Encoding): string; + getPrivateKey(): Buffer; + getPrivateKey(encoding: HexBase64Latin1Encoding): string; + getPublicKey(): Buffer; + getPublicKey(encoding: HexBase64Latin1Encoding, format?: ECDHKeyFormat): string; + setPrivateKey(private_key: Binary): void; + setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; + } + function createECDH(curve_name: string): ECDH; + function timingSafeEqual(a: Binary, b: Binary): boolean; + /** @deprecated since v10.0.0 */ + const DEFAULT_ENCODING: string; + + export type KeyType = 'rsa' | 'dsa' | 'ec'; + export type KeyFormat = 'pem' | 'der'; + + interface BasePrivateKeyEncodingOptions { + format: T; + cipher: string; + passphrase: string; + } + + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + } + + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + + /** + * @default 0x10001 + */ + publicExponent?: number; + } + + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + + /** + * Size of q in bits + */ + divisorLength: number; + } + + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void; + + namespace generateKeyPair { + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + } +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..8f0e798 --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,102 @@ +declare module "dgram" { + import { AddressInfo } from "net"; + import * as dns from "dns"; + import * as events from "events"; + + interface RemoteInfo { + address: string; + family: 'IPv4' | 'IPv6'; + port: number; + size: number; + } + + interface BindOptions { + port: number; + address?: string; + exclusive?: boolean; + } + + type SocketType = "udp4" | "udp6"; + + interface SocketOptions { + type: SocketType; + reuseAddr?: boolean; + /** + * @default false + */ + ipv6Only?: boolean; + recvBufferSize?: number; + sendBufferSize?: number; + lookup?: (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + } + + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + + class Socket extends events.EventEmitter { + send(msg: Buffer | string | Uint8Array | ReadonlyArray, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + send(msg: Buffer | string | Uint8Array, offset: number, length: number, port: number, address?: string, callback?: (error: Error | null, bytes: number) => void): void; + bind(port?: number, address?: string, callback?: () => void): void; + bind(port?: number, callback?: () => void): void; + bind(callback?: () => void): void; + bind(options: BindOptions, callback?: () => void): void; + close(callback?: () => void): void; + address(): AddressInfo | string; + setBroadcast(flag: boolean): void; + setTTL(ttl: number): void; + setMulticastTTL(ttl: number): void; + setMulticastInterface(multicastInterface: string): void; + setMulticastLoopback(flag: boolean): void; + addMembership(multicastAddress: string, multicastInterface?: string): void; + dropMembership(multicastAddress: string, multicastInterface?: string): void; + ref(): this; + unref(): this; + setRecvBufferSize(size: number): void; + setSendBufferSize(size: number): void; + getRecvBufferSize(): number; + getSendBufferSize(): number; + + /** + * events.EventEmitter + * 1. close + * 2. error + * 3. listening + * 4. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + } +} diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..879d690 --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,366 @@ +declare module "dns" { + // Supported getaddrinfo flags. + const ADDRCONFIG: number; + const V4MAPPED: number; + + interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + verbatim?: boolean; + } + + interface LookupOneOptions extends LookupOptions { + all?: false; + } + + interface LookupAllOptions extends LookupOptions { + all: true; + } + + interface LookupAddress { + address: string; + family: number; + } + + function lookup(hostname: string, family: number, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + function lookup(hostname: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void): void; + function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void): void; + function lookup(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; + function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; + } + + function lookupService(address: string, port: number, callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void): void; + + namespace lookupService { + function __promisify__(address: string, port: number): Promise<{ hostname: string, service: string }>; + } + + interface ResolveOptions { + ttl: boolean; + } + + interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + + interface RecordWithTtl { + address: string; + ttl: number; + } + + /** @deprecated Use AnyARecord or AnyAaaaRecord instead. */ + type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + + interface AnyARecord extends RecordWithTtl { + type: "A"; + } + + interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + + interface MxRecord { + priority: number; + exchange: string; + } + + interface AnyMxRecord extends MxRecord { + type: "MX"; + } + + interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + + interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + + interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + + interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + + interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + + interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + + interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + + interface AnyNsRecord { + type: "NS"; + value: string; + } + + interface AnyPtrRecord { + type: "PTR"; + value: string; + } + + interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + + type AnyRecord = AnyARecord | + AnyAaaaRecord | + AnyCnameRecord | + AnyMxRecord | + AnyNaptrRecord | + AnyNsRecord | + AnyPtrRecord | + AnySoaRecord | + AnySrvRecord | + AnyTxtRecord; + + function resolve(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "A", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "AAAA", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "ANY", callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + function resolve(hostname: string, rrtype: "CNAME", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "MX", callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NAPTR", callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + function resolve(hostname: string, rrtype: "NS", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "PTR", callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + function resolve(hostname: string, rrtype: "SOA", callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void): void; + function resolve(hostname: string, rrtype: "SRV", callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + function resolve( + hostname: string, + rrtype: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__(hostname: string, rrtype: string): Promise; + } + + function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void): void; + function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + + function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + + function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void): void; + namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + + function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void): void; + namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + + function resolveNs(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + + function resolvePtr(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void): void; + namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + + function resolveSoa(hostname: string, callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void): void; + namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + + function resolveSrv(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void): void; + namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + + function resolveTxt(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void): void; + namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + + function resolveAny(hostname: string, callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void): void; + namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + + function reverse(ip: string, callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void): void; + function setServers(servers: ReadonlyArray): void; + function getServers(): string[]; + + // Error codes + const NODATA: string; + const FORMERR: string; + const SERVFAIL: string; + const NOTFOUND: string; + const NOTIMP: string; + const REFUSED: string; + const BADQUERY: string; + const BADNAME: string; + const BADFAMILY: string; + const BADRESP: string; + const CONNREFUSED: string; + const TIMEOUT: string; + const EOF: string; + const FILE: string; + const NOMEM: string; + const DESTRUCTION: string; + const BADSTR: string; + const BADFLAGS: string; + const NONAME: string; + const BADHINTS: string; + const NOTINITIALIZED: string; + const LOADIPHLPAPI: string; + const ADDRGETNETWORKPARAMS: string; + const CANCELLED: string; + + class Resolver { + getServers: typeof getServers; + setServers: typeof setServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + cancel(): void; + } + + namespace promises { + function getServers(): string[]; + + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + + function lookupService(address: string, port: number): Promise<{ hostname: string, service: string }>; + + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A"): Promise; + function resolve(hostname: string, rrtype: "AAAA"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CNAME"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "NS"): Promise; + function resolve(hostname: string, rrtype: "PTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve(hostname: string, rrtype: string): Promise; + + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + + function resolveAny(hostname: string): Promise; + + function resolveCname(hostname: string): Promise; + + function resolveMx(hostname: string): Promise; + + function resolveNaptr(hostname: string): Promise; + + function resolveNs(hostname: string): Promise; + + function resolvePtr(hostname: string): Promise; + + function resolveSoa(hostname: string): Promise; + + function resolveSrv(hostname: string): Promise; + + function resolveTxt(hostname: string): Promise; + + function reverse(ip: string): Promise; + + function setServers(servers: ReadonlyArray): void; + + class Resolver { + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + setServers: typeof setServers; + } + } +} diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..45e388c --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,16 @@ +declare module "domain" { + import * as events from "events"; + + class Domain extends events.EventEmitter implements NodeJS.Domain { + run(fn: (...args: any[]) => T, ...args: any[]): T; + add(emitter: events.EventEmitter | NodeJS.Timer): void; + remove(emitter: events.EventEmitter | NodeJS.Timer): void; + bind(cb: T): T; + intercept(cb: T): T; + members: Array; + enter(): void; + exit(): void; + } + + function create(): Domain; +} diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..71684f4 --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,39 @@ +declare module "events" { + class internal extends NodeJS.EventEmitter { } + + interface NodeEventTarget { + once(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface DOMEventTarget { + addEventListener(event: string, listener: (...args: any[]) => void, opts?: { once: boolean }): any; + } + + namespace internal { + function once(emitter: NodeEventTarget, event: string | symbol): Promise; + function once(emitter: DOMEventTarget, event: string): Promise; + class EventEmitter extends internal { + /** @deprecated since v4.0.0 */ + static listenerCount(emitter: EventEmitter, event: string | symbol): number; + static defaultMaxListeners: number; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + eventNames(): Array; + listenerCount(type: string | symbol): number; + } + } + + export = internal; +} diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..f37332e --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,2297 @@ +declare module "fs" { + import * as stream from "stream"; + import * as events from "events"; + import { URL } from "url"; + + /** + * Valid types for path values in "fs". + */ + type PathLike = string | Buffer | URL; + + type BinaryData = Buffer | DataView | NodeJS.TypedArray; + class Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atimeMs: number; + mtimeMs: number; + ctimeMs: number; + birthtimeMs: number; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + + class Dirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; + } + + interface FSWatcher extends events.EventEmitter { + close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + + class ReadStream extends stream.Readable { + close(): void; + bytesRead: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + class WriteStream extends stream.Writable { + close(): void; + bytesWritten: number; + path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + } + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function fchownSync(fd: number, uid: number, gid: number): void; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: string | number): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function fstatSync(fd: number): Stats; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstatSync(path: PathLike): Stats; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + + /** + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function linkSync(existingPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + + type Type = "dir" | "file" | "junction"; + } + + /** + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void + ): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + function native( + path: PathLike, + options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void + ): void; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void; + function native(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void; + function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + namespace realpathSync { + function native(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + function native(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + function native(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + } + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlinkSync(path: PathLike): void; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdirSync(path: PathLike): void; + + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777. + */ + mode?: number | string; + } + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer", callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: { encoding?: string | null; withFileTypes?: false } | string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer"; withFileTypes?: false }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdirSync(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): string[] | Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdirSync(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Dirent[]; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function close(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function closeSync(fd: number): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function fsyncSync(fd: number): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void + ): void; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write( + fd: number, + string: any, + position: number | undefined | null, + encoding: string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + */ + function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function writeSync(fd: number, buffer: BinaryData, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function readSync(fd: number, buffer: BinaryData, offset: number, length: number, position: number | null): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException | null, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | number, + options: { encoding?: string | null; flag?: string; } | string | undefined | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + type WriteFileOptions = { encoding?: string | null; mode?: number | string; flag?: string; } | string | null; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__(path: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFileSync(path: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(file: PathLike | number, data: any, options: WriteFileOptions, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__(file: PathLike | number, data: any, options?: WriteFileOptions): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFileSync(file: PathLike | number, data: any, options?: WriteFileOptions): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, + listener?: (event: string, filename: string) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, + listener?: (event: string, filename: string | Buffer) => void, + ): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function existsSync(path: PathLike): boolean; + + namespace constants { + // File Access Constants + + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + + // File Copy Constants + + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + + // File Open Constants + + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + + // File Type Constants + + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + + // File Mode Constants + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException | null) => void): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createReadStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + end?: number; + highWaterMark?: number; + }): ReadStream; + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function createWriteStream(path: PathLike, options?: string | { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + autoClose?: boolean; + start?: number; + highWaterMark?: number; + }): WriteStream; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function fdatasyncSync(fd: number): void; + + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + */ + function copyFile(src: PathLike, dest: PathLike, callback: (err: NodeJS.ErrnoException | null) => void): void; + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An integer that specifies the behavior of the copy operation. The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags: number, callback: (err: NodeJS.ErrnoException | null) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + namespace copyFile { + /** + * Asynchronously copies src to dest. By default, dest is overwritten if it already exists. + * No arguments other than a possible exception are given to the callback function. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, + * which causes the copy operation to fail if dest already exists. + */ + function __promisify__(src: PathLike, dst: PathLike, flags?: number): Promise; + } + + /** + * Synchronously copies src to dest. By default, dest is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. + * The only supported flag is fs.constants.COPYFILE_EXCL, which causes the copy operation to fail if dest already exists. + */ + function copyFileSync(src: PathLike, dest: PathLike, flags?: number): void; + + namespace promises { + interface FileHandle { + /** + * Gets the file descriptor for this file handle. + */ + readonly fd: number; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for appending. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + appendFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + */ + chown(uid: number, gid: number): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + chmod(mode: string | number): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + */ + datasync(): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + */ + sync(): Promise; + + /** + * Asynchronously reads data from the file. + * The `FileHandle` must have been opened for reading. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + read(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile(options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + */ + stat(): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param len If not specified, defaults to `0`. + */ + truncate(len?: number): Promise; + + /** + * Asynchronously change file timestamps of the file. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously writes `buffer` to the file. + * The `FileHandle` must have been opened for writing. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + write(buffer: TBuffer, offset?: number | null, length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + write(data: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for writing. + * It is unsafe to call `writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + writeFile(data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronous close(2) - close a `FileHandle`. + */ + close(): Promise; + } + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function access(path: PathLike, mode?: number): Promise; + + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it already exists. + * Node.js makes no guarantees about the atomicity of the copy operation. + * If an error occurs after the destination file has been opened for writing, Node.js will attempt + * to remove the destination. + * @param src A path to the source file. + * @param dest A path to the destination file. + * @param flags An optional integer that specifies the behavior of the copy operation. The only + * supported flag is `fs.constants.COPYFILE_EXCL`, which causes the copy operation to fail if + * `dest` already exists. + */ + function copyFile(src: PathLike, dest: PathLike, flags?: number): Promise; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not + * supplied, defaults to `0o666`. + */ + function open(path: PathLike, flags: string | number, mode?: string | number): Promise; + + /** + * Asynchronously reads data from the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If + * `null`, data will be read from the current position. + */ + function read( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ bytesRead: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `buffer` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param buffer The buffer that the data will be written to. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function write( + handle: FileHandle, + buffer: TBuffer, + offset?: number | null, + length?: number | null, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied `FileHandle`. + * It is unsafe to call `fsPromises.write()` multiple times on the same file without waiting for the `Promise` + * to be resolved (or rejected). For this scenario, `fs.createWriteStream` is strongly recommended. + * @param handle A `FileHandle`. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function write(handle: FileHandle, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function truncate(path: PathLike, len?: number): Promise; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param handle A `FileHandle`. + * @param len If not specified, defaults to `0`. + */ + function ftruncate(handle: FileHandle, len?: number): Promise; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function rmdir(path: PathLike): Promise; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param handle A `FileHandle`. + */ + function fdatasync(handle: FileHandle): Promise; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param handle A `FileHandle`. + */ + function fsync(handle: FileHandle): Promise; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: BufferEncoding | null; withFileTypes?: false } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options: { encoding: "buffer"; withFileTypes?: false } | "buffer"): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir(path: PathLike, options?: { encoding?: string | null; withFileTypes?: false } | string | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir(path: PathLike, options: { encoding?: string | null; withFileTypes: true }): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + + /** + * Asynchronous fstat(2) - Get file status. + * @param handle A `FileHandle`. + */ + function fstat(handle: FileHandle): Promise; + + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lstat(path: PathLike): Promise; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function stat(path: PathLike): Promise; + + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function unlink(path: PathLike): Promise; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param handle A `FileHandle`. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function fchmod(handle: FileHandle, mode: string | number): Promise; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function chmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function lchmod(path: PathLike, mode: string | number): Promise; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param handle A `FileHandle`. + */ + function fchown(handle: FileHandle, uid: number, gid: number): Promise; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied `FileHandle`. + * @param handle A `FileHandle`. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * It is unsafe to call `fsPromises.writeFile()` multiple times on the same file without waiting for the `Promise` to be resolved (or rejected). + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function writeFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a `Buffer` or `Uint8Array` is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function appendFile(path: PathLike | FileHandle, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string | number } | string | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: null, flag?: string | number } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options: { encoding: BufferEncoding, flag?: string | number } | BufferEncoding): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile(path: PathLike | FileHandle, options?: { encoding?: string | null, flag?: string | number } | string | null): Promise; + } +} diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..d80e119 --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,1144 @@ +// This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build +interface Console { + Console: NodeJS.ConsoleConstructor; + /** + * A simple assertion test that verifies whether `value` is truthy. + * If it is not, an `AssertionError` is thrown. + * If provided, the error `message` is formatted using `util.format()` and used as the error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the TTY. + * When `stdout` is not a TTY, this method does nothing. + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the number of times `console.count()` has been called with the given `label`. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link console.log()}. + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses {@link util.inspect()} on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + */ + dir(obj: any, options?: NodeJS.InspectOptions): void; + /** + * This method calls {@link console.log()} passing it the arguments received. Please note that this method does not produce any XML formatting + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by two spaces. + * If one or more `label`s are provided, those are printed first without the additional indentation. + */ + group(...label: any[]): void; + /** + * The `console.groupCollapsed()` function is an alias for {@link console.group()}. + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by two spaces. + */ + groupEnd(): void; + /** + * The {@link console.info()} function is an alias for {@link console.log()}. + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * This method does not display anything unless used in the inspector. + * Prints to `stdout` the array `array` formatted as a table. + */ + table(tabularData: any, properties?: ReadonlyArray): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers are identified by a unique `label`. + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The {@link console.warn()} function is an alias for {@link console.error()}. + */ + warn(message?: any, ...optionalParams: any[]): void; + + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. + * The console.markTimeline() method is the deprecated form of console.timeStamp(). + * + * @deprecated Use console.timeStamp() instead. + */ + markTimeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Starts a JavaScript CPU profile with an optional label. + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Stops the current JavaScript CPU profiling session if one has been started and prints the report to the Profiles panel of the inspector. + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * Adds an event with the label `label` to the Timeline panel of the inspector. + */ + timeStamp(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timeline() method is the deprecated form of console.time(). + * + * @deprecated Use console.time() instead. + */ + timeline(label?: string): void; + /** + * This method does not display anything unless used in the inspector. + * The console.timelineEnd() method is the deprecated form of console.timeEnd(). + * + * @deprecated Use console.timeEnd() instead. + */ + timelineEnd(label?: string): void; +} + +interface Error { + stack?: string; +} + +// Declare "static" methods in Error +interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: Object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://github.com/v8/v8/wiki/Stack%20Trace%20API#customizing-stack-traces + */ + prepareStackTrace?: (err: Error, stackTraces: NodeJS.CallSite[]) => any; + + stackTraceLimit: number; +} + +interface SymbolConstructor { + readonly observable: symbol; +} + +// Node.js ESNEXT support +interface String { + /** Removes whitespace from the left end of a string. */ + trimLeft(): string; + /** Removes whitespace from the right end of a string. */ + trimRight(): string; + + /** Returns a copy with leading whitespace removed. */ + trimStart(): string; + /** Returns a copy with trailing whitespace removed. */ + trimEnd(): string; +} + +/*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ +declare var process: NodeJS.Process; +declare var global: NodeJS.Global; +declare var console: Console; + +declare var __filename: string; +declare var __dirname: string; + +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; +} +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; +declare namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; +} +declare function clearImmediate(immediateId: NodeJS.Immediate): void; + +/** + * @experimental + */ +declare function queueMicrotask(callback: () => void): void; + +// TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. +interface NodeRequireFunction { + (id: string): any; +} + +interface NodeRequire extends NodeRequireFunction { + resolve: RequireResolve; + cache: any; + /** + * @deprecated + */ + extensions: NodeExtensions; + main: NodeModule | undefined; +} + +interface RequireResolve { + (id: string, options?: { paths?: string[]; }): string; + paths(request: string): string[] | null; +} + +interface NodeExtensions { + '.js': (m: NodeModule, filename: string) => any; + '.json': (m: NodeModule, filename: string) => any; + '.node': (m: NodeModule, filename: string) => any; + [ext: string]: (m: NodeModule, filename: string) => any; +} + +declare var require: NodeRequire; + +interface NodeModule { + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: NodeModule | null; + children: NodeModule[]; + /** + * @since 11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; +} + +declare var module: NodeModule; + +// Same as module.exports +declare var exports: any; + +// Buffer class +type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex"; +interface Buffer extends Uint8Array { + constructor: typeof Buffer; + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: number[] }; + equals(otherBuffer: Uint8Array): boolean; + compare(otherBuffer: Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + subarray(begin: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number): number; + writeUIntBE(value: number, offset: number, byteLength: number): number; + writeIntLE(value: number, offset: number, byteLength: number): number; + writeIntBE(value: number, offset: number, byteLength: number): number; + readUIntLE(offset: number, byteLength: number): number; + readUIntBE(offset: number, byteLength: number): number; + readIntLE(offset: number, byteLength: number): number; + readIntBE(offset: number, byteLength: number): number; + readUInt8(offset: number): number; + readUInt16LE(offset: number): number; + readUInt16BE(offset: number): number; + readUInt32LE(offset: number): number; + readUInt32BE(offset: number): number; + readInt8(offset: number): number; + readInt16LE(offset: number): number; + readInt16BE(offset: number): number; + readInt32LE(offset: number): number; + readInt32BE(offset: number): number; + readFloatLE(offset: number): number; + readFloatBE(offset: number): number; + readDoubleLE(offset: number): number; + readDoubleBE(offset: number): number; + reverse(): this; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number): number; + writeUInt16LE(value: number, offset: number): number; + writeUInt16BE(value: number, offset: number): number; + writeUInt32LE(value: number, offset: number): number; + writeUInt32BE(value: number, offset: number): number; + writeInt8(value: number, offset: number): number; + writeInt16LE(value: number, offset: number): number; + writeInt16BE(value: number, offset: number): number; + writeInt32LE(value: number, offset: number): number; + writeInt32BE(value: number, offset: number): number; + writeFloatLE(value: number, offset: number): number; + writeFloatBE(value: number, offset: number): number; + writeDoubleLE(value: number, offset: number): number; + writeDoubleBE(value: number, offset: number): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + keys(): IterableIterator; + values(): IterableIterator; +} + +/** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + */ +declare const Buffer: { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: ReadonlyArray): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + prototype: Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of any TypedArray or a new ArrayBuffer() + */ + from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: ReadonlyArray): Buffer; + from(data: Uint8Array): Buffer; + /** + * Creates a new buffer containing the coerced value of an object + * A `TypeError` will be thrown if {obj} has not mentioned methods or is not of other type appropriate for `Buffer.from()` variants. + * @param obj An object supporting `Symbol.toPrimitive` or `valueOf()`. + */ + from(obj: { valueOf(): string | object } | { [Symbol.toPrimitive](hint: 'string'): string }, byteOffset?: number, length?: number): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from(str: string, encoding?: BufferEncoding): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + isEncoding(encoding: string): encoding is BufferEncoding + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + byteLength(string: string | NodeJS.TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + concat(list: ReadonlyArray, totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + compare(buf1: Uint8Array, buf2: Uint8Array): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the number of bytes used to determine the size of pre-allocated, internal Buffer instances used for pooling. This value may be modified. + */ + poolSize: number; +}; + +/*----------------------------------------------* +* * +* GLOBAL INTERFACES * +* * +*-----------------------------------------------*/ +declare namespace NodeJS { + interface InspectOptions { + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default `false` + */ + getters?: 'get' | 'set' | boolean; + showHidden?: boolean; + /** + * @default 2 + */ + depth?: number | null; + colors?: boolean; + customInspect?: boolean; + showProxy?: boolean; + maxArrayLength?: number | null; + breakLength?: number; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default `true` + */ + compact?: boolean | number; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; + inspectOptions?: InspectOptions; + } + + interface ConsoleConstructor { + prototype: Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + + interface CallSite { + /** + * Value of "this" + */ + getThis(): any; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | null; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + } + + interface ErrnoException extends Error { + errno?: number; + code?: string; + path?: string; + syscall?: string; + stack?: string; + } + + class EventEmitter { + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string | symbol): this; + setMaxListeners(n: number): this; + getMaxListeners(): number; + listeners(event: string | symbol): Function[]; + rawListeners(event: string | symbol): Function[]; + emit(event: string | symbol, ...args: any[]): boolean; + listenerCount(type: string | symbol): number; + // Added in Node 6... + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + eventNames(): Array; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Buffer | Uint8Array): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Buffer | Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: string, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): void; + end(data: string | Uint8Array | Buffer, cb?: () => void): void; + end(str: string, encoding?: string, cb?: () => void): void; + } + + interface ReadWriteStream extends ReadableStream, WritableStream { } + + interface Events extends EventEmitter { } + + interface Domain extends Events { + run(fn: (...args: any[]) => T, ...args: any[]): T; + add(emitter: EventEmitter | Timer): void; + remove(emitter: EventEmitter | Timer): void; + bind(cb: T): T; + intercept(cb: T): T; + + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + removeAllListeners(event?: string): this; + } + + interface MemoryUsage { + rss: number; + heapTotal: number; + heapUsed: number; + external: number; + } + + interface CpuUsage { + user: number; + system: number; + } + + interface ProcessRelease { + name: string; + sourceUrl?: string; + headersUrl?: string; + libUrl?: string; + lts?: string; + } + + interface ProcessVersions { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + + type Platform = 'aix' + | 'android' + | 'darwin' + | 'freebsd' + | 'linux' + | 'openbsd' + | 'sunos' + | 'win32' + | 'cygwin'; + + type Signals = + "SIGABRT" | "SIGALRM" | "SIGBUS" | "SIGCHLD" | "SIGCONT" | "SIGFPE" | "SIGHUP" | "SIGILL" | "SIGINT" | "SIGIO" | + "SIGIOT" | "SIGKILL" | "SIGPIPE" | "SIGPOLL" | "SIGPROF" | "SIGPWR" | "SIGQUIT" | "SIGSEGV" | "SIGSTKFLT" | + "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | + "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + + type MultipleResolveType = 'resolve' | 'reject'; + + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error) => void; + type UnhandledRejectionListener = (reason: {} | null | undefined, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: any, sendHandle: any) => void; + type SignalsListener = (signal: Signals) => void; + type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; + + interface Socket extends ReadWriteStream { + isTTY?: true; + } + + interface ProcessEnv { + [key: string]: string | undefined; + } + + interface WriteStream extends Socket { + readonly writableHighWaterMark: number; + readonly writableLength: number; + columns?: number; + rows?: number; + _write(chunk: any, encoding: string, callback: (err?: null | Error) => void): void; + _destroy(err: Error | null, callback: (err?: null | Error) => void): void; + _final(callback: (err?: null | Error) => void): void; + setDefaultEncoding(encoding: string): this; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + } + interface ReadStream extends Socket { + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + isRaw?: boolean; + setRawMode?(mode: boolean): void; + _read(size: number): void; + _destroy(err: Error | null, callback: (err?: null | Error) => void): void; + push(chunk: any, encoding?: string): boolean; + destroy(error?: Error): void; + } + + interface HRTime { + (time?: [number, number]): [number, number]; + bigint(): bigint; + } + + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @defaul false + */ + reportOnSignal: boolean; + + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + + interface Process extends EventEmitter { + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stdout: WriteStream; + /** + * Can also be a tty.WriteStream, not typed due to limitation.s + */ + stderr: WriteStream; + stdin: ReadStream; + openStdin(): Socket; + argv: string[]; + argv0: string; + execArgv: string[]; + execPath: string; + abort(): void; + chdir(directory: string): void; + cwd(): string; + debugPort: number; + emitWarning(warning: string | Error, name?: string, ctor?: Function): void; + env: ProcessEnv; + exit(code?: number): never; + exitCode?: number; + getgid(): number; + setgid(id: number | string): void; + getuid(): number; + setuid(id: number | string): void; + geteuid(): number; + seteuid(id: number | string): void; + getegid(): number; + setegid(id: number | string): void; + getgroups(): number[]; + setgroups(groups: ReadonlyArray): void; + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + hasUncaughtExceptionCaptureCallback(): boolean; + version: string; + versions: ProcessVersions; + config: { + target_defaults: { + cflags: any[]; + default_configuration: string; + defines: string[]; + include_dirs: string[]; + libraries: string[]; + }; + variables: { + clang: number; + host_arch: string; + node_install_npm: boolean; + node_install_waf: boolean; + node_prefix: string; + node_shared_openssl: boolean; + node_shared_v8: boolean; + node_shared_zlib: boolean; + node_use_dtrace: boolean; + node_use_etw: boolean; + node_use_openssl: boolean; + target_arch: string; + v8_no_strict_aliasing: number; + v8_use_snapshot: boolean; + visibility: string; + }; + }; + kill(pid: number, signal?: string | number): void; + pid: number; + ppid: number; + title: string; + arch: string; + platform: Platform; + mainModule?: NodeModule; + memoryUsage(): MemoryUsage; + cpuUsage(previousValue?: CpuUsage): CpuUsage; + nextTick(callback: Function, ...args: any[]): void; + release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * Can only be set if not in worker thread. + */ + umask(mask?: number): number; + uptime(): number; + hrtime: HRTime; + domain: Domain; + + // Worker + send?(message: any, sendHandle?: any, options?: { swallowErrors?: boolean}, callback?: (error: Error | null) => void): boolean; + disconnect(): void; + connected: boolean; + + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] + * environment variable. + */ + allowedNodeEnvironmentFlags: ReadonlySet; + + /** + * Only available with `--experimental-report` + */ + report?: ProcessReport; + + /** + * EventEmitter + * 1. beforeExit + * 2. disconnect + * 3. exit + * 4. message + * 5. rejectionHandled + * 6. uncaughtException + * 7. unhandledRejection + * 8. warning + * 9. message + * 10. + * 11. newListener/removeListener inherited from EventEmitter + */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "newListener", listener: NewListenerListener): this; + addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "unhandledRejection", reason: any, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: any, sendHandle: any): this; + emit(event: Signals, signal: Signals): boolean; + emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; + + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "newListener", listener: NewListenerListener): this; + on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "newListener", listener: NewListenerListener): this; + once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "newListener", listener: NewListenerListener): this; + prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "newListener", listener: NewListenerListener): this; + prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "newListener"): NewListenerListener[]; + listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + } + + interface Global { + Array: typeof Array; + ArrayBuffer: typeof ArrayBuffer; + Boolean: typeof Boolean; + Buffer: typeof Buffer; + DataView: typeof DataView; + Date: typeof Date; + Error: typeof Error; + EvalError: typeof EvalError; + Float32Array: typeof Float32Array; + Float64Array: typeof Float64Array; + Function: typeof Function; + GLOBAL: Global; + Infinity: typeof Infinity; + Int16Array: typeof Int16Array; + Int32Array: typeof Int32Array; + Int8Array: typeof Int8Array; + Intl: typeof Intl; + JSON: typeof JSON; + Map: MapConstructor; + Math: typeof Math; + NaN: typeof NaN; + Number: typeof Number; + Object: typeof Object; + Promise: Function; + RangeError: typeof RangeError; + ReferenceError: typeof ReferenceError; + RegExp: typeof RegExp; + Set: SetConstructor; + String: typeof String; + Symbol: Function; + SyntaxError: typeof SyntaxError; + TypeError: typeof TypeError; + URIError: typeof URIError; + Uint16Array: typeof Uint16Array; + Uint32Array: typeof Uint32Array; + Uint8Array: typeof Uint8Array; + Uint8ClampedArray: Function; + WeakMap: WeakMapConstructor; + WeakSet: WeakSetConstructor; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => void; + console: typeof console; + decodeURI: typeof decodeURI; + decodeURIComponent: typeof decodeURIComponent; + encodeURI: typeof encodeURI; + encodeURIComponent: typeof encodeURIComponent; + escape: (str: string) => string; + eval: typeof eval; + global: Global; + isFinite: typeof isFinite; + isNaN: typeof isNaN; + parseFloat: typeof parseFloat; + parseInt: typeof parseInt; + process: Process; + root: Global; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + queueMicrotask: typeof queueMicrotask; + undefined: typeof undefined; + unescape: (str: string) => string; + gc: () => void; + v8debug?: any; + } + + interface Timer { + hasRef(): boolean; + ref(): this; + refresh(): this; + unref(): this; + } + + class Immediate { + hasRef(): boolean; + ref(): this; + refresh(): this; + unref(): this; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + hasRef(): boolean; + ref(): this; + refresh(): this; + unref(): this; + } + + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; + static builtinModules: string[]; + + static Module: typeof Module; + + exports: any; + require: NodeRequireFunction; + id: string; + filename: string; + loaded: boolean; + parent: Module | null; + children: Module[]; + paths: string[]; + + constructor(id: string, parent?: Module); + } + + type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Int8Array | Int16Array | Int32Array | Float32Array | Float64Array; +} diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..4c12f89 --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,282 @@ +declare module "http" { + import * as events from "events"; + import * as stream from "stream"; + import { URL } from "url"; + import { Socket, Server as NetServer } from "net"; + + // incoming headers will never contain number + interface IncomingHttpHeaders { + 'accept'?: string; + 'accept-language'?: string; + 'accept-patch'?: string; + 'accept-ranges'?: string; + 'access-control-allow-credentials'?: string; + 'access-control-allow-headers'?: string; + 'access-control-allow-methods'?: string; + 'access-control-allow-origin'?: string; + 'access-control-expose-headers'?: string; + 'access-control-max-age'?: string; + 'access-control-request-headers'?: string; + 'access-control-request-method'?: string; + 'age'?: string; + 'allow'?: string; + 'alt-svc'?: string; + 'authorization'?: string; + 'cache-control'?: string; + 'connection'?: string; + 'content-disposition'?: string; + 'content-encoding'?: string; + 'content-language'?: string; + 'content-length'?: string; + 'content-location'?: string; + 'content-range'?: string; + 'content-type'?: string; + 'cookie'?: string; + 'date'?: string; + 'expect'?: string; + 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; + 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; + 'last-modified'?: string; + 'location'?: string; + 'origin'?: string; + 'pragma'?: string; + 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; + 'public-key-pins'?: string; + 'range'?: string; + 'referer'?: string; + 'retry-after'?: string; + 'set-cookie'?: string[]; + 'strict-transport-security'?: string; + 'tk'?: string; + 'trailer'?: string; + 'transfer-encoding'?: string; + 'upgrade'?: string; + 'user-agent'?: string; + 'vary'?: string; + 'via'?: string; + 'warning'?: string; + 'www-authenticate'?: string; + [header: string]: string | string[] | undefined; + } + + // outgoing headers allows numbers (as they are converted internally to strings) + interface OutgoingHttpHeaders { + [header: string]: number | string | string[] | undefined; + } + + interface ClientRequestArgs { + protocol?: string; + host?: string; + hostname?: string; + family?: number; + port?: number | string; + defaultPort?: number | string; + localAddress?: string; + socketPath?: string; + method?: string; + path?: string; + headers?: OutgoingHttpHeaders; + auth?: string; + agent?: Agent | boolean; + _defaultAgent?: Agent; + timeout?: number; + setHost?: boolean; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: Socket) => void) => Socket; + } + + interface ServerOptions { + IncomingMessage?: typeof IncomingMessage; + ServerResponse?: typeof ServerResponse; + } + + type RequestListener = (req: IncomingMessage, res: ServerResponse) => void; + + class Server extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @default 2000 + * {@link https://nodejs.org/api/http.html#http_server_maxheaderscount} + */ + maxHeadersCount: number | null; + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP headers. + * @default 40000 + * {@link https://nodejs.org/api/http.html#http_server_headerstimeout} + */ + headersTimeout: number; + keepAliveTimeout: number; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js + class OutgoingMessage extends stream.Writable { + upgrading: boolean; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + finished: boolean; + headersSent: boolean; + connection: Socket; + + constructor(); + + setTimeout(msecs: number, callback?: () => void): this; + setHeader(name: string, value: number | string | ReadonlyArray): void; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + flushHeaders(): void; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 + class ServerResponse extends OutgoingMessage { + statusCode: number; + statusMessage: string; + + constructor(req: IncomingMessage); + + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 + // no args in writeContinue callback + writeContinue(callback?: () => void): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + } + + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + class ClientRequest extends OutgoingMessage { + connection: Socket; + socket: Socket; + aborted: boolean; + + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + + readonly path: string; + abort(): void; + onSocket(socket: Socket): void; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): void; + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + } + + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + complete: boolean; + connection: Socket; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + trailers: { [key: string]: string | undefined }; + rawTrailers: string[]; + setTimeout(msecs: number, callback?: () => void): this; + /** + * Only valid for request obtained from http.Server. + */ + method?: string; + /** + * Only valid for request obtained from http.Server. + */ + url?: string; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusCode?: number; + /** + * Only valid for response obtained from http.ClientRequest. + */ + statusMessage?: string; + socket: Socket; + destroy(error?: Error): void; + } + + interface AgentOptions { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number; + } + + class Agent { + maxFreeSockets: number; + maxSockets: number; + readonly sockets: { + readonly [key: string]: Socket[]; + }; + readonly requests: { + readonly [key: string]: IncomingMessage[]; + }; + + constructor(opts?: AgentOptions); + + /** + * Destroy any sockets that are currently in use by the agent. + * It is usually not necessary to do this. However, if you are using an agent with KeepAlive enabled, + * then it is best to explicitly shut down the agent when you know that it will no longer be used. Otherwise, + * sockets may hang open for quite a long time before the server terminates them. + */ + destroy(): void; + } + + const METHODS: string[]; + + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + + function createServer(requestListener?: RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: RequestListener): Server; + + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs { } + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + let globalAgent: Agent; + + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 8KB. Configurable using the [`--max-http-header-size`][] CLI option. + */ + const maxHeaderSize: number; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..4ac13f5 --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,959 @@ +declare module "http2" { + import * as events from "events"; + import * as fs from "fs"; + import * as net from "net"; + import * as stream from "stream"; + import * as tls from "tls"; + import * as url from "url"; + + import { IncomingHttpHeaders as Http1IncomingHttpHeaders, OutgoingHttpHeaders, IncomingMessage, ServerResponse } from "http"; + export { OutgoingHttpHeaders } from "http"; + + export interface IncomingHttpStatusHeader { + ":status"?: number; + } + + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string; + ":method"?: string; + ":authority"?: string; + ":scheme"?: string; + } + + // Http2Stream + + export interface StreamPriorityOptions { + exclusive?: boolean; + parent?: number; + weight?: number; + silent?: boolean; + } + + export interface StreamState { + localWindowSize?: number; + state?: number; + localClose?: number; + remoteClose?: number; + sumDependencyWeight?: number; + weight?: number; + } + + export interface ServerStreamResponseOptions { + endStream?: boolean; + waitForTrailers?: boolean; + } + + export interface StatOptions { + offset: number; + length: number; + } + + export interface ServerStreamFileResponseOptions { + statCheck?: (stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void | boolean; + waitForTrailers?: boolean; + offset?: number; + length?: number; + } + + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?: (err: NodeJS.ErrnoException) => void; + } + + export class Http2Stream extends stream.Duplex { + protected constructor(); + + readonly aborted: boolean; + readonly bufferSize: number; + readonly closed: boolean; + readonly destroyed: boolean; + /** + * Set the true if the END_STREAM flag was set in the request or response HEADERS frame received, + * indicating that no additional data should be received and the readable side of the Http2Stream will be closed. + */ + readonly endAfterHeaders: boolean; + readonly pending: boolean; + readonly rstCode: number; + readonly sentHeaders: OutgoingHttpHeaders; + readonly sentInfoHeaders?: OutgoingHttpHeaders[]; + readonly sentTrailers?: OutgoingHttpHeaders; + readonly session: Http2Session; + readonly state: StreamState; + + close(code?: number, callback?: () => void): void; + priority(options: StreamPriorityOptions): void; + setTimeout(msecs: number, callback?: () => void): void; + sendTrailers(headers: OutgoingHttpHeaders): void; + + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export class ClientHttp2Stream extends Http2Stream { + private constructor(); + + addListener(event: "continue", listener: () => {}): this; + addListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "continue", listener: () => {}): this; + on(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "continue", listener: () => {}): this; + once(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "continue", listener: () => {}): this; + prependListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener(event: "headers", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "response", listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export class ServerHttp2Stream extends Http2Stream { + private constructor(); + + additionalHeaders(headers: OutgoingHttpHeaders): void; + readonly headersSent: boolean; + readonly pushAllowed: boolean; + pushStream(headers: OutgoingHttpHeaders, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + pushStream(headers: OutgoingHttpHeaders, options?: StreamPriorityOptions, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void): void; + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + respondWithFD(fd: number, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptions): void; + respondWithFile(path: string, headers?: OutgoingHttpHeaders, options?: ServerStreamFileResponseOptionsWithError): void; + } + + // Http2Session + + export interface Settings { + headerTableSize?: number; + enablePush?: boolean; + initialWindowSize?: number; + maxFrameSize?: number; + maxConcurrentStreams?: number; + maxHeaderListSize?: number; + enableConnectProtocol?: boolean; + } + + export interface ClientSessionRequestOptions { + endStream?: boolean; + exclusive?: boolean; + parent?: number; + weight?: number; + waitForTrailers?: boolean; + } + + export interface SessionState { + effectiveLocalWindowSize?: number; + effectiveRecvDataLength?: number; + nextStreamID?: number; + localWindowSize?: number; + lastProcStreamID?: number; + remoteWindowSize?: number; + outboundQueueSize?: number; + deflateDynamicTableSize?: number; + inflateDynamicTableSize?: number; + } + + export class Http2Session extends events.EventEmitter { + protected constructor(); + + readonly alpnProtocol?: string; + close(callback?: () => void): void; + readonly closed: boolean; + readonly connecting: boolean; + destroy(error?: Error, code?: number): void; + readonly destroyed: boolean; + readonly encrypted?: boolean; + goaway(code?: number, lastStreamID?: number, opaqueData?: Buffer | DataView | NodeJS.TypedArray): void; + readonly localSettings: Settings; + readonly originSet?: string[]; + readonly pendingSettingsAck: boolean; + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping(payload: Buffer | DataView | NodeJS.TypedArray , callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ref(): void; + readonly remoteSettings: Settings; + setTimeout(msecs: number, callback?: () => void): void; + readonly socket: net.Socket | tls.TLSSocket; + readonly state: SessionState; + settings(settings: Settings): void; + readonly type: number; + unref(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + addListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + prependOnceListener(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData: Buffer) => void): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export class ClientHttp2Session extends Http2Session { + private constructor(); + + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: ReadonlyArray): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ClientHttp2Stream, headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + + export class ServerHttp2Session extends Http2Session { + private constructor(); + + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + origin(...args: Array): void; + readonly server: Http2Server | Http2SecureServer; + + addListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + // Http2Server + + export interface SessionOptions { + maxDeflateDynamicTableSize?: number; + maxSessionMemory?: number; + maxHeaderListPairs?: number; + maxOutstandingPings?: number; + maxSendHeaderBlockLength?: number; + paddingStrategy?: number; + peerMaxConcurrentStreams?: number; + selectPadding?: (frameLen: number, maxFrameLen: number) => number; + settings?: Settings; + createConnection?: (authority: url.URL, option: SessionOptions) => stream.Duplex; + } + + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number; + createConnection?: (authority: url.URL, option: SessionOptions) => stream.Duplex; + } + + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage; + Http1ServerResponse?: typeof ServerResponse; + Http2ServerRequest?: typeof Http2ServerRequest; + Http2ServerResponse?: typeof Http2ServerResponse; + } + + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions { } + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions { } + + export interface ServerOptions extends ServerSessionOptions { } + + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean; + origins?: string[]; + } + + export class Http2Server extends net.Server { + private constructor(); + + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + setTimeout(msec?: number, callback?: () => void): this; + } + + export class Http2SecureServer extends tls.Server { + private constructor(); + + addListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "checkContinue", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener(event: "stream", listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + setTimeout(msec?: number, callback?: () => void): this; + } + + export class Http2ServerRequest extends stream.Readable { + private constructor(); + + readonly aborted: boolean; + readonly authority: string; + readonly headers: IncomingHttpHeaders; + readonly httpVersion: string; + readonly method: string; + readonly rawHeaders: string[]; + readonly rawTrailers: string[]; + readonly scheme: string; + setTimeout(msecs: number, callback?: () => void): void; + readonly socket: net.Socket | tls.TLSSocket; + readonly stream: ServerHttp2Stream; + readonly trailers: IncomingHttpHeaders; + readonly url: string; + + read(size?: number): Buffer | string | null; + + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + export class Http2ServerResponse extends stream.Stream { + private constructor(); + + addTrailers(trailers: OutgoingHttpHeaders): void; + readonly connection: net.Socket | tls.TLSSocket; + end(callback?: () => void): void; + end(data: string | Buffer | Uint8Array, callback?: () => void): void; + end(data: string | Buffer | Uint8Array, encoding: string, callback?: () => void): void; + readonly finished: boolean; + getHeader(name: string): string; + getHeaderNames(): string[]; + getHeaders(): OutgoingHttpHeaders; + hasHeader(name: string): boolean; + readonly headersSent: boolean; + removeHeader(name: string): void; + sendDate: boolean; + setHeader(name: string, value: number | string | ReadonlyArray): void; + setTimeout(msecs: number, callback?: () => void): void; + readonly socket: net.Socket | tls.TLSSocket; + statusCode: number; + statusMessage: ''; + readonly stream: ServerHttp2Stream; + write(chunk: string | Buffer | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Buffer | Uint8Array, encoding: string, callback?: (err: Error) => void): boolean; + writeContinue(): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + createPushResponse(headers: OutgoingHttpHeaders, callback: (err: Error | null, res: Http2ServerResponse) => void): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + // Public API + + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + + export function getDefaultSettings(): Settings; + export function getPackedSettings(settings: Settings): Buffer; + export function getUnpackedSettings(buf: Buffer | Uint8Array): Settings; + + export function createServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + export function createServer(options: ServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2Server; + + export function createSecureServer(onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + export function createSecureServer(options: SecureServerOptions, onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void): Http2SecureServer; + + export function connect(authority: string | url.URL, listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..6f33dbd --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,53 @@ +declare module "https" { + import * as tls from "tls"; + import * as events from "events"; + import * as http from "http"; + import { URL } from "url"; + + type ServerOptions = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + + type RequestOptions = http.RequestOptions & tls.SecureContextOptions & { + rejectUnauthorized?: boolean; // Defaults to true + servername?: string; // SNI TLS Extension + }; + + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean; + maxCachedSessions?: number; + } + + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + + class Server extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor(options: ServerOptions, requestListener?: http.RequestListener); + + setTimeout(callback: () => void): this; + setTimeout(msecs?: number, callback?: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @default 2000 + * {@link https://nodejs.org/api/http.html#http_server_maxheaderscount} + */ + maxHeadersCount: number | null; + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP headers. + * @default 40000 + * {@link https://nodejs.org/api/http.html#http_server_headerstimeout} + */ + headersTimeout: number; + keepAliveTimeout: number; + } + + function createServer(requestListener?: http.RequestListener): Server; + function createServer(options: ServerOptions, requestListener?: http.RequestListener): Server; + function request(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function request(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(options: RequestOptions | string | URL, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + let globalAgent: Agent; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..6ee96a5 --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for non-npm package Node.js 11.15 +// Project: http://nodejs.org/ +// Definitions by: Microsoft TypeScript +// DefinitelyTyped +// Alberto Schiabel +// Alexander T. +// Alvis HT Tang +// Andrew Makarov +// Benjamin Toueg +// Bruno Scheufler +// Chigozirim C. +// David Junger +// Deividas Bakanas +// Eugene Y. Q. Shen +// Flarna +// Hannes Magnusson +// Hoàng Văn Khải +// Huw +// Kelvin Jin +// Klaus Meinhardt +// Lishude +// Mariusz Wiktorczyk +// Mohsen Azimi +// Nicolas Even +// Nikita Galkin +// Parambir Singh +// Sebastian Silbermann +// Simon Schick +// Thomas den Hollander +// Wilco Bakker +// wwwy3y3 +// Zane Hannan AU +// Jeremie Rodriguez +// Samuel Ainsworth +// Kyle Uehlein +// Jordi Oliveras Rovira +// Thanik Bhongbhibhat +// Ivan Sieder +// Minh Son Nguyen +// ExE Boss +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NOTE: These definitions support NodeJS and TypeScript 3.7. +// This isn't strictly needed since 3.7 has the assert module, but this way we're consistent. +// Typically type modificatons should be made in base.d.ts instead of here + +/// diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..8abee39 --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,3257 @@ +// tslint:disable-next-line:dt-header +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module "inspector" { + import { EventEmitter } from 'events'; + + interface InspectorNotification { + method: string; + params: T; + } + + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number; + } + + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + + /** + * Call frame identifier. + */ + type CallFrameId = string; + + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + } + + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * `this` object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject; + } + + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For `global` and `with` scopes it represents the actual + * object; for the rest of the scopes, it is artificial transient object enumerating scope + * variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string; + /** + * Location in the source code where scope starts + */ + startLocation?: Location; + /** + * Location in the source code where scope ends + */ + endLocation?: Location; + } + + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + + interface BreakLocation { + /** + * Script identifier as reported in the `Debugger.scriptParsed`. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number; + type?: string; + } + + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string; + } + + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles + * using `releaseObjectGroup`). + */ + objectGroup?: string; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults + * to false. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean; + /** + * Terminate execution after timing out (number of milliseconds). + * @experimental + */ + timeout?: Runtime.TimeDelta; + } + + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end + * of scripts is used as end of range. + */ + end?: Location; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean; + } + + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean; + } + + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async + * call stacks (default). + */ + maxDepth: number; + } + + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the + * breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either `url` or + * `urlRegex` must be specified. + */ + urlRegex?: string; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the + * breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointOnFunctionCallParameterType { + /** + * Function object id. + */ + objectId: Runtime.RemoteObjectId; + /** + * Expression to use as a breakpoint condition. When specified, debugger will + * stop on the breakpoint if this expression evaluates to true. + */ + condition?: string; + } + + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result + * description without actually modifying the code. + */ + dryRun?: boolean; + } + + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' + * scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled + * before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean; + } + + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + } + + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + + interface SetBreakpointOnFunctionCallReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + } + + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[]; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails; + } + + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {}; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. + * This field is available only after `Debugger.stepInto` call with `breakOnAsynCall` flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId; + } + + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {}; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean; + /** + * This script length. + */ + length?: number; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace; + } + } + + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + } + + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The + * default value is 32768 bytes. + */ + samplingInterval?: number; + } + + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean; + } + + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken + * when the tracking is stopped. + */ + reportProgress?: boolean; + } + + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean; + } + + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment + * index, the second integer is a total count of objects for the fragment, the third integer is + * a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean; + } + } + + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number; + /** + * Child node ids. + */ + children?: number[]; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't + * optimize. + */ + deoptReason?: string; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[]; + } + + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[]; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the + * profile startTime. + */ + timeDeltas?: number[]; + } + + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean; + /** + * Collect block-based coverage. + */ + detailed?: boolean; + } + + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string; + } + } + + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + + /** + * Primitive value which cannot be JSON-stringified. Includes values `-0`, `NaN`, `Infinity`, + * `-Infinity`, and bigint literals. + */ + type UnserializableValue = string; + + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * Object class (constructor) name. Specified for `object` type values only. + */ + className?: string; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have `value`, but gets this + * property. + */ + unserializableValue?: UnserializableValue; + /** + * String representation of the object. + */ + description?: string; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId; + /** + * Preview containing abbreviated property values. Specified for `object` type values only. + * @experimental + */ + preview?: ObjectPreview; + /** + * @experimental + */ + customPreview?: CustomPreview; + } + + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId; + } + + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + /** + * String representation of the object. + */ + description?: string; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for `map` and `set` subtype values only. + */ + entries?: EntryPreview[]; + } + + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview; + /** + * Object subtype hint. Specified for `object` type values only. + */ + subtype?: string; + } + + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean; + /** + * A function which serves as a getter for the property, or `undefined` if there is no getter + * (accessor descriptors only). + */ + get?: RemoteObject; + /** + * A function which serves as a setter for the property, or `undefined` if there is no setter + * (accessor descriptors only). + */ + set?: RemoteObject; + /** + * True if the type of this property descriptor may be changed and if the property may be + * deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding + * object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean; + /** + * Property symbol object, if the property is of the `symbol` type. + */ + symbol?: RemoteObject; + } + + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject; + } + + /** + * Represents function call argument. Either remote object id `objectId`, primitive `value`, + * unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId; + } + + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context + * script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {}; + } + + /** + * Detailed information about exception (or error) that was thrown during script compilation or + * execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace; + /** + * Exception object if available. + */ + exception?: RemoteObject; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId; + } + + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + + /** + * Number of milliseconds. + */ + type TimeDelta = number; + + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that + * initiated the async call. + */ + description?: string; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId; + } + + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + + /** + * If `debuggerId` is set stack trace comes from another debugger and can be resolved there. This + * allows to track cross-debugger calls. See `Runtime.StackTrace` and `Debugger.paused` for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId; + } + + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + } + + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should + * be specified. + */ + objectId?: RemoteObjectId; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target + * object. + */ + arguments?: CallArgument[]; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + /** + * Specifies execution context which global object will be used to call function on. Either + * executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not + * specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string; + } + + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + } + + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + * @experimental + */ + throwOnSideEffect?: boolean; + /** + * Terminate execution after timing out (number of milliseconds). + * @experimental + */ + timeout?: TimeDelta; + } + + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype + * chain. + */ + ownProperties?: boolean; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not + * returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean; + } + + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId; + } + + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + /** + * Symbolic group name that can be used to release the results. + */ + objectGroup?: string; + } + + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the + * evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause + * execution. Overrides `setPauseOnException` state. + */ + silent?: boolean; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean; + /** + * Whether execution should `await` for resulting value and return once awaited promise is + * resolved. + */ + awaitPromise?: boolean; + } + + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to `0` will effectively disable collecting async + * call stacks (default). + */ + maxDepth: number; + } + + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + + interface SetMaxCallStackSizeToCaptureParameterType { + size: number; + } + + interface AddBindingParameterType { + name: string; + executionContextId?: ExecutionContextId; + } + + interface RemoveBindingParameterType { + name: string; + } + + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GetIsolateIdReturnType { + /** + * The isolate id. + */ + id: string; + } + + interface GetHeapUsageReturnType { + /** + * Used heap size in bytes. + */ + usedSize: number; + /** + * Allocated heap size in bytes. + */ + totalSize: number; + } + + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[]; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails; + } + + interface BindingCalledEventDataType { + name: string; + payload: string; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + } + + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace; + /** + * Console context descriptor for calls on non-default console context (not console.*): + * 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call + * on named context. + * @experimental + */ + context?: string; + } + + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in `exceptionThrown`. + */ + exceptionId: number; + } + + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + + interface StartParameterType { + traceConfig: TraceConfig; + } + + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + + namespace NodeWorker { + type WorkerID = string; + + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + + /** + * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + + /** + * Connects a session to the inspector back-end. + * An exception will be thrown if there is already a connected session established either + * through the API or by a front-end connected to the Inspector WebSocket port. + */ + connect(): void; + + /** + * Immediately close the session. All pending message callbacks will be called with an error. + * session.connect() will need to be called to be able to send messages again. + * Reconnected session will lose all inspector state, such as enabled agents or configured breakpoints. + */ + disconnect(): void; + + /** + * Posts a message to the inspector back-end. callback will be notified when a response is received. + * callback is a function that accepts two optional arguments - error and message-specific result. + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + + /** + * Does nothing. + */ + post(method: "Console.clearMessages", callback?: (err: Error | null) => void): void; + + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: "Console.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables console domain, sends the messages collected so far to the client by means of the + * `messageAdded` notification. + */ + post(method: "Console.enable", callback?: (err: Error | null) => void): void; + + /** + * Continues execution until specific location is reached. + */ + post(method: "Debugger.continueToLocation", params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.continueToLocation", callback?: (err: Error | null) => void): void; + + /** + * Disables debugger for given page. + */ + post(method: "Debugger.disable", callback?: (err: Error | null) => void): void; + + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been + * enabled until the result for this command is received. + */ + post(method: "Debugger.enable", callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + + /** + * Evaluates expression on a given call frame. + */ + post(method: "Debugger.evaluateOnCallFrame", params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: "Debugger.evaluateOnCallFrame", callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be + * the same. + */ + post( + method: "Debugger.getPossibleBreakpoints", + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: "Debugger.getPossibleBreakpoints", callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + + /** + * Returns source for the script with given id. + */ + post(method: "Debugger.getScriptSource", params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: "Debugger.getScriptSource", callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + + /** + * Returns stack trace with given `stackTraceId`. + * @experimental + */ + post(method: "Debugger.getStackTrace", params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: "Debugger.getStackTrace", callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + + /** + * Stops on the next JavaScript statement. + */ + post(method: "Debugger.pause", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Debugger.pauseOnAsyncCall", params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.pauseOnAsyncCall", callback?: (err: Error | null) => void): void; + + /** + * Removes JavaScript breakpoint. + */ + post(method: "Debugger.removeBreakpoint", params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.removeBreakpoint", callback?: (err: Error | null) => void): void; + + /** + * Restarts particular call frame from the beginning. + */ + post(method: "Debugger.restartFrame", params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: "Debugger.restartFrame", callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + + /** + * Resumes JavaScript execution. + */ + post(method: "Debugger.resume", callback?: (err: Error | null) => void): void; + + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and + * Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled + * before next pause. Returns success when async task is actually scheduled, returns error if no + * task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: "Debugger.scheduleStepIntoAsync", callback?: (err: Error | null) => void): void; + + /** + * Searches for given string in script content. + */ + post(method: "Debugger.searchInContent", params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: "Debugger.searchInContent", callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Debugger.setAsyncCallStackDepth", params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in + * scripts with url matching one of the patterns. VM will try to leave blackboxed script by + * performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: "Debugger.setBlackboxPatterns", params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxPatterns", callback?: (err: Error | null) => void): void; + + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted + * scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * Positions array contains positions where blackbox state is changed. First interval isn't + * blackboxed. Array should be sorted. + * @experimental + */ + post(method: "Debugger.setBlackboxedRanges", params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBlackboxedRanges", callback?: (err: Error | null) => void): void; + + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: "Debugger.setBreakpoint", params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: "Debugger.setBreakpoint", callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this + * command is issued, all existing parsed scripts will have breakpoints resolved and returned in + * `locations` property. Further matching script parsing will result in subsequent + * `breakpointResolved` events issued. This logical breakpoint will survive page reloads. + */ + post(method: "Debugger.setBreakpointByUrl", params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: "Debugger.setBreakpointByUrl", callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + + /** + * Sets JavaScript breakpoint before each call to the given function. + * If another function was created from the same source as a given one, + * calling it will also trigger the breakpoint. + * @experimental + */ + post( + method: "Debugger.setBreakpointOnFunctionCall", + params?: Debugger.SetBreakpointOnFunctionCallParameterType, + callback?: (err: Error | null, params: Debugger.SetBreakpointOnFunctionCallReturnType) => void + ): void; + post(method: "Debugger.setBreakpointOnFunctionCall", callback?: (err: Error | null, params: Debugger.SetBreakpointOnFunctionCallReturnType) => void): void; + + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: "Debugger.setBreakpointsActive", params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setBreakpointsActive", callback?: (err: Error | null) => void): void; + + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or + * no exceptions. Initial pause on exceptions state is `none`. + */ + post(method: "Debugger.setPauseOnExceptions", params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setPauseOnExceptions", callback?: (err: Error | null) => void): void; + + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: "Debugger.setReturnValue", params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setReturnValue", callback?: (err: Error | null) => void): void; + + /** + * Edits JavaScript source live. + */ + post(method: "Debugger.setScriptSource", params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: "Debugger.setScriptSource", callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: "Debugger.setSkipAllPauses", params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setSkipAllPauses", callback?: (err: Error | null) => void): void; + + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be + * mutated manually. + */ + post(method: "Debugger.setVariableValue", params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.setVariableValue", callback?: (err: Error | null) => void): void; + + /** + * Steps into the function call. + */ + post(method: "Debugger.stepInto", params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: "Debugger.stepInto", callback?: (err: Error | null) => void): void; + + /** + * Steps out of the function call. + */ + post(method: "Debugger.stepOut", callback?: (err: Error | null) => void): void; + + /** + * Steps over the statement. + */ + post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details + * $x functions). + */ + post(method: "HeapProfiler.addInspectedHeapObject", params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.addInspectedHeapObject", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.collectGarbage", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.enable", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.getHeapObjectId", params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: "HeapProfiler.getHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + + post( + method: "HeapProfiler.getObjectByHeapObjectId", + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: "HeapProfiler.getObjectByHeapObjectId", callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + + post(method: "HeapProfiler.getSamplingProfile", callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + + post(method: "HeapProfiler.startSampling", params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startSampling", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.startTrackingHeapObjects", params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.startTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.stopSampling", callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + + post(method: "HeapProfiler.stopTrackingHeapObjects", params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.stopTrackingHeapObjects", callback?: (err: Error | null) => void): void; + + post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to + * garbage collection. + */ + post(method: "Profiler.getBestEffortCoverage", callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: "Profiler.setSamplingInterval", params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.setSamplingInterval", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.start", callback?: (err: Error | null) => void): void; + + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code + * coverage may be incomplete. Enabling prevents running optimized code and resets execution + * counters. + */ + post(method: "Profiler.startPreciseCoverage", params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: "Profiler.startPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Enable type profile. + * @experimental + */ + post(method: "Profiler.startTypeProfile", callback?: (err: Error | null) => void): void; + + post(method: "Profiler.stop", callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows + * executing optimized code. + */ + post(method: "Profiler.stopPreciseCoverage", callback?: (err: Error | null) => void): void; + + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: "Profiler.stopTypeProfile", callback?: (err: Error | null) => void): void; + + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code + * coverage needs to have started. + */ + post(method: "Profiler.takePreciseCoverage", callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + + /** + * Collect type profile. + * @experimental + */ + post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + + /** + * Add handler to promise with given promise object id. + */ + post(method: "Runtime.awaitPromise", params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: "Runtime.awaitPromise", callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + + /** + * Calls function with given declaration on the given object. Object group of the result is + * inherited from the target object. + */ + post(method: "Runtime.callFunctionOn", params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: "Runtime.callFunctionOn", callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + + /** + * Compiles expression. + */ + post(method: "Runtime.compileScript", params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: "Runtime.compileScript", callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + + /** + * Disables reporting of execution contexts creation. + */ + post(method: "Runtime.disable", callback?: (err: Error | null) => void): void; + + /** + * Discards collected exceptions and console API calls. + */ + post(method: "Runtime.discardConsoleEntries", callback?: (err: Error | null) => void): void; + + /** + * Enables reporting of execution contexts creation by means of `executionContextCreated` event. + * When the reporting gets enabled the event will be sent immediately for each existing execution + * context. + */ + post(method: "Runtime.enable", callback?: (err: Error | null) => void): void; + + /** + * Evaluates expression on global object. + */ + post(method: "Runtime.evaluate", params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: "Runtime.evaluate", callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + + /** + * Returns the isolate id. + * @experimental + */ + post(method: "Runtime.getIsolateId", callback?: (err: Error | null, params: Runtime.GetIsolateIdReturnType) => void): void; + + /** + * Returns the JavaScript heap usage. + * It is the total usage of the corresponding isolate not scoped to a particular Runtime. + * @experimental + */ + post(method: "Runtime.getHeapUsage", callback?: (err: Error | null, params: Runtime.GetHeapUsageReturnType) => void): void; + + /** + * Returns properties of a given object. Object group of the result is inherited from the target + * object. + */ + post(method: "Runtime.getProperties", params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: "Runtime.getProperties", callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: "Runtime.globalLexicalScopeNames", + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: "Runtime.globalLexicalScopeNames", callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + + post(method: "Runtime.queryObjects", params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: "Runtime.queryObjects", callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + + /** + * Releases remote object with given id. + */ + post(method: "Runtime.releaseObject", params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObject", callback?: (err: Error | null) => void): void; + + /** + * Releases all remote objects that belong to a given group. + */ + post(method: "Runtime.releaseObjectGroup", params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.releaseObjectGroup", callback?: (err: Error | null) => void): void; + + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: "Runtime.runIfWaitingForDebugger", callback?: (err: Error | null) => void): void; + + /** + * Runs script with given id in a given context. + */ + post(method: "Runtime.runScript", params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: "Runtime.runScript", callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + + /** + * Enables or disables async call stacks tracking. + */ + post(method: "Runtime.setAsyncCallStackDepth", params?: Runtime.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setAsyncCallStackDepth", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Runtime.setCustomObjectFormatterEnabled", params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setCustomObjectFormatterEnabled", callback?: (err: Error | null) => void): void; + + /** + * @experimental + */ + post(method: "Runtime.setMaxCallStackSizeToCapture", params?: Runtime.SetMaxCallStackSizeToCaptureParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.setMaxCallStackSizeToCapture", callback?: (err: Error | null) => void): void; + + /** + * Terminate current or next JavaScript execution. + * Will cancel the termination when the outer-most script execution ends. + * @experimental + */ + post(method: "Runtime.terminateExecution", callback?: (err: Error | null) => void): void; + + /** + * If executionContextId is empty, adds binding with the given name on the + * global objects of all inspected contexts, including those created later, + * bindings survive reloads. + * If executionContextId is specified, adds binding only on global object of + * given execution context. + * Binding function takes exactly one argument, this argument should be string, + * in case of any other input, function throws an exception. + * Each binding function call produces Runtime.bindingCalled notification. + * @experimental + */ + post(method: "Runtime.addBinding", params?: Runtime.AddBindingParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.addBinding", callback?: (err: Error | null) => void): void; + + /** + * This method does not remove binding function from global object but + * unsubscribes current runtime agent from Runtime.bindingCalled notifications. + * @experimental + */ + post(method: "Runtime.removeBinding", params?: Runtime.RemoveBindingParameterType, callback?: (err: Error | null) => void): void; + post(method: "Runtime.removeBinding", callback?: (err: Error | null) => void): void; + + /** + * Returns supported domains. + */ + post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + + // Events + + addListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + addListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + addListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + addListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + addListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + addListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + addListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Notification is issued every time when binding is called. + * @experimental + */ + addListener(event: "Runtime.bindingCalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + addListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + addListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + addListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; + emit(event: "Console.messageAdded", message: InspectorNotification): boolean; + emit(event: "Debugger.breakpointResolved", message: InspectorNotification): boolean; + emit(event: "Debugger.paused", message: InspectorNotification): boolean; + emit(event: "Debugger.resumed"): boolean; + emit(event: "Debugger.scriptFailedToParse", message: InspectorNotification): boolean; + emit(event: "Debugger.scriptParsed", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.addHeapSnapshotChunk", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.heapStatsUpdate", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.lastSeenObjectId", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.reportHeapSnapshotProgress", message: InspectorNotification): boolean; + emit(event: "HeapProfiler.resetProfiles"): boolean; + emit(event: "Profiler.consoleProfileFinished", message: InspectorNotification): boolean; + emit(event: "Profiler.consoleProfileStarted", message: InspectorNotification): boolean; + emit(event: "Runtime.bindingCalled", message: InspectorNotification): boolean; + emit(event: "Runtime.consoleAPICalled", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionRevoked", message: InspectorNotification): boolean; + emit(event: "Runtime.exceptionThrown", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; + emit(event: "Runtime.executionContextsCleared"): boolean; + emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + on(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + on(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + on(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + on(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + on(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + on(event: "HeapProfiler.resetProfiles", listener: () => void): this; + on(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Notification is issued every time when binding is called. + * @experimental + */ + on(event: "Runtime.bindingCalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + on(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + on(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + on(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + on(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + on(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + once(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + once(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + once(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + once(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + once(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + once(event: "HeapProfiler.resetProfiles", listener: () => void): this; + once(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Notification is issued every time when binding is called. + * @experimental + */ + once(event: "Runtime.bindingCalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + once(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + once(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + once(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + once(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + once(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + prependListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + prependListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + prependListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + prependListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Notification is issued every time when binding is called. + * @experimental + */ + prependListener(event: "Runtime.bindingCalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + prependListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: "inspectorNotification", listener: (message: InspectorNotification<{}>) => void): this; + + /** + * Issued when new console message is added. + */ + prependOnceListener(event: "Console.messageAdded", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: "Debugger.breakpointResolved", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: "Debugger.paused", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: "Debugger.resumed", listener: () => void): this; + + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: "Debugger.scriptFailedToParse", listener: (message: InspectorNotification) => void): this; + + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected + * scripts upon enabling debugger. + */ + prependOnceListener(event: "Debugger.scriptParsed", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: "HeapProfiler.addHeapSnapshotChunk", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: "HeapProfiler.heapStatsUpdate", listener: (message: InspectorNotification) => void): this; + + /** + * If heap objects tracking has been started then backend regularly sends a current value for last + * seen object id and corresponding timestamp. If the were changes in the heap since last event + * then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: "HeapProfiler.lastSeenObjectId", listener: (message: InspectorNotification) => void): this; + + prependOnceListener(event: "HeapProfiler.reportHeapSnapshotProgress", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "HeapProfiler.resetProfiles", listener: () => void): this; + prependOnceListener(event: "Profiler.consoleProfileFinished", listener: (message: InspectorNotification) => void): this; + + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: "Profiler.consoleProfileStarted", listener: (message: InspectorNotification) => void): this; + + /** + * Notification is issued every time when binding is called. + * @experimental + */ + prependOnceListener(event: "Runtime.bindingCalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when console API was called. + */ + prependOnceListener(event: "Runtime.consoleAPICalled", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: "Runtime.exceptionRevoked", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: "Runtime.exceptionThrown", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: "Runtime.executionContextCreated", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: "Runtime.executionContextDestroyed", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: "Runtime.executionContextsCleared", listener: () => void): this; + + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API + * call). + */ + prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + } + + // Top Level API + + /** + * Activate inspector on host and port. Equivalent to node --inspect=[[host:]port], but can be done programatically after node has started. + * If wait is true, will block until a client has connected to the inspect port and flow control has been passed to the debugger client. + * @param port Port to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param host Host to listen on for inspector connections. Optional, defaults to what was specified on the CLI. + * @param wait Block until a client has connected. Optional, defaults to false. + */ + function open(port?: number, host?: string, wait?: boolean): void; + + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + + /** + * Return the URL of the active inspector, or `undefined` if there is none. + */ + function url(): string | undefined; +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..f512be7 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,3 @@ +declare module "module" { + export = NodeJS.Module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..1cf524d --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,249 @@ +declare module "net" { + import * as stream from "stream"; + import * as events from "events"; + import * as dns from "dns"; + + type LookupFunction = (hostname: string, options: dns.LookupOneOptions, callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void) => void; + + interface AddressInfo { + address: string; + family: string; + port: number; + } + + interface SocketConstructorOpts { + fd?: number; + allowHalfOpen?: boolean; + readable?: boolean; + writable?: boolean; + } + + interface TcpSocketConnectOpts { + port: number; + host?: string; + localAddress?: string; + localPort?: number; + hints?: number; + family?: number; + lookup?: LookupFunction; + } + + interface IpcSocketConnectOpts { + path: string; + } + + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + + // Extended base methods + write(buffer: Buffer | Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Buffer | Uint8Array | string, encoding?: string, cb?: (err?: Error) => void): boolean; + + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + + setEncoding(encoding?: string): this; + pause(): this; + resume(): this; + setTimeout(timeout: number, callback?: () => void): this; + setNoDelay(noDelay?: boolean): this; + setKeepAlive(enable?: boolean, initialDelay?: number): this; + address(): AddressInfo | string; + unref(): void; + ref(): void; + + readonly bufferSize: number; + readonly bytesRead: number; + readonly bytesWritten: number; + readonly connecting: boolean; + readonly destroyed: boolean; + readonly localAddress: string; + readonly localPort: number; + readonly remoteAddress?: string; + readonly remoteFamily?: string; + readonly remotePort?: number; + + // Extended base methods + end(cb?: () => void): void; + end(buffer: Buffer | Uint8Array | string, cb?: () => void): void; + end(str: Buffer | Uint8Array | string, encoding?: string, cb?: () => void): void; + + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. data + * 4. drain + * 5. end + * 6. error + * 7. lookup + * 8. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (had_error: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + addListener(event: "timeout", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", had_error: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "timeout"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (had_error: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + on(event: "timeout", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (had_error: boolean) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + once(event: "timeout", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (had_error: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependListener(event: "timeout", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (had_error: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "lookup", listener: (err: Error, address: string, family: string | number, host: string) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + + interface ListenOptions { + port?: number; + host?: string; + backlog?: number; + path?: string; + exclusive?: boolean; + readableAll?: boolean; + writableAll?: boolean; + /** + * @default false + */ + ipv6Only?: boolean; + } + + // https://github.com/nodejs/node/blob/master/lib/net.js + class Server extends events.EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); + + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + close(callback?: (err?: Error) => void): this; + address(): AddressInfo | string | null; + getConnections(cb: (error: Error | null, count: number) => void): void; + ref(): this; + unref(): this; + maxConnections: number; + connections: number; + listening: boolean; + + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + } + + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number; + } + + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + function isIP(input: string): number; + function isIPv4(input: string): boolean; + function isIPv6(input: string): boolean; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..eba380e --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,205 @@ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + } + + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + } + + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T; + homedir: T; + } + + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + + function hostname(): string; + function loadavg(): number[]; + function uptime(): number; + function freemem(): number; + function totalmem(): number; + function cpus(): CpuInfo[]; + function type(): string; + function release(): string; + function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; + function homedir(): string; + function userInfo(options: { encoding: 'buffer' }): UserInfo; + function userInfo(options?: { encoding: string }): UserInfo; + const constants: { + UV_UDP_REUSEADDR: number; + // signals: { [key in NodeJS.Signals]: number; }; @todo: change after migration to typescript 2.1 + signals: { + SIGHUP: number; + SIGINT: number; + SIGQUIT: number; + SIGILL: number; + SIGTRAP: number; + SIGABRT: number; + SIGIOT: number; + SIGBUS: number; + SIGFPE: number; + SIGKILL: number; + SIGUSR1: number; + SIGSEGV: number; + SIGUSR2: number; + SIGPIPE: number; + SIGALRM: number; + SIGTERM: number; + SIGCHLD: number; + SIGSTKFLT: number; + SIGCONT: number; + SIGSTOP: number; + SIGTSTP: number; + SIGBREAK: number; + SIGTTIN: number; + SIGTTOU: number; + SIGURG: number; + SIGXCPU: number; + SIGXFSZ: number; + SIGVTALRM: number; + SIGPROF: number; + SIGWINCH: number; + SIGIO: number; + SIGPOLL: number; + SIGLOST: number; + SIGPWR: number; + SIGINFO: number; + SIGSYS: number; + SIGUNUSED: number; + }; + errno: { + E2BIG: number; + EACCES: number; + EADDRINUSE: number; + EADDRNOTAVAIL: number; + EAFNOSUPPORT: number; + EAGAIN: number; + EALREADY: number; + EBADF: number; + EBADMSG: number; + EBUSY: number; + ECANCELED: number; + ECHILD: number; + ECONNABORTED: number; + ECONNREFUSED: number; + ECONNRESET: number; + EDEADLK: number; + EDESTADDRREQ: number; + EDOM: number; + EDQUOT: number; + EEXIST: number; + EFAULT: number; + EFBIG: number; + EHOSTUNREACH: number; + EIDRM: number; + EILSEQ: number; + EINPROGRESS: number; + EINTR: number; + EINVAL: number; + EIO: number; + EISCONN: number; + EISDIR: number; + ELOOP: number; + EMFILE: number; + EMLINK: number; + EMSGSIZE: number; + EMULTIHOP: number; + ENAMETOOLONG: number; + ENETDOWN: number; + ENETRESET: number; + ENETUNREACH: number; + ENFILE: number; + ENOBUFS: number; + ENODATA: number; + ENODEV: number; + ENOENT: number; + ENOEXEC: number; + ENOLCK: number; + ENOLINK: number; + ENOMEM: number; + ENOMSG: number; + ENOPROTOOPT: number; + ENOSPC: number; + ENOSR: number; + ENOSTR: number; + ENOSYS: number; + ENOTCONN: number; + ENOTDIR: number; + ENOTEMPTY: number; + ENOTSOCK: number; + ENOTSUP: number; + ENOTTY: number; + ENXIO: number; + EOPNOTSUPP: number; + EOVERFLOW: number; + EPERM: number; + EPIPE: number; + EPROTO: number; + EPROTONOSUPPORT: number; + EPROTOTYPE: number; + ERANGE: number; + EROFS: number; + ESPIPE: number; + ESRCH: number; + ESTALE: number; + ETIME: number; + ETIMEDOUT: number; + ETXTBSY: number; + EWOULDBLOCK: number; + EXDEV: number; + }; + priority: { + PRIORITY_LOW: number; + PRIORITY_BELOW_NORMAL: number; + PRIORITY_NORMAL: number; + PRIORITY_ABOVE_NORMAL: number; + PRIORITY_HIGH: number; + PRIORITY_HIGHEST: number; + } + }; + function arch(): string; + function platform(): NodeJS.Platform; + function tmpdir(): string; + const EOL: string; + function endianness(): "BE" | "LE"; + /** + * Gets the priority of a process. + * Defaults to current process. + */ + function getPriority(pid?: number): number; + /** + * Sets the priority of the current process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(priority: number): void; + /** + * Sets the priority of the process specified process. + * @param priority Must be in range of -20 to 19 + */ + function setPriority(pid: number, priority: number): void; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000..76d8646 --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,212 @@ +{ + "_args": [ + [ + "@types/node@11.15.35", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "@types/node@11.15.35", + "_id": "@types/node@11.15.35", + "_inBundle": false, + "_integrity": "sha512-kmxE30w+R//Vh/+dlVS5DPPyzPtWtrMrJ9+io7jvkPtWv3X43ERA4HTcFEn/R7dtHO3HCMU1y3WKf3NDLYhQEQ==", + "_location": "/@types/node", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "@types/node@11.15.35", + "name": "@types/node", + "escapedName": "@types%2fnode", + "scope": "@types", + "rawSpec": "11.15.35", + "saveSpec": null, + "fetchSpec": "11.15.35" + }, + "_requiredBy": [ + "/node-latex" + ], + "_resolved": "https://registry.npmjs.org/@types/node/-/node-11.15.35.tgz", + "_spec": "11.15.35", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "bugs": { + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped/issues" + }, + "contributors": [ + { + "name": "Microsoft TypeScript", + "url": "https://github.com/Microsoft" + }, + { + "name": "DefinitelyTyped", + "url": "https://github.com/DefinitelyTyped" + }, + { + "name": "Alberto Schiabel", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alexander T.", + "url": "https://github.com/a-tarasyuk" + }, + { + "name": "Alvis HT Tang", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Bruno Scheufler", + "url": "https://github.com/brunoscheufler" + }, + { + "name": "Chigozirim C.", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "url": "https://github.com/eyqs" + }, + { + "name": "Flarna", + "url": "https://github.com/Flarna" + }, + { + "name": "Hannes Magnusson", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Hoàng Văn Khải", + "url": "https://github.com/KSXGitHub" + }, + { + "name": "Huw", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nicolas Even", + "url": "https://github.com/n-e" + }, + { + "name": "Nikita Galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "url": "https://github.com/eps1lon" + }, + { + "name": "Simon Schick", + "url": "https://github.com/SimonSchick" + }, + { + "name": "Thomas den Hollander", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Zane Hannan AU", + "url": "https://github.com/ZaneHannanAU" + }, + { + "name": "Jeremie Rodriguez", + "url": "https://github.com/jeremiergz" + }, + { + "name": "Samuel Ainsworth", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Jordi Oliveras Rovira", + "url": "https://github.com/j-oliveras" + }, + { + "name": "Thanik Bhongbhibhat", + "url": "https://github.com/bhongy" + }, + { + "name": "Ivan Sieder", + "url": "https://github.com/ivansieder" + }, + { + "name": "Minh Son Nguyen", + "url": "https://github.com/nguymin4" + }, + { + "name": "ExE Boss", + "url": "https://github.com/ExE-Boss" + } + ], + "dependencies": {}, + "description": "TypeScript definitions for Node.js", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", + "license": "MIT", + "main": "", + "name": "@types/node", + "repository": { + "type": "git", + "url": "git+https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "typeScriptVersion": "3.2", + "types": "index.d.ts", + "typesPublisherContentHash": "4ce7547e1ee4bbb21510f180b1247aa3f88ad51b20bbee606fb70104b782acce", + "typesVersions": { + "<=3.6": { + "*": [ + "ts3.6/*" + ] + } + }, + "version": "11.15.35" +} diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..2f4a549 --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,159 @@ +declare module "path" { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string; + /** + * The file extension (if any) such as '.html' + */ + ext?: string; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string; + } + + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param p string path to normalize. + */ + function normalize(p: string): string; + /** + * Join all arguments together and normalize the resulting path. + * Arguments must be strings. In v0.8, non-string arguments were silently ignored. In v0.10 and up, an exception is thrown. + * + * @param paths paths to join. + */ + function join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param pathSegments string paths to join. Non-string arguments are ignored. + */ + function resolve(...pathSegments: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * @param path path to test. + */ + function isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to}. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + */ + function relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param p the path to evaluate. + */ + function dirname(p: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param p the path to evaluate. + * @param ext optionally, an extension to remove from the result. + */ + function basename(p: string, ext?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string + * + * @param p the path to evaluate. + */ + function extname(p: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + const sep: '\\' | '/'; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + const delimiter: ';' | ':'; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param pathString path to evaluate. + */ + function parse(pathString: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathString path to evaluate. + */ + function format(pathObject: FormatInputPathObject): string; + + namespace posix { + function normalize(p: string): string; + function join(...paths: string[]): string; + function resolve(...pathSegments: string[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } + + namespace win32 { + function normalize(p: string): string; + function join(...paths: string[]): string; + function resolve(...pathSegments: string[]): string; + function isAbsolute(p: string): boolean; + function relative(from: string, to: string): string; + function dirname(p: string): string; + function basename(p: string, ext?: string): string; + function extname(p: string): string; + const sep: string; + const delimiter: string; + function parse(p: string): ParsedPath; + function format(pP: FormatInputPathObject): string; + } +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..054366d --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,232 @@ +declare module "perf_hooks" { + import { AsyncResource } from "async_hooks"; + + interface PerformanceEntry { + /** + * The total number of milliseconds elapsed for this entry. + * This value will not be meaningful for all Performance Entry types. + */ + readonly duration: number; + + /** + * The name of the performance entry. + */ + readonly name: string; + + /** + * The high resolution millisecond timestamp marking the starting time of the Performance Entry. + */ + readonly startTime: number; + + /** + * The type of the performance entry. + * Currently it may be one of: 'node', 'mark', 'measure', 'gc', or 'function'. + */ + readonly entryType: string; + + /** + * When performanceEntry.entryType is equal to 'gc', the performance.kind property identifies + * the type of garbage collection operation that occurred. + * The value may be one of perf_hooks.constants. + */ + readonly kind?: number; + } + + interface PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process completed bootstrap. + * If bootstrapping has not yet finished, the property has the value of -1. + */ + readonly bootstrapComplete: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop exited. + * If the event loop has not yet exited, the property has the value of -1. + * It can only have a value of not -1 in a handler of the 'exit' event. + */ + readonly loopExit: number; + + /** + * The high resolution millisecond timestamp at which the Node.js event loop started. + * If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1. + */ + readonly loopStart: number; + + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + */ + readonly nodeStart: number; + + /** + * The high resolution millisecond timestamp at which the V8 platform was initialized. + */ + readonly v8Start: number; + } + + interface Performance { + /** + * If name is not provided, removes all PerformanceMark objects from the Performance Timeline. + * If name is provided, removes only the named mark. + * @param name + */ + clearMarks(name?: string): void; + + /** + * Creates a new PerformanceMark entry in the Performance Timeline. + * A PerformanceMark is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'mark', + * and whose performanceEntry.duration is always 0. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * @param name + */ + mark(name?: string): void; + + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + */ + measure(name: string, startMark: string, endMark: string): void; + + /** + * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. + */ + readonly nodeTiming: PerformanceNodeTiming; + + /** + * @return the current high resolution millisecond timestamp + */ + now(): number; + + /** + * The timeOrigin specifies the high resolution millisecond timestamp from which all performance metric durations are measured. + */ + readonly timeOrigin: number; + + /** + * Wraps a function within a new function that measures the running time of the wrapped function. + * A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed. + * @param fn + */ + timerify any>(fn: T): T; + } + + interface PerformanceObserverEntryList { + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime. + */ + getEntries(): PerformanceEntry[]; + + /** + * @return a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.name is equal to name, and optionally, whose performanceEntry.entryType is equal to type. + */ + getEntriesByName(name: string, type?: string): PerformanceEntry[]; + + /** + * @return Returns a list of PerformanceEntry objects in chronological order with respect to performanceEntry.startTime + * whose performanceEntry.entryType is equal to type. + */ + getEntriesByType(type: string): PerformanceEntry[]; + } + + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + + /** + * Disconnects the PerformanceObserver instance from all notifications. + */ + disconnect(): void; + + /** + * Subscribes the PerformanceObserver instance to notifications of new PerformanceEntry instances identified by options.entryTypes. + * When options.buffered is false, the callback will be invoked once for every PerformanceEntry instance. + * Property buffered defaults to false. + * @param options + */ + observe(options: { entryTypes: ReadonlyArray, buffered?: boolean }): void; + } + + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + } + + const performance: Performance; + + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number; + } + + interface EventLoopDelayMonitor { + /** + * Enables the event loop delay sample timer. Returns `true` if the timer was started, `false` if it was already started. + */ + enable(): boolean; + /** + * Disables the event loop delay sample timer. Returns `true` if the timer was stopped, `false` if it was already stopped. + */ + disable(): boolean; + + /** + * Resets the collected histogram data. + */ + reset(): void; + + /** + * Returns the value at the given percentile. + * @param percentile A percentile value between 1 and 100. + */ + percentile(percentile: number): number; + + /** + * A `Map` object detailing the accumulated percentile distribution. + */ + readonly percentiles: Map; + + /** + * The number of times the event loop delay exceeded the maximum 1 hour eventloop delay threshold. + */ + readonly exceeds: number; + + /** + * The minimum recorded event loop delay. + */ + readonly min: number; + + /** + * The maximum recorded event loop delay. + */ + readonly max: number; + + /** + * The mean of the recorded event loop delays. + */ + readonly mean: number; + + /** + * The standard deviation of the recorded event loop delays. + */ + readonly stddev: number; + } + + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): EventLoopDelayMonitor; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..ccd5c9c --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,3 @@ +declare module "process" { + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..2b771d4 --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,68 @@ +declare module "punycode" { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + function decode(string: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + function encode(string: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + function toUnicode(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: ReadonlyArray): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..5e65b6a --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,29 @@ +declare module "querystring" { + interface StringifyOptions { + encodeURIComponent?: (str: string) => string; + } + + interface ParseOptions { + maxKeys?: number; + decodeURIComponent?: (str: string) => string; + } + + interface ParsedUrlQuery { [key: string]: string | string[]; } + + interface ParsedUrlQueryInput { + [key: string]: unknown; + } + + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + function escape(str: string): string; + function unescape(str: string): string; +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..e1fe4af --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,137 @@ +declare module "readline" { + import * as events from "events"; + import * as stream from "stream"; + + interface Key { + sequence?: string; + name?: string; + ctrl?: boolean; + meta?: boolean; + shift?: boolean; + } + + class Interface extends events.EventEmitter { + readonly terminal: boolean; + + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + + setPrompt(prompt: string): void; + prompt(preserveCursor?: boolean): void; + question(query: string, callback: (answer: string) => void): void; + pause(): this; + resume(): this; + close(): void; + write(data: string | Buffer, key?: Key): void; + + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + type ReadLine = Interface; // type forwarded for backwards compatiblity + + type Completer = (line: string) => CompleterResult; + type AsyncCompleter = (line: string, callback: (err?: null | Error, result?: CompleterResult) => void) => any; + + type CompleterResult = [string[], string]; + + interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream; + completer?: Completer | AsyncCompleter; + terminal?: boolean; + historySize?: number; + prompt?: string; + crlfDelay?: number; + removeHistoryDuplicates?: boolean; + escapeCodeTimeout?: number; + } + + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; + + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; + function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; + function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + function clearLine(stream: NodeJS.WritableStream, dir: number): void; + function clearScreenDown(stream: NodeJS.WritableStream): void; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..605f07c --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,390 @@ +declare module "repl" { + import { Interface, Completer, AsyncCompleter } from "readline"; + import { Context } from "vm"; + import { InspectOptions } from "util"; + + interface ReplOptions { + /** + * The input prompt to display. + * Default: `"> "` + */ + prompt?: string; + /** + * The `Readable` stream from which REPL input will be read. + * Default: `process.stdin` + */ + input?: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + * Default: `process.stdout` + */ + output?: NodeJS.WritableStream; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ + useColors?: boolean; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ + useGlobal?: boolean; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ + ignoreUndefined?: boolean; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean; + } + + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { options: InspectOptions }; + + type REPLCommandAction = (this: REPLServer, text: string) => void; + + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + + /** + * Provides a customizable Read-Eval-Print-Loop (REPL). + * + * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those + * according to a user-defined evaluation function, then output the result. Input and output + * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. + * + * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style + * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session + * state, error recovery, and customizable evaluation functions. + * + * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ + * be created directly using the JavaScript `new` keyword. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * Outdated alias for `input`. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * Outdated alias for `output`. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: { readonly [name: string]: REPLCommand | undefined }; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + + /** + * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked + * by typing a `.` followed by the `keyword`. + * + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * Readies the REPL instance for input from the user, printing the configured `prompt` to a + * new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * Clears any command that has been buffered but not yet executed. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @since v9.0.0 + */ + clearBufferedCommand(): void; + + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @param path The path to the history file + */ + setupHistory(path: string, cb: (err: Error | null, repl: this) => void): void; + + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol + + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + export const REPL_MODE_STRICT: symbol; // TODO: unique symbol + + /** + * Creates and starts a `repl.REPLServer` instance. + * + * @param options The options for the `REPLServer`. If `options` is a string, then it specifies + * the input prompt. + */ + function start(options?: string | ReplOptions): REPLServer; + + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + + constructor(err: Error); + } +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..07cf07d --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,310 @@ +declare module "stream" { + import * as events from "events"; + + class internal extends events.EventEmitter { + pipe(destination: T, options?: { end?: boolean; }): T; + } + + namespace internal { + class Stream extends internal { } + + interface ReadableOptions { + highWaterMark?: number; + encoding?: string; + objectMode?: boolean; + read?(this: Readable, size: number): void; + destroy?(this: Readable, error: Error | null, callback: (error: Error | null) => void): void; + autoDestroy?: boolean; + } + + class Readable extends Stream implements NodeJS.ReadableStream { + readable: boolean; + readonly readableFlowing: boolean | null; + readonly readableHighWaterMark: number; + readonly readableLength: number; + constructor(opts?: ReadableOptions); + _read(size: number): void; + read(size?: number): any; + setEncoding(encoding: string): this; + pause(): this; + resume(): this; + isPaused(): boolean; + unpipe(destination?: NodeJS.WritableStream): this; + unshift(chunk: any): void; + wrap(oldStream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: string): boolean; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableOptions { + highWaterMark?: number; + decodeStrings?: boolean; + defaultEncoding?: string; + objectMode?: boolean; + emitClose?: boolean; + write?(this: Writable, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Writable, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + destroy?(this: Writable, error: Error | null, callback: (error: Error | null) => void): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + autoDestroy?: boolean; + } + + class Writable extends Stream implements NodeJS.WritableStream { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: string, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding: string, cb?: () => void): void; + cork(): void; + uncork(): void; + destroy(error?: Error): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writableObjectMode?: boolean; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Duplex, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error: Error | null) => void): void; + } + + // Note: Duplex extends both Readable and Writable. + class Duplex extends Readable implements Writable { + writable: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + constructor(opts?: DuplexOptions); + _write(chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + _writev?(chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: string): this; + end(cb?: () => void): void; + end(chunk: any, cb?: () => void): void; + end(chunk: any, encoding?: string, cb?: () => void): void; + cork(): void; + uncork(): void; + } + + type TransformCallback = (error?: Error | null, data?: any) => void; + + interface TransformOptions extends DuplexOptions { + read?(this: Transform, size: number): void; + write?(this: Transform, chunk: any, encoding: string, callback: (error?: Error | null) => void): void; + writev?(this: Transform, chunks: Array<{ chunk: any, encoding: string }>, callback: (error?: Error | null) => void): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: string, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: string, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + + class PassThrough extends Transform { } + + interface FinishedOptions { + error?: boolean; + readable?: boolean; + writable?: boolean; + } + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options: FinishedOptions, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + function finished(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, callback: (err?: NodeJS.ErrnoException | null) => void): () => void; + namespace finished { + function __promisify__(stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, options?: FinishedOptions): Promise; + } + + function pipeline(stream1: NodeJS.ReadableStream, stream2: T, callback?: (err: NodeJS.ErrnoException | null) => void): T; + function pipeline(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: T, callback?: (err: NodeJS.ErrnoException | null) => void): T; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: T, + callback?: (err: NodeJS.ErrnoException | null) => void, + ): T; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: T, + callback?: (err: NodeJS.ErrnoException | null) => void, + ): T; + function pipeline( + streams: ReadonlyArray, + callback?: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array void)>, + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.WritableStream): Promise; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.WritableStream): Promise; + function __promisify__(stream1: NodeJS.ReadableStream, stream2: NodeJS.ReadWriteStream, stream3: NodeJS.ReadWriteStream, stream4: NodeJS.WritableStream): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream, + stream3: NodeJS.ReadWriteStream, + stream4: NodeJS.ReadWriteStream, + stream5: NodeJS.WritableStream, + ): Promise; + function __promisify__(streams: ReadonlyArray): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array, + ): Promise; + } + + interface Pipe { } + } + + export = internal; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..762a4d8 --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,9 @@ +declare module "string_decoder" { + interface NodeStringDecoder { + write(buffer: Buffer): string; + end(buffer?: Buffer): string; + } + const StringDecoder: { + new(encoding?: string): NodeStringDecoder; + }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..e64a673 --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,16 @@ +declare module "timers" { + function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + namespace setTimeout { + function __promisify__(ms: number): Promise; + function __promisify__(ms: number, value: T): Promise; + } + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; + namespace setImmediate { + function __promisify__(): Promise; + function __promisify__(value: T): Promise; + } + function clearImmediate(immediateId: NodeJS.Immediate): void; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..6e3a322 --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,398 @@ +declare module "tls" { + import * as crypto from "crypto"; + import * as dns from "dns"; + import * as net from "net"; + import * as stream from "stream"; + + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + + interface PeerCertificate { + subject: Certificate; + issuer: Certificate; + subjectaltname: string; + infoAccess: { [index: string]: string[] | undefined }; + modulus: string; + exponent: string; + valid_from: string; + valid_to: string; + fingerprint: string; + fingerprint256: string; + ext_key_usage: string[]; + serialNumber: string; + raw: Buffer; + } + + interface DetailedPeerCertificate extends PeerCertificate { + issuerCertificate: DetailedPeerCertificate; + } + + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + } + + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket, options?: { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext, + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean, + /** + * An optional net.Server instance. + */ + server?: net.Server, + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean, + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. Defaults to false. + */ + rejectUnauthorized?: boolean, + /** + * An array of strings or a Buffer naming possible NPN protocols. + * (Protocols should be ordered by their priority.) + */ + NPNProtocols?: ReadonlyArray | ReadonlyArray | ReadonlyArray | Buffer | Uint8Array, + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) When the server + * receives both NPN and ALPN extensions from the client, ALPN takes + * precedence over NPN and the server does not send an NPN extension + * to the client. + */ + ALPNProtocols?: ReadonlyArray | ReadonlyArray | ReadonlyArray | Buffer | Uint8Array, + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer, + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean + }); + + /** + * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. + */ + authorized: boolean; + /** + * The reason why the peer's certificate has not been verified. + * This property becomes available only when tlsSocket.authorized === false. + */ + authorizationError: Error; + /** + * Static boolean value, always true. + * May be used to distinguish TLS sockets from regular ones. + */ + encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + + /** + * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. + * @returns Returns an object representing the cipher name + * and the SSL/TLS protocol version of the current connection. + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the peer's certificate. + * The returned object has some properties corresponding to the field of the certificate. + * If detailed argument is true the full chain with issuer property will be returned, + * if false only the top certificate without issuer property. + * If the peer does not provide a certificate, it returns null or an empty object. + * @param detailed - If true; the full chain with issuer property will be returned. + * @returns An object representing the peer's certificate. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. + * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. + * The value `null` will be returned for server sockets or disconnected client sockets. + * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. + * @returns negotiated SSL/TLS protocol version of the current connection + */ + getProtocol(): string | null; + /** + * Could be used to speed up handshake establishment when reconnecting to the server. + * @returns ASN.1 encoded TLS session or undefined if none was negotiated. + */ + getSession(): Buffer | undefined; + /** + * NOTE: Works only with client TLS sockets. + * Useful only for debugging, for session reuse provide session option to tls.connect(). + * @returns TLS session ticket or undefined if none was negotiated. + */ + getTLSTicket(): Buffer | undefined; + /** + * Initiate TLS renegotiation process. + * + * NOTE: Can be used to request peer's certificate after the secure connection has been established. + * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. + * @param options - The options may contain the following fields: rejectUnauthorized, + * requestCert (See tls.createServer() for details). + * @param callback - callback(err) will be executed with null as err, once the renegotiation + * is successfully completed. + * @return `undefined` when socket is destroy, `false` if negotiaion can't be initiated. + */ + renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): undefined | boolean; + /** + * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by + * the TLS layer until the entire fragment is received and its integrity is verified; + * large fragments can span multiple roundtrips, and their processing can be delayed due to packet + * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, + * which may decrease overall server throughput. + * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). + * @returns Returns true on success, false otherwise. + */ + setMaxSendFragment(size: number): boolean; + + /** + * events.EventEmitter + * 1. OCSPResponse + * 2. secureConnect + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + } + + interface TlsOptions extends SecureContextOptions { + handshakeTimeout?: number; + requestCert?: boolean; + rejectUnauthorized?: boolean; + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; + sessionTimeout?: number; + ticketKeys?: Buffer; + } + + interface ConnectionOptions extends SecureContextOptions { + host?: string; + port?: number; + path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket + rejectUnauthorized?: boolean; // Defaults to true + NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; + checkServerIdentity?: typeof checkServerIdentity; + servername?: string; // SNI TLS Extension + session?: Buffer; + minDHSize?: number; + secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() + lookup?: net.LookupFunction; + timeout?: number; + } + + class Server extends net.Server { + addContext(hostName: string, credentials: SecureContextOptions): void; + + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + addListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; + emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + on(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + once(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; + prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; + prependOnceListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + } + + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + + type SecureVersion = 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; + + interface SecureContextOptions { + pfx?: string | Buffer | Array; + key?: string | Buffer | Array; + passphrase?: string; + cert?: string | Buffer | Array; + ca?: string | Buffer | Array; + ciphers?: string; + honorCipherOrder?: boolean; + ecdhCurve?: string; + clientCertEngine?: string; + crl?: string | Buffer | Array; + dhparam?: string | Buffer; + secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options + secureProtocol?: string; // SSL Method, e.g. SSLv23_method + sessionIdContext?: string; + /** + * Optionally set the maximum TLS version to allow. One + * of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. **Default:** `'TLSv1.2'`. + */ + maxVersion?: SecureVersion; + /** + * Optionally set the minimum TLS version to allow. One + * of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` changes the default to `'TLSv1'`. Using `--tls-v1.1` changes + * the default to `'TLSv1.1'`. + */ + minVersion?: SecureVersion; + } + + interface SecureContext { + context: any; + } + + /* + * Verifies the certificate `cert` is issued to host `host`. + * @host The hostname to verify the certificate against + * @cert PeerCertificate representing the peer's certificate + * + * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. + */ + function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * @deprecated + */ + function createSecurePair(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; + function createSecureContext(options?: SecureContextOptions): SecureContext; + function getCiphers(): string[]; + + const DEFAULT_ECDH_CURVE: string; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..9d1a59b --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,61 @@ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + export interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + + /** + * Creates and returns a Tracing object for the given set of categories. + */ + export function createTracing(options: CreateTracingOptions): Tracing; + + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is + * determined by the union of all currently-enabled `Tracing` objects and + * any categories enabled using the `--trace-event-categories` flag. + */ + export function getEnabledCategories(): string; +} diff --git a/node_modules/@types/node/ts3.6/assert.d.ts b/node_modules/@types/node/ts3.6/assert.d.ts new file mode 100644 index 0000000..f91a62a --- /dev/null +++ b/node_modules/@types/node/ts3.6/assert.d.ts @@ -0,0 +1,69 @@ +declare module 'assert' { + function assert(value: any, message?: string | Error): void; + namespace assert { + class AssertionError implements Error { + name: string; + message: string; + actual: any; + expected: any; + operator: string; + generatedMessage: boolean; + code: 'ERR_ASSERTION'; + + constructor(options?: { + message?: string; + actual?: any; + expected?: any; + operator?: string; + stackStartFn?: Function; + }); + } + + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: any, + expected: any, + message?: string | Error, + operator?: string, + stackStartFn?: Function, + ): never; + function ok(value: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use strictEqual() instead. */ + function equal(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notStrictEqual() instead. */ + function notEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use deepStrictEqual() instead. */ + function deepEqual(actual: any, expected: any, message?: string | Error): void; + /** @deprecated since v9.9.0 - use notDeepStrictEqual() instead. */ + function notDeepEqual(actual: any, expected: any, message?: string | Error): void; + function strictEqual(actual: any, expected: any, message?: string | Error): void; + function notStrictEqual(actual: any, expected: any, message?: string | Error): void; + function deepStrictEqual(actual: any, expected: any, message?: string | Error): void; + function notDeepStrictEqual(actual: any, expected: any, message?: string | Error): void; + + function throws(block: () => any, message?: string | Error): void; + function throws(block: () => any, error: RegExp | Function | Object | Error, message?: string | Error): void; + function doesNotThrow(block: () => any, message?: string | Error): void; + function doesNotThrow(block: () => any, error: RegExp | Function, message?: string | Error): void; + + function ifError(value: any): void; + + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: RegExp | Function | Object | Error, + message?: string | Error, + ): Promise; + function doesNotReject(block: (() => Promise) | Promise, message?: string | Error): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: RegExp | Function, + message?: string | Error, + ): Promise; + + const strict: typeof assert; + } + + export = assert; +} diff --git a/node_modules/@types/node/ts3.6/base.d.ts b/node_modules/@types/node/ts3.6/base.d.ts new file mode 100644 index 0000000..9080234 --- /dev/null +++ b/node_modules/@types/node/ts3.6/base.d.ts @@ -0,0 +1,54 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.2. + +// NOTE: TypeScript version-specific augmentations can be found in the following paths: +// - ~/base.d.ts - Shared definitions common to all TypeScript versions +// - ~/index.d.ts - Definitions specific to TypeScript 2.1 +// - ~/ts3.2/base.d.ts - Definitions specific to TypeScript 3.2 +// - ~/ts3.2/index.d.ts - Definitions specific to TypeScript 3.2 with assert pulled in + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// diff --git a/node_modules/@types/node/ts3.6/index.d.ts b/node_modules/@types/node/ts3.6/index.d.ts new file mode 100644 index 0000000..ed49ea6 --- /dev/null +++ b/node_modules/@types/node/ts3.6/index.d.ts @@ -0,0 +1,6 @@ +// NOTE: These definitions support NodeJS and TypeScript 3.2. +// This is required to enable typing assert in ts3.7 without causing errors +// Typically type modifiations should be made in base.d.ts instead of here + +/// +/// diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..8ae27b9 --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,52 @@ +declare module "tty" { + import * as net from "net"; + + function isatty(fd: number): boolean; + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + isRaw: boolean; + setRawMode(mode: boolean): void; + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + + clearLine(dir: Direction): void; + clearScreenDown(): void; + cursorTo(x: number, y: number): void; + /** + * @default `process.env` + */ + getColorDepth(env?: {}): number; + hasColors(depth?: number): boolean; + hasColors(env?: {}): boolean; + hasColors(depth: number, env?: {}): boolean; + getWindowSize(): [number, number]; + columns: number; + rows: number; + isTTY: boolean; + } +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..8b01cd3 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,104 @@ +declare module "url" { + import { ParsedUrlQuery, ParsedUrlQueryInput } from 'querystring'; + + interface UrlObjectCommon { + auth?: string; + hash?: string; + host?: string; + hostname?: string; + href?: string; + path?: string; + pathname?: string; + protocol?: string; + search?: string; + slashes?: boolean; + } + + // Input to `url.format` + interface UrlObject extends UrlObjectCommon { + port?: string | number; + query?: string | null | ParsedUrlQueryInput; + } + + // Output of `url.parse` + interface Url extends UrlObjectCommon { + port?: string; + query?: string | null | ParsedUrlQuery; + } + + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + + interface UrlWithStringQuery extends Url { + query: string | null; + } + + function parse(urlStr: string): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: false | undefined, slashesDenoteHost?: boolean): UrlWithStringQuery; + function parse(urlStr: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlStr: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + + function format(URL: URL, options?: URLFormatOptions): string; + function format(urlObject: UrlObject | string): string; + function resolve(from: string, to: string): string; + + function domainToASCII(domain: string): string; + function domainToUnicode(domain: string): string; + + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * @param url The file URL string or URL object to convert to a path. + */ + function fileURLToPath(url: string | URL): string; + + /** + * This function ensures that path is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * @param url The path to convert to a File URL. + */ + function pathToFileURL(url: string): URL; + + interface URLFormatOptions { + auth?: boolean; + fragment?: boolean; + search?: boolean; + unicode?: boolean; + } + + class URL { + constructor(input: string, base?: string | URL); + hash: string; + host: string; + hostname: string; + href: string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toString(): string; + toJSON(): string; + } + + class URLSearchParams implements Iterable<[string, string]> { + constructor(init?: URLSearchParams | string | { [key: string]: string | ReadonlyArray | undefined } | Iterable<[string, string]> | ReadonlyArray<[string, string]>); + append(name: string, value: string): void; + delete(name: string): void; + entries(): IterableIterator<[string, string]>; + forEach(callback: (value: string, name: string, searchParams: this) => void): void; + get(name: string): string | null; + getAll(name: string): string[]; + has(name: string): boolean; + keys(): IterableIterator; + set(name: string, value: string): void; + sort(): void; + toString(): string; + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..78554b6 --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,181 @@ +declare module "util" { + interface InspectOptions extends NodeJS.InspectOptions { } + function format(format: any, ...param: any[]): string; + function formatWithOptions(inspectOptions: InspectOptions, format: string, ...param: any[]): string; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function debug(string: string): void; + /** @deprecated since v0.11.3 - use `console.error()` instead. */ + function error(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function puts(...param: any[]): void; + /** @deprecated since v0.11.3 - use `console.log()` instead. */ + function print(...param: any[]): void; + /** @deprecated since v0.11.3 - use a third party module instead. */ + function log(string: string): void; + function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + function inspect(object: any, options: InspectOptions): string; + namespace inspect { + const custom: unique symbol; + let colors: { + [color: string]: [number, number] | undefined + }; + let styles: { + [style: string]: string | undefined + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + } + /** @deprecated since v4.0.0 - use `Array.isArray()` instead. */ + function isArray(object: any): object is any[]; + /** @deprecated since v4.0.0 - use `util.types.isRegExp()` instead. */ + function isRegExp(object: any): object is RegExp; + /** @deprecated since v4.0.0 - use `util.types.isDate()` instead. */ + function isDate(object: any): object is Date; + /** @deprecated since v4.0.0 - use `util.types.isNativeError()` instead. */ + function isError(object: any): object is Error; + function inherits(constructor: any, superConstructor: any): void; + function debuglog(key: string): (msg: string, ...param: any[]) => void; + /** @deprecated since v4.0.0 - use `typeof value === 'boolean'` instead. */ + function isBoolean(object: any): object is boolean; + /** @deprecated since v4.0.0 - use `Buffer.isBuffer()` instead. */ + function isBuffer(object: any): object is Buffer; + /** @deprecated since v4.0.0 - use `typeof value === 'function'` instead. */ + function isFunction(object: any): boolean; + /** @deprecated since v4.0.0 - use `value === null` instead. */ + function isNull(object: any): object is null; + /** @deprecated since v4.0.0 - use `value === null || value === undefined` instead. */ + function isNullOrUndefined(object: any): object is null | undefined; + /** @deprecated since v4.0.0 - use `typeof value === 'number'` instead. */ + function isNumber(object: any): object is number; + /** @deprecated since v4.0.0 - use `value !== null && typeof value === 'object'` instead. */ + function isObject(object: any): boolean; + /** @deprecated since v4.0.0 - use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. */ + function isPrimitive(object: any): boolean; + /** @deprecated since v4.0.0 - use `typeof value === 'string'` instead. */ + function isString(object: any): object is string; + /** @deprecated since v4.0.0 - use `typeof value === 'symbol'` instead. */ + function isSymbol(object: any): object is symbol; + /** @deprecated since v4.0.0 - use `value === undefined` instead. */ + function isUndefined(object: any): object is undefined; + function deprecate(fn: T, message: string): T; + function isDeepStrictEqual(val1: any, val2: any): boolean; + + interface CustomPromisify extends Function { + __promisify__: TCustom; + } + + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1) => Promise): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2) => Promise): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify(fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException) => void) => void; + function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + + function promisify(fn: CustomPromisify): TCustom; + function promisify(fn: (callback: (err: Error | null, result: TResult) => void) => void): () => Promise; + function promisify(fn: (callback: (err?: Error) => void) => void): () => Promise; + function promisify(fn: (arg1: T1, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, callback: (err?: Error) => void) => void): (arg1: T1) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: Error | null, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: Error) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: Error | null, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: Error) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + function promisify(fn: Function): Function; + + namespace promisify { + const custom: unique symbol; + } + + namespace types { + function isAnyArrayBuffer(object: any): boolean; + function isArgumentsObject(object: any): object is IArguments; + function isArrayBuffer(object: any): object is ArrayBuffer; + function isArrayBufferView(object: any): object is ArrayBufferView; + function isAsyncFunction(object: any): boolean; + function isBigInt64Array(value: any): value is BigInt64Array; + function isBigUint64Array(value: any): value is BigUint64Array; + function isBooleanObject(object: any): object is Boolean; + function isBoxedPrimitive(object: any): object is (Number | Boolean | String | Symbol /* | Object(BigInt) | Object(Symbol) */); + function isDataView(object: any): object is DataView; + function isDate(object: any): object is Date; + function isExternal(object: any): boolean; + function isFloat32Array(object: any): object is Float32Array; + function isFloat64Array(object: any): object is Float64Array; + function isGeneratorFunction(object: any): boolean; + function isGeneratorObject(object: any): boolean; + function isInt8Array(object: any): object is Int8Array; + function isInt16Array(object: any): object is Int16Array; + function isInt32Array(object: any): object is Int32Array; + function isMap(object: any): boolean; + function isMapIterator(object: any): boolean; + function isModuleNamespaceObject(value: any): boolean; + function isNativeError(object: any): object is Error; + function isNumberObject(object: any): object is Number; + function isPromise(object: any): boolean; + function isProxy(object: any): boolean; + function isRegExp(object: any): object is RegExp; + function isSet(object: any): boolean; + function isSetIterator(object: any): boolean; + function isSharedArrayBuffer(object: any): boolean; + function isStringObject(object: any): boolean; + function isSymbolObject(object: any): boolean; + function isTypedArray(object: any): object is NodeJS.TypedArray; + function isUint8Array(object: any): object is Uint8Array; + function isUint8ClampedArray(object: any): object is Uint8ClampedArray; + function isUint16Array(object: any): object is Uint16Array; + function isUint32Array(object: any): object is Uint32Array; + function isWeakMap(object: any): boolean; + function isWeakSet(object: any): boolean; + function isWebAssemblyCompiledModule(object: any): boolean; + } + + class TextDecoder { + readonly encoding: string; + readonly fatal: boolean; + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { fatal?: boolean; ignoreBOM?: boolean } + ); + decode( + input?: NodeJS.TypedArray | DataView | ArrayBuffer | null, + options?: { stream?: boolean } + ): string; + } + + class TextEncoder { + readonly encoding: string; + encode(input?: string): Uint8Array; + } +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..78e76e0 --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,50 @@ +declare module "v8" { + import { Readable } from "stream"; + + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + } + + function getHeapStatistics(): HeapInfo; + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + function setFlagsFromString(flags: string): void; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This conversation was marked as resolved by joyeecheung + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine, and may change from one version of V8 to the next. + */ + function getHeapSnapshot(): Readable; + + /** + * + * @param fileName The file path where the V8 heap snapshot is to be + * saved. If not specified, a file name with the pattern + * `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, + * `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from + * the main Node.js thread or the id of a worker thread. + */ + function writeHeapSnapshot(fileName?: string): string; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..8376d08 --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,64 @@ +declare module "vm" { + interface Context { + [key: string]: any; + } + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * Default: `''`. + */ + filename?: string; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * Default: `0`. + */ + lineOffset?: number; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * Default: `0` + */ + columnOffset?: number; + } + interface ScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + cachedData?: Buffer; + produceCachedData?: boolean; + } + interface RunningScriptOptions extends BaseOptions { + displayErrors?: boolean; + timeout?: number; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer; + /** + * Specifies whether to produce new cache data. + * Default: `false`, + */ + produceCachedData?: boolean; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context; + + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[]; + } + class Script { + constructor(code: string, options?: ScriptOptions); + runInContext(contextifiedSandbox: Context, options?: RunningScriptOptions): any; + runInNewContext(sandbox?: Context, options?: RunningScriptOptions): any; + runInThisContext(options?: RunningScriptOptions): any; + } + function createContext(sandbox?: Context): Context; + function isContext(sandbox: Context): boolean; + function runInContext(code: string, contextifiedSandbox: Context, options?: RunningScriptOptions | string): any; + function runInNewContext(code: string, sandbox?: Context, options?: RunningScriptOptions | string): any; + function runInThisContext(code: string, options?: RunningScriptOptions | string): any; + function compileFunction(code: string, params?: ReadonlyArray, options?: CompileFunctionOptions): Function; +} diff --git a/node_modules/@types/node/worker_threads.d.ts b/node_modules/@types/node/worker_threads.d.ts new file mode 100644 index 0000000..8c15436 --- /dev/null +++ b/node_modules/@types/node/worker_threads.d.ts @@ -0,0 +1,143 @@ +declare module "worker_threads" { + import { Context } from "vm"; + import { EventEmitter } from "events"; + import { Readable, Writable } from "stream"; + + const isMainThread: boolean; + const parentPort: null | MessagePort; + const SHARE_ENV: unique symbol; + const threadId: number; + const workerData: any; + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + } + + class MessagePort extends EventEmitter { + close(): void; + postMessage(value: any, transferList?: ReadonlyArray): void; + ref(): void; + unref(): void; + start(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface WorkerOptions { + eval?: boolean; + env?: NodeJS.ProcessEnv | typeof SHARE_ENV; + workerData?: any; + stdin?: boolean; + stdout?: boolean; + stderr?: boolean; + execArgv?: string[]; + } + + class Worker extends EventEmitter { + readonly stdin: Writable | null; + readonly stdout: Readable; + readonly stderr: Readable; + readonly threadId: number; + + constructor(filename: string, options?: WorkerOptions); + + postMessage(value: any, transferList?: ReadonlyArray): void; + ref(): void; + unref(): void; + terminate(callback?: (err: Error, exitCode: number) => void): void; + /** + * Transfer a `MessagePort` to a different `vm` Context. The original `port` + * object will be rendered unusable, and the returned `MessagePort` instance will + * take its place. + * + * The returned `MessagePort` will be an object in the target context, and will + * inherit from its global `Object` class. Objects passed to the + * `port.onmessage()` listener will also be created in the target context + * and inherit from its global `Object` class. + * + * However, the created `MessagePort` will no longer inherit from + * `EventEmitter`, and only `port.onmessage()` can be used to receive + * events using it. + */ + moveMessagePortToContext(port: MessagePort, context: Context): MessagePort; + + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "online", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "error", err: Error): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "online", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "online", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "error", listener: (err: Error) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } +} diff --git a/node_modules/@types/node/zlib.d.ts b/node_modules/@types/node/zlib.d.ts new file mode 100644 index 0000000..b6e7a71 --- /dev/null +++ b/node_modules/@types/node/zlib.d.ts @@ -0,0 +1,353 @@ +declare module "zlib" { + import * as stream from "stream"; + + interface ZlibOptions { + /** + * @default constants.Z_NO_FLUSH + */ + flush?: number; + /** + * @default constants.Z_FINISH + */ + finishFlush?: number; + /** + * @default 16*1024 + */ + chunkSize?: number; + windowBits?: number; + level?: number; // compression only + memLevel?: number; // compression only + strategy?: number; // compression only + dictionary?: Buffer | NodeJS.TypedArray | DataView | ArrayBuffer; // deflate/inflate only, empty dictionary by default + info?: boolean; + } + + interface BrotliOptions { + /** + * @default constants.BROTLI_OPERATION_PROCESS + */ + flush?: number; + /** + * @default constants.BROTLI_OPERATION_FINISH + */ + finishFlush?: number; + /** + * @default 16*1024 + */ + chunkSize?: number; + params?: { + /** + * Each key is a `constants.BROTLI_*` constant. + */ + [key: number]: boolean | number; + }; + } + + interface Zlib { + /** @deprecated Use bytesWritten instead. */ + readonly bytesRead: number; + readonly bytesWritten: number; + shell?: boolean | string; + close(callback?: () => void): void; + flush(kind?: number | (() => void), callback?: () => void): void; + } + + interface ZlibParams { + params(level: number, strategy: number, callback: () => void): void; + } + + interface ZlibReset { + reset(): void; + } + + interface BrotliCompress extends stream.Transform, Zlib { } + interface BrotliDecompress extends stream.Transform, Zlib { } + interface Gzip extends stream.Transform, Zlib { } + interface Gunzip extends stream.Transform, Zlib { } + interface Deflate extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface Inflate extends stream.Transform, Zlib, ZlibReset { } + interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams { } + interface InflateRaw extends stream.Transform, Zlib, ZlibReset { } + interface Unzip extends stream.Transform, Zlib { } + + function createBrotliCompress(options?: BrotliOptions): BrotliCompress; + function createBrotliDecompress(options?: BrotliOptions): BrotliDecompress; + function createGzip(options?: ZlibOptions): Gzip; + function createGunzip(options?: ZlibOptions): Gunzip; + function createDeflate(options?: ZlibOptions): Deflate; + function createInflate(options?: ZlibOptions): Inflate; + function createDeflateRaw(options?: ZlibOptions): DeflateRaw; + function createInflateRaw(options?: ZlibOptions): InflateRaw; + function createUnzip(options?: ZlibOptions): Unzip; + + type InputType = string | Buffer | DataView | ArrayBuffer | NodeJS.TypedArray; + + type CompressCallback = (error: Error | null, result: Buffer) => void; + + function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; + function brotliCompress(buf: InputType, callback: CompressCallback): void; + function brotliCompressSync(buf: InputType, options?: BrotliOptions): Buffer; + function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; + function brotliDecompress(buf: InputType, callback: CompressCallback): void; + function brotliDecompressSync(buf: InputType, options?: BrotliOptions): Buffer; + function deflate(buf: InputType, callback: CompressCallback): void; + function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function deflateRaw(buf: InputType, callback: CompressCallback): void; + function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function gzip(buf: InputType, callback: CompressCallback): void; + function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function gunzip(buf: InputType, callback: CompressCallback): void; + function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflate(buf: InputType, callback: CompressCallback): void; + function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; + function inflateRaw(buf: InputType, callback: CompressCallback): void; + function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; + function unzip(buf: InputType, callback: CompressCallback): void; + function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; + function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + + namespace constants { + const BROTLI_DECODE: number; + const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: number; + const BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: number; + const BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: number; + const BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: number; + const BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: number; + const BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: number; + const BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: number; + const BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: number; + const BROTLI_DECODER_ERROR_FORMAT_DISTANCE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: number; + const BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_1: number; + const BROTLI_DECODER_ERROR_FORMAT_PADDING_2: number; + const BROTLI_DECODER_ERROR_FORMAT_RESERVED: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: number; + const BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: number; + const BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: number; + const BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: number; + const BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: number; + const BROTLI_DECODER_ERROR_UNREACHABLE: number; + const BROTLI_DECODER_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_NO_ERROR: number; + const BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: number; + const BROTLI_DECODER_PARAM_LARGE_WINDOW: number; + const BROTLI_DECODER_RESULT_ERROR: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: number; + const BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: number; + const BROTLI_DECODER_RESULT_SUCCESS: number; + const BROTLI_DECODER_SUCCESS: number; + + const BROTLI_DEFAULT_MODE: number; + const BROTLI_DEFAULT_QUALITY: number; + const BROTLI_DEFAULT_WINDOW: number; + const BROTLI_ENCODE: number; + const BROTLI_LARGE_MAX_WINDOW_BITS: number; + const BROTLI_MAX_INPUT_BLOCK_BITS: number; + const BROTLI_MAX_QUALITY: number; + const BROTLI_MAX_WINDOW_BITS: number; + const BROTLI_MIN_INPUT_BLOCK_BITS: number; + const BROTLI_MIN_QUALITY: number; + const BROTLI_MIN_WINDOW_BITS: number; + + const BROTLI_MODE_FONT: number; + const BROTLI_MODE_GENERIC: number; + const BROTLI_MODE_TEXT: number; + + const BROTLI_OPERATION_EMIT_METADATA: number; + const BROTLI_OPERATION_FINISH: number; + const BROTLI_OPERATION_FLUSH: number; + const BROTLI_OPERATION_PROCESS: number; + + const BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: number; + const BROTLI_PARAM_LARGE_WINDOW: number; + const BROTLI_PARAM_LGBLOCK: number; + const BROTLI_PARAM_LGWIN: number; + const BROTLI_PARAM_MODE: number; + const BROTLI_PARAM_NDIRECT: number; + const BROTLI_PARAM_NPOSTFIX: number; + const BROTLI_PARAM_QUALITY: number; + const BROTLI_PARAM_SIZE_HINT: number; + + const DEFLATE: number; + const DEFLATERAW: number; + const GUNZIP: number; + const GZIP: number; + const INFLATE: number; + const INFLATERAW: number; + const UNZIP: number; + + const Z_BEST_COMPRESSION: number; + const Z_BEST_SPEED: number; + const Z_BLOCK: number; + const Z_BUF_ERROR: number; + const Z_DATA_ERROR: number; + + const Z_DEFAULT_CHUNK: number; + const Z_DEFAULT_COMPRESSION: number; + const Z_DEFAULT_LEVEL: number; + const Z_DEFAULT_MEMLEVEL: number; + const Z_DEFAULT_STRATEGY: number; + const Z_DEFAULT_WINDOWBITS: number; + + const Z_ERRNO: number; + const Z_FILTERED: number; + const Z_FINISH: number; + const Z_FIXED: number; + const Z_FULL_FLUSH: number; + const Z_HUFFMAN_ONLY: number; + const Z_MAX_CHUNK: number; + const Z_MAX_LEVEL: number; + const Z_MAX_MEMLEVEL: number; + const Z_MAX_WINDOWBITS: number; + const Z_MEM_ERROR: number; + const Z_MIN_CHUNK: number; + const Z_MIN_LEVEL: number; + const Z_MIN_MEMLEVEL: number; + const Z_MIN_WINDOWBITS: number; + const Z_NEED_DICT: number; + const Z_NO_COMPRESSION: number; + const Z_NO_FLUSH: number; + const Z_OK: number; + const Z_PARTIAL_FLUSH: number; + const Z_RLE: number; + const Z_STREAM_END: number; + const Z_STREAM_ERROR: number; + const Z_SYNC_FLUSH: number; + const Z_VERSION_ERROR: number; + const ZLIB_VERNUM: number; + } + + /** + * @deprecated + */ + const Z_NO_FLUSH: number; + /** + * @deprecated + */ + const Z_PARTIAL_FLUSH: number; + /** + * @deprecated + */ + const Z_SYNC_FLUSH: number; + /** + * @deprecated + */ + const Z_FULL_FLUSH: number; + /** + * @deprecated + */ + const Z_FINISH: number; + /** + * @deprecated + */ + const Z_BLOCK: number; + /** + * @deprecated + */ + const Z_TREES: number; + /** + * @deprecated + */ + const Z_OK: number; + /** + * @deprecated + */ + const Z_STREAM_END: number; + /** + * @deprecated + */ + const Z_NEED_DICT: number; + /** + * @deprecated + */ + const Z_ERRNO: number; + /** + * @deprecated + */ + const Z_STREAM_ERROR: number; + /** + * @deprecated + */ + const Z_DATA_ERROR: number; + /** + * @deprecated + */ + const Z_MEM_ERROR: number; + /** + * @deprecated + */ + const Z_BUF_ERROR: number; + /** + * @deprecated + */ + const Z_VERSION_ERROR: number; + /** + * @deprecated + */ + const Z_NO_COMPRESSION: number; + /** + * @deprecated + */ + const Z_BEST_SPEED: number; + /** + * @deprecated + */ + const Z_BEST_COMPRESSION: number; + /** + * @deprecated + */ + const Z_DEFAULT_COMPRESSION: number; + /** + * @deprecated + */ + const Z_FILTERED: number; + /** + * @deprecated + */ + const Z_HUFFMAN_ONLY: number; + /** + * @deprecated + */ + const Z_RLE: number; + /** + * @deprecated + */ + const Z_FIXED: number; + /** + * @deprecated + */ + const Z_DEFAULT_STRATEGY: number; + /** + * @deprecated + */ + const Z_BINARY: number; + /** + * @deprecated + */ + const Z_TEXT: number; + /** + * @deprecated + */ + const Z_ASCII: number; + /** + * @deprecated + */ + const Z_UNKNOWN: number; + /** + * @deprecated + */ + const Z_DEFLATED: number; +} diff --git a/node_modules/balanced-match/.npmignore b/node_modules/balanced-match/.npmignore new file mode 100644 index 0000000..ae5d8c3 --- /dev/null +++ b/node_modules/balanced-match/.npmignore @@ -0,0 +1,5 @@ +test +.gitignore +.travis.yml +Makefile +example.js diff --git a/node_modules/balanced-match/LICENSE.md b/node_modules/balanced-match/LICENSE.md new file mode 100644 index 0000000..2cdc8e4 --- /dev/null +++ b/node_modules/balanced-match/LICENSE.md @@ -0,0 +1,21 @@ +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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/balanced-match/README.md b/node_modules/balanced-match/README.md new file mode 100644 index 0000000..08e918c --- /dev/null +++ b/node_modules/balanced-match/README.md @@ -0,0 +1,91 @@ +# balanced-match + +Match balanced string pairs, like `{` and `}` or `` and ``. Supports regular expressions as well! + +[![build status](https://secure.travis-ci.org/juliangruber/balanced-match.svg)](http://travis-ci.org/juliangruber/balanced-match) +[![downloads](https://img.shields.io/npm/dm/balanced-match.svg)](https://www.npmjs.org/package/balanced-match) + +[![testling badge](https://ci.testling.com/juliangruber/balanced-match.png)](https://ci.testling.com/juliangruber/balanced-match) + +## Example + +Get the first matching pair of braces: + +```js +var balanced = require('balanced-match'); + +console.log(balanced('{', '}', 'pre{in{nested}}post')); +console.log(balanced('{', '}', 'pre{first}between{second}post')); +console.log(balanced(/\s+\{\s+/, /\s+\}\s+/, 'pre { in{nest} } post')); +``` + +The matches are: + +```bash +$ node example.js +{ start: 3, end: 14, pre: 'pre', body: 'in{nested}', post: 'post' } +{ start: 3, + end: 9, + pre: 'pre', + body: 'first', + post: 'between{second}post' } +{ start: 3, end: 17, pre: 'pre', body: 'in{nest}', post: 'post' } +``` + +## API + +### var m = balanced(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +object with those keys: + +* **start** the index of the first match of `a` +* **end** the index of the matching `b` +* **pre** the preamble, `a` and `b` not included +* **body** the match, `a` and `b` not included +* **post** the postscript, `a` and `b` not included + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `['{', 'a', '']` and `{a}}` will match `['', 'a', '}']`. + +### var r = balanced.range(a, b, str) + +For the first non-nested matching pair of `a` and `b` in `str`, return an +array with indexes: `[ , ]`. + +If there's no match, `undefined` will be returned. + +If the `str` contains more `a` than `b` / there are unmatched pairs, the first match that was closed will be used. For example, `{{a}` will match `[ 1, 3 ]` and `{a}}` will match `[0, 2]`. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install balanced-match +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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/balanced-match/index.js b/node_modules/balanced-match/index.js new file mode 100644 index 0000000..1685a76 --- /dev/null +++ b/node_modules/balanced-match/index.js @@ -0,0 +1,59 @@ +'use strict'; +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [ left, right ]; + } + } + + return result; +} diff --git a/node_modules/balanced-match/package.json b/node_modules/balanced-match/package.json new file mode 100644 index 0000000..c13069a --- /dev/null +++ b/node_modules/balanced-match/package.json @@ -0,0 +1,81 @@ +{ + "_args": [ + [ + "balanced-match@1.0.0", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "balanced-match@1.0.0", + "_id": "balanced-match@1.0.0", + "_inBundle": false, + "_integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "_location": "/balanced-match", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "balanced-match@1.0.0", + "name": "balanced-match", + "escapedName": "balanced-match", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" + }, + "_requiredBy": [ + "/brace-expansion" + ], + "_resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", + "_spec": "1.0.0", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/balanced-match/issues" + }, + "dependencies": {}, + "description": "Match balanced character pairs, like \"{\" and \"}\"", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/balanced-match", + "keywords": [ + "match", + "regexp", + "test", + "balanced", + "parse" + ], + "license": "MIT", + "main": "index.js", + "name": "balanced-match", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/balanced-match.git" + }, + "scripts": { + "bench": "make bench", + "test": "make test" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.0.0" +} diff --git a/node_modules/brace-expansion/LICENSE b/node_modules/brace-expansion/LICENSE new file mode 100644 index 0000000..de32266 --- /dev/null +++ b/node_modules/brace-expansion/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2013 Julian Gruber + +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/brace-expansion/README.md b/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..6b4e0e1 --- /dev/null +++ b/node_modules/brace-expansion/README.md @@ -0,0 +1,129 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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/brace-expansion/index.js b/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..0478be8 --- /dev/null +++ b/node_modules/brace-expansion/index.js @@ -0,0 +1,201 @@ +var concatMap = require('concat-map'); +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function identity(e) { + return e; +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + var post = m.post.length + ? expand(m.post, false) + : ['']; + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = concatMap(n, function(el) { return expand(el, false) }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + + return expansions; +} + diff --git a/node_modules/brace-expansion/package.json b/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..e59bb96 --- /dev/null +++ b/node_modules/brace-expansion/package.json @@ -0,0 +1,79 @@ +{ + "_args": [ + [ + "brace-expansion@1.1.11", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "brace-expansion@1.1.11", + "_id": "brace-expansion@1.1.11", + "_inBundle": false, + "_integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "_location": "/brace-expansion", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "brace-expansion@1.1.11", + "name": "brace-expansion", + "escapedName": "brace-expansion", + "rawSpec": "1.1.11", + "saveSpec": null, + "fetchSpec": "1.1.11" + }, + "_requiredBy": [ + "/minimatch" + ], + "_resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "_spec": "1.1.11", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/brace-expansion/issues" + }, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + }, + "description": "Brace expansion as known from sh/bash", + "devDependencies": { + "matcha": "^0.7.0", + "tape": "^4.6.0" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "keywords": [], + "license": "MIT", + "main": "index.js", + "name": "brace-expansion", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "scripts": { + "bench": "matcha test/perf/bench.js", + "gentest": "bash test/generate.sh", + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + }, + "version": "1.1.11" +} diff --git a/node_modules/concat-map/.travis.yml b/node_modules/concat-map/.travis.yml new file mode 100644 index 0000000..f1d0f13 --- /dev/null +++ b/node_modules/concat-map/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - 0.4 + - 0.6 diff --git a/node_modules/concat-map/LICENSE b/node_modules/concat-map/LICENSE new file mode 100644 index 0000000..ee27ba4 --- /dev/null +++ b/node_modules/concat-map/LICENSE @@ -0,0 +1,18 @@ +This software is released under 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/concat-map/README.markdown b/node_modules/concat-map/README.markdown new file mode 100644 index 0000000..408f70a --- /dev/null +++ b/node_modules/concat-map/README.markdown @@ -0,0 +1,62 @@ +concat-map +========== + +Concatenative mapdashery. + +[![browser support](http://ci.testling.com/substack/node-concat-map.png)](http://ci.testling.com/substack/node-concat-map) + +[![build status](https://secure.travis-ci.org/substack/node-concat-map.png)](http://travis-ci.org/substack/node-concat-map) + +example +======= + +``` js +var concatMap = require('concat-map'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); +``` + +*** + +``` +[ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ] +``` + +methods +======= + +``` js +var concatMap = require('concat-map') +``` + +concatMap(xs, fn) +----------------- + +Return an array of concatenated elements by calling `fn(x, i)` for each element +`x` and each index `i` in the array `xs`. + +When `fn(x, i)` returns an array, its result will be concatenated with the +result array. If `fn(x, i)` returns anything else, that value will be pushed +onto the end of the result array. + +install +======= + +With [npm](http://npmjs.org) do: + +``` +npm install concat-map +``` + +license +======= + +MIT + +notes +===== + +This module was written while sitting high above the ground in a tree. diff --git a/node_modules/concat-map/example/map.js b/node_modules/concat-map/example/map.js new file mode 100644 index 0000000..3365621 --- /dev/null +++ b/node_modules/concat-map/example/map.js @@ -0,0 +1,6 @@ +var concatMap = require('../'); +var xs = [ 1, 2, 3, 4, 5, 6 ]; +var ys = concatMap(xs, function (x) { + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; +}); +console.dir(ys); diff --git a/node_modules/concat-map/index.js b/node_modules/concat-map/index.js new file mode 100644 index 0000000..b29a781 --- /dev/null +++ b/node_modules/concat-map/index.js @@ -0,0 +1,13 @@ +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; + +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; diff --git a/node_modules/concat-map/package.json b/node_modules/concat-map/package.json new file mode 100644 index 0000000..dfecb9d --- /dev/null +++ b/node_modules/concat-map/package.json @@ -0,0 +1,92 @@ +{ + "_args": [ + [ + "concat-map@0.0.1", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "concat-map@0.0.1", + "_id": "concat-map@0.0.1", + "_inBundle": false, + "_integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "_location": "/concat-map", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "concat-map@0.0.1", + "name": "concat-map", + "escapedName": "concat-map", + "rawSpec": "0.0.1", + "saveSpec": null, + "fetchSpec": "0.0.1" + }, + "_requiredBy": [ + "/brace-expansion" + ], + "_resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "_spec": "0.0.1", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "James Halliday", + "email": "mail@substack.net", + "url": "http://substack.net" + }, + "bugs": { + "url": "https://github.com/substack/node-concat-map/issues" + }, + "description": "concatenative mapdashery", + "devDependencies": { + "tape": "~2.4.0" + }, + "directories": { + "example": "example", + "test": "test" + }, + "homepage": "https://github.com/substack/node-concat-map#readme", + "keywords": [ + "concat", + "concatMap", + "map", + "functional", + "higher-order" + ], + "license": "MIT", + "main": "index.js", + "name": "concat-map", + "repository": { + "type": "git", + "url": "git://github.com/substack/node-concat-map.git" + }, + "scripts": { + "test": "tape test/*.js" + }, + "testling": { + "files": "test/*.js", + "browsers": { + "ie": [ + 6, + 7, + 8, + 9 + ], + "ff": [ + 3.5, + 10, + 15 + ], + "chrome": [ + 10, + 22 + ], + "safari": [ + 5.1 + ], + "opera": [ + 12 + ] + } + }, + "version": "0.0.1" +} diff --git a/node_modules/concat-map/test/map.js b/node_modules/concat-map/test/map.js new file mode 100644 index 0000000..fdbd702 --- /dev/null +++ b/node_modules/concat-map/test/map.js @@ -0,0 +1,39 @@ +var concatMap = require('../'); +var test = require('tape'); + +test('empty or not', function (t) { + var xs = [ 1, 2, 3, 4, 5, 6 ]; + var ixes = []; + var ys = concatMap(xs, function (x, ix) { + ixes.push(ix); + return x % 2 ? [ x - 0.1, x, x + 0.1 ] : []; + }); + t.same(ys, [ 0.9, 1, 1.1, 2.9, 3, 3.1, 4.9, 5, 5.1 ]); + t.same(ixes, [ 0, 1, 2, 3, 4, 5 ]); + t.end(); +}); + +test('always something', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : [ x ]; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('scalars', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function (x) { + return x === 'b' ? [ 'B', 'B', 'B' ] : x; + }); + t.same(ys, [ 'a', 'B', 'B', 'B', 'c', 'd' ]); + t.end(); +}); + +test('undefs', function (t) { + var xs = [ 'a', 'b', 'c', 'd' ]; + var ys = concatMap(xs, function () {}); + t.same(ys, [ undefined, undefined, undefined, undefined ]); + t.end(); +}); diff --git a/node_modules/core-util-is/LICENSE b/node_modules/core-util-is/LICENSE new file mode 100644 index 0000000..d8d7f94 --- /dev/null +++ b/node_modules/core-util-is/LICENSE @@ -0,0 +1,19 @@ +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. diff --git a/node_modules/core-util-is/README.md b/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/node_modules/core-util-is/float.patch b/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // 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); +- } +- +- // 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)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- 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) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = 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 = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-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); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/node_modules/core-util-is/lib/util.js b/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..ff4c851 --- /dev/null +++ b/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// 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); +} diff --git a/node_modules/core-util-is/package.json b/node_modules/core-util-is/package.json new file mode 100644 index 0000000..77d37ae --- /dev/null +++ b/node_modules/core-util-is/package.json @@ -0,0 +1,66 @@ +{ + "_args": [ + [ + "core-util-is@1.0.2", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "core-util-is@1.0.2", + "_id": "core-util-is@1.0.2", + "_inBundle": false, + "_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=", + "_location": "/core-util-is", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "core-util-is@1.0.2", + "name": "core-util-is", + "escapedName": "core-util-is", + "rawSpec": "1.0.2", + "saveSpec": null, + "fetchSpec": "1.0.2" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", + "_spec": "1.0.2", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "description": "The `util.is*` functions introduced in Node v0.12.", + "devDependencies": { + "tap": "^2.3.0" + }, + "homepage": "https://github.com/isaacs/core-util-is#readme", + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "license": "MIT", + "main": "lib/util.js", + "name": "core-util-is", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "scripts": { + "test": "tap test.js" + }, + "version": "1.0.2" +} diff --git a/node_modules/core-util-is/test.js b/node_modules/core-util-is/test.js new file mode 100644 index 0000000..1a490c6 --- /dev/null +++ b/node_modules/core-util-is/test.js @@ -0,0 +1,68 @@ +var assert = require('tap'); + +var t = require('./lib/util'); + +assert.equal(t.isArray([]), true); +assert.equal(t.isArray({}), false); + +assert.equal(t.isBoolean(null), false); +assert.equal(t.isBoolean(true), true); +assert.equal(t.isBoolean(false), true); + +assert.equal(t.isNull(null), true); +assert.equal(t.isNull(undefined), false); +assert.equal(t.isNull(false), false); +assert.equal(t.isNull(), false); + +assert.equal(t.isNullOrUndefined(null), true); +assert.equal(t.isNullOrUndefined(undefined), true); +assert.equal(t.isNullOrUndefined(false), false); +assert.equal(t.isNullOrUndefined(), true); + +assert.equal(t.isNumber(null), false); +assert.equal(t.isNumber('1'), false); +assert.equal(t.isNumber(1), true); + +assert.equal(t.isString(null), false); +assert.equal(t.isString('1'), true); +assert.equal(t.isString(1), false); + +assert.equal(t.isSymbol(null), false); +assert.equal(t.isSymbol('1'), false); +assert.equal(t.isSymbol(1), false); +assert.equal(t.isSymbol(Symbol()), true); + +assert.equal(t.isUndefined(null), false); +assert.equal(t.isUndefined(undefined), true); +assert.equal(t.isUndefined(false), false); +assert.equal(t.isUndefined(), true); + +assert.equal(t.isRegExp(null), false); +assert.equal(t.isRegExp('1'), false); +assert.equal(t.isRegExp(new RegExp()), true); + +assert.equal(t.isObject({}), true); +assert.equal(t.isObject([]), true); +assert.equal(t.isObject(new RegExp()), true); +assert.equal(t.isObject(new Date()), true); + +assert.equal(t.isDate(null), false); +assert.equal(t.isDate('1'), false); +assert.equal(t.isDate(new Date()), true); + +assert.equal(t.isError(null), false); +assert.equal(t.isError({ err: true }), false); +assert.equal(t.isError(new Error()), true); + +assert.equal(t.isFunction(null), false); +assert.equal(t.isFunction({ }), false); +assert.equal(t.isFunction(function() {}), true); + +assert.equal(t.isPrimitive(null), true); +assert.equal(t.isPrimitive(''), true); +assert.equal(t.isPrimitive(0), true); +assert.equal(t.isPrimitive(new Date()), false); + +assert.equal(t.isBuffer(null), false); +assert.equal(t.isBuffer({}), false); +assert.equal(t.isBuffer(new Buffer(0)), true); diff --git a/node_modules/fs-extra/.npmignore b/node_modules/fs-extra/.npmignore new file mode 100644 index 0000000..68eefb7 --- /dev/null +++ b/node_modules/fs-extra/.npmignore @@ -0,0 +1,8 @@ +.nyc_output/ +coverage/ +test/ +.travis.yml +appveyor.yml +lib/**/__tests__/ +test/readme.md +test.js diff --git a/node_modules/fs-extra/CHANGELOG.md b/node_modules/fs-extra/CHANGELOG.md new file mode 100644 index 0000000..99b4bd8 --- /dev/null +++ b/node_modules/fs-extra/CHANGELOG.md @@ -0,0 +1,733 @@ +2.1.2 / 2017-03-16 +------------------ + +### Fixed + +- Weird windows bug that resulted in `ensureDir()`'s callback being called twice in some cases. This bug may have also affected `remove()`. See [#392](https://github.com/jprichardson/node-fs-extra/issues/392), [#393](https://github.com/jprichardson/node-fs-extra/pull/393) + +2.1.1 / 2017-03-15 +------------------ + +### Fixed + +- Reverted [`5597bd`](https://github.com/jprichardson/node-fs-extra/commit/5597bd5b67f7d060f5f5bf26e9635be48330f5d7), this broke compatibility with Node.js versions v4+ but less than `v4.5.0`. +- Remove `Buffer.alloc()` usage in `moveSync()`. + +2.1.0 / 2017-03-15 +------------------ + +Thanks to [Mani Maghsoudlou (@manidlou)](https://github.com/manidlou) & [Jan Peer Stöcklmair (@JPeer264)](https://github.com/JPeer264) for their extraordinary help with this release! + +### Added +- `moveSync()` See [#309], [#381](https://github.com/jprichardson/node-fs-extra/pull/381). ([@manidlou](https://github.com/manidlou)) +- `copy()` and `copySync()`'s `filter` option now gets the destination path passed as the second parameter. [#366](https://github.com/jprichardson/node-fs-extra/pull/366) ([@manidlou](https://github.com/manidlou)) + +### Changed +- Use `Buffer.alloc()` instead of deprecated `new Buffer()` in `copySync()`. [#380](https://github.com/jprichardson/node-fs-extra/pull/380) ([@manidlou](https://github.com/manidlou)) +- Refactored entire codebase to use ES6 features supported by Node.js v4+ [#355](https://github.com/jprichardson/node-fs-extra/issues/355). [(@JPeer264)](https://github.com/JPeer264) +- Refactored docs. ([@manidlou](https://github.com/manidlou)) + +### Fixed + +- `move()` shouldn't error out when source and dest are the same. [#377](https://github.com/jprichardson/node-fs-extra/issues/377), [#378](https://github.com/jprichardson/node-fs-extra/pull/378) ([@jdalton](https://github.com/jdalton)) + +2.0.0 / 2017-01-16 +------------------ + +### Removed +- **BREAKING:** Removed support for Node `v0.12`. The Node foundation stopped officially supporting it +on Jan 1st, 2017. +- **BREAKING:** Remove `walk()` and `walkSync()`. `walkSync()` was only part of `fs-extra` for a little +over two months. Use [klaw](https://github.com/jprichardson/node-klaw) instead of `walk()`, in fact, `walk()` was just +an alias to klaw. For `walkSync()` use [klaw-sync](https://github.com/mawni/node-klaw-sync). See: [#338], [#339] + +### Changed +- **BREAKING:** Renamed `clobber` to `overwrite`. This affects `copy()`, `copySync()`, and `move()`. [#330], [#333] +- Moved docs, to `docs/`. [#340] + +### Fixed +- Apply filters to directories in `copySync()` like in `copy()`. [#324] +- A specific condition when disk is under heavy use, `copy()` can fail. [#326] + + +1.0.0 / 2016-11-01 +------------------ + +After five years of development, we finally have reach the 1.0.0 milestone! Big thanks goes +to [Ryan Zim](https://github.com/RyanZim) for leading the charge on this release! + +### Added +- `walkSync()` + +### Changed +- **BREAKING**: dropped Node v0.10 support. +- disabled `rimaf` globbing, wasn't used. [#280] +- deprecate `copy()/copySync()` option `filter` if it's a `RegExp`. `filter` should now be a function. +- inline `rimraf`. This is temporary and was done because `rimraf` depended upon the beefy `glob` which `fs-extra` does not use. [#300] + +### Fixed +- bug fix proper closing of file handle on `utimesMillis()` [#271] +- proper escaping of files with dollar signs [#291] +- `copySync()` failed if user didn't own file. [#199], [#301] + + +0.30.0 / 2016-04-28 +------------------- +- Brought back Node v0.10 support. I didn't realize there was still demand. Official support will end **2016-10-01**. + +0.29.0 / 2016-04-27 +------------------- +- **BREAKING**: removed support for Node v0.10. If you still want to use Node v0.10, everything should work except for `ensureLink()/ensureSymlink()`. Node v0.12 is still supported but will be dropped in the near future as well. + +0.28.0 / 2016-04-17 +------------------- +- **BREAKING**: removed `createOutputStream()`. Use https://www.npmjs.com/package/create-output-stream. See: [#192][#192] +- `mkdirs()/mkdirsSync()` check for invalid win32 path chars. See: [#209][#209], [#237][#237] +- `mkdirs()/mkdirsSync()` if drive not mounted, error. See: [#93][#93] + +0.27.0 / 2016-04-15 +------------------- +- add `dereference` option to `copySync()`. [#235][#235] + +0.26.7 / 2016-03-16 +------------------- +- fixed `copy()` if source and dest are the same. [#230][#230] + +0.26.6 / 2016-03-15 +------------------- +- fixed if `emptyDir()` does not have a callback: [#229][#229] + +0.26.5 / 2016-01-27 +------------------- +- `copy()` with two arguments (w/o callback) was broken. See: [#215][#215] + +0.26.4 / 2016-01-05 +------------------- +- `copySync()` made `preserveTimestamps` default consistent with `copy()` which is `false`. See: [#208][#208] + +0.26.3 / 2015-12-17 +------------------- +- fixed `copy()` hangup in copying blockDevice / characterDevice / `/dev/null`. See: [#193][#193] + +0.26.2 / 2015-11-02 +------------------- +- fixed `outputJson{Sync}()` spacing adherence to `fs.spaces` + +0.26.1 / 2015-11-02 +------------------- +- fixed `copySync()` when `clogger=true` and the destination is read only. See: [#190][#190] + +0.26.0 / 2015-10-25 +------------------- +- extracted the `walk()` function into its own module [`klaw`](https://github.com/jprichardson/node-klaw). + +0.25.0 / 2015-10-24 +------------------- +- now has a file walker `walk()` + +0.24.0 / 2015-08-28 +------------------- +- removed alias `delete()` and `deleteSync()`. See: [#171][#171] + +0.23.1 / 2015-08-07 +------------------- +- Better handling of errors for `move()` when moving across devices. [#170][#170] +- `ensureSymlink()` and `ensureLink()` should not throw errors if link exists. [#169][#169] + +0.23.0 / 2015-08-06 +------------------- +- added `ensureLink{Sync}()` and `ensureSymlink{Sync}()`. See: [#165][#165] + +0.22.1 / 2015-07-09 +------------------- +- Prevent calling `hasMillisResSync()` on module load. See: [#149][#149]. +Fixes regression that was introduced in `0.21.0`. + +0.22.0 / 2015-07-09 +------------------- +- preserve permissions / ownership in `copy()`. See: [#54][#54] + +0.21.0 / 2015-07-04 +------------------- +- add option to preserve timestamps in `copy()` and `copySync()`. See: [#141][#141] +- updated `graceful-fs@3.x` to `4.x`. This brings in features from `amazing-graceful-fs` (much cleaner code / less hacks) + +0.20.1 / 2015-06-23 +------------------- +- fixed regression caused by latest jsonfile update: See: https://github.com/jprichardson/node-jsonfile/issues/26 + +0.20.0 / 2015-06-19 +------------------- +- removed `jsonfile` aliases with `File` in the name, they weren't documented and probably weren't in use e.g. +this package had both `fs.readJsonFile` and `fs.readJson` that were aliases to each other, now use `fs.readJson`. +- preliminary walker created. Intentionally not documented. If you use it, it will almost certainly change and break your code. +- started moving tests inline +- upgraded to `jsonfile@2.1.0`, can now pass JSON revivers/replacers to `readJson()`, `writeJson()`, `outputJson()` + +0.19.0 / 2015-06-08 +------------------- +- `fs.copy()` had support for Node v0.8, dropped support + +0.18.4 / 2015-05-22 +------------------- +- fixed license field according to this: [#136][#136] and https://github.com/npm/npm/releases/tag/v2.10.0 + +0.18.3 / 2015-05-08 +------------------- +- bugfix: handle `EEXIST` when clobbering on some Linux systems. [#134][#134] + +0.18.2 / 2015-04-17 +------------------- +- bugfix: allow `F_OK` ([#120][#120]) + +0.18.1 / 2015-04-15 +------------------- +- improved windows support for `move()` a bit. https://github.com/jprichardson/node-fs-extra/commit/92838980f25dc2ee4ec46b43ee14d3c4a1d30c1b +- fixed a lot of tests for Windows (appveyor) + +0.18.0 / 2015-03-31 +------------------- +- added `emptyDir()` and `emptyDirSync()` + +0.17.0 / 2015-03-28 +------------------- +- `copySync` added `clobber` option (before always would clobber, now if `clobber` is `false` it throws an error if the destination exists). +**Only works with files at the moment.** +- `createOutputStream()` added. See: [#118][#118] + +0.16.5 / 2015-03-08 +------------------- +- fixed `fs.move` when `clobber` is `true` and destination is a directory, it should clobber. [#114][#114] + +0.16.4 / 2015-03-01 +------------------- +- `fs.mkdirs` fix infinite loop on Windows. See: See https://github.com/substack/node-mkdirp/pull/74 and https://github.com/substack/node-mkdirp/issues/66 + +0.16.3 / 2015-01-28 +------------------- +- reverted https://github.com/jprichardson/node-fs-extra/commit/1ee77c8a805eba5b99382a2591ff99667847c9c9 + + +0.16.2 / 2015-01-28 +------------------- +- fixed `fs.copy` for Node v0.8 (support is temporary and will be removed in the near future) + +0.16.1 / 2015-01-28 +------------------- +- if `setImmediate` is not available, fall back to `process.nextTick` + +0.16.0 / 2015-01-28 +------------------- +- bugfix `fs.move()` into itself. Closes #104 +- bugfix `fs.move()` moving directory across device. Closes #108 +- added coveralls support +- bugfix: nasty multiple callback `fs.copy()` bug. Closes #98 +- misc fs.copy code cleanups + +0.15.0 / 2015-01-21 +------------------- +- dropped `ncp`, imported code in +- because of previous, now supports `io.js` +- `graceful-fs` is now a dependency + +0.14.0 / 2015-01-05 +------------------- +- changed `copy`/`copySync` from `fs.copy(src, dest, [filters], callback)` to `fs.copy(src, dest, [options], callback)` [#100][#100] +- removed mockfs tests for mkdirp (this may be temporary, but was getting in the way of other tests) + +0.13.0 / 2014-12-10 +------------------- +- removed `touch` and `touchSync` methods (they didn't handle permissions like UNIX touch) +- updated `"ncp": "^0.6.0"` to `"ncp": "^1.0.1"` +- imported `mkdirp` => `minimist` and `mkdirp` are no longer dependences, should now appease people who wanted `mkdirp` to be `--use_strict` safe. See [#59]([#59][#59]) + +0.12.0 / 2014-09-22 +------------------- +- copy symlinks in `copySync()` [#85][#85] + +0.11.1 / 2014-09-02 +------------------- +- bugfix `copySync()` preserve file permissions [#80][#80] + +0.11.0 / 2014-08-11 +------------------- +- upgraded `"ncp": "^0.5.1"` to `"ncp": "^0.6.0"` +- upgrade `jsonfile": "^1.2.0"` to `jsonfile": "^2.0.0"` => on write, json files now have `\n` at end. Also adds `options.throws` to `readJsonSync()` +see https://github.com/jprichardson/node-jsonfile#readfilesyncfilename-options for more details. + +0.10.0 / 2014-06-29 +------------------ +* bugfix: upgaded `"jsonfile": "~1.1.0"` to `"jsonfile": "^1.2.0"`, bumped minor because of `jsonfile` dep change +from `~` to `^`. #67 + +0.9.1 / 2014-05-22 +------------------ +* removed Node.js `0.8.x` support, `0.9.0` was published moments ago and should have been done there + +0.9.0 / 2014-05-22 +------------------ +* upgraded `ncp` from `~0.4.2` to `^0.5.1`, #58 +* upgraded `rimraf` from `~2.2.6` to `^2.2.8` +* upgraded `mkdirp` from `0.3.x` to `^0.5.0` +* added methods `ensureFile()`, `ensureFileSync()` +* added methods `ensureDir()`, `ensureDirSync()` #31 +* added `move()` method. From: https://github.com/andrewrk/node-mv + + +0.8.1 / 2013-10-24 +------------------ +* copy failed to return an error to the callback if a file doesn't exist (ulikoehler #38, #39) + +0.8.0 / 2013-10-14 +------------------ +* `filter` implemented on `copy()` and `copySync()`. (Srirangan / #36) + +0.7.1 / 2013-10-12 +------------------ +* `copySync()` implemented (Srirangan / #33) +* updated to the latest `jsonfile` version `1.1.0` which gives `options` params for the JSON methods. Closes #32 + +0.7.0 / 2013-10-07 +------------------ +* update readme conventions +* `copy()` now works if destination directory does not exist. Closes #29 + +0.6.4 / 2013-09-05 +------------------ +* changed `homepage` field in package.json to remove NPM warning + +0.6.3 / 2013-06-28 +------------------ +* changed JSON spacing default from `4` to `2` to follow Node conventions +* updated `jsonfile` dep +* updated `rimraf` dep + +0.6.2 / 2013-06-28 +------------------ +* added .npmignore, #25 + +0.6.1 / 2013-05-14 +------------------ +* modified for `strict` mode, closes #24 +* added `outputJson()/outputJsonSync()`, closes #23 + +0.6.0 / 2013-03-18 +------------------ +* removed node 0.6 support +* added node 0.10 support +* upgraded to latest `ncp` and `rimraf`. +* optional `graceful-fs` support. Closes #17 + + +0.5.0 / 2013-02-03 +------------------ +* Removed `readTextFile`. +* Renamed `readJSONFile` to `readJSON` and `readJson`, same with write. +* Restructured documentation a bit. Added roadmap. + +0.4.0 / 2013-01-28 +------------------ +* Set default spaces in `jsonfile` from 4 to 2. +* Updated `testutil` deps for tests. +* Renamed `touch()` to `createFile()` +* Added `outputFile()` and `outputFileSync()` +* Changed creation of testing diretories so the /tmp dir is not littered. +* Added `readTextFile()` and `readTextFileSync()`. + +0.3.2 / 2012-11-01 +------------------ +* Added `touch()` and `touchSync()` methods. + +0.3.1 / 2012-10-11 +------------------ +* Fixed some stray globals. + +0.3.0 / 2012-10-09 +------------------ +* Removed all CoffeeScript from tests. +* Renamed `mkdir` to `mkdirs`/`mkdirp`. + +0.2.1 / 2012-09-11 +------------------ +* Updated `rimraf` dep. + +0.2.0 / 2012-09-10 +------------------ +* Rewrote module into JavaScript. (Must still rewrite tests into JavaScript) +* Added all methods of [jsonfile][https://github.com/jprichardson/node-jsonfile] +* Added Travis-CI. + +0.1.3 / 2012-08-13 +------------------ +* Added method `readJSONFile`. + +0.1.2 / 2012-06-15 +------------------ +* Bug fix: `deleteSync()` didn't exist. +* Verified Node v0.8 compatibility. + +0.1.1 / 2012-06-15 +------------------ +* Fixed bug in `remove()`/`delete()` that wouldn't execute the function if a callback wasn't passed. + +0.1.0 / 2012-05-31 +------------------ +* Renamed `copyFile()` to `copy()`. `copy()` can now copy directories (recursively) too. +* Renamed `rmrf()` to `remove()`. +* `remove()` aliased with `delete()`. +* Added `mkdirp` capabilities. Named: `mkdir()`. Hides Node.js native `mkdir()`. +* Instead of exporting the native `fs` module with new functions, I now copy over the native methods to a new object and export that instead. + +0.0.4 / 2012-03-14 +------------------ +* Removed CoffeeScript dependency + +0.0.3 / 2012-01-11 +------------------ +* Added methods rmrf and rmrfSync +* Moved tests from Jasmine to Mocha + + +[#344]: https://github.com/jprichardson/node-fs-extra/issues/344 "Licence Year" +[#343]: https://github.com/jprichardson/node-fs-extra/pull/343 "Add klaw-sync link to readme" +[#342]: https://github.com/jprichardson/node-fs-extra/pull/342 "allow preserveTimestamps when use move" +[#341]: https://github.com/jprichardson/node-fs-extra/issues/341 "mkdirp(path.dirname(dest) in move() logic needs cleaning up [question]" +[#340]: https://github.com/jprichardson/node-fs-extra/pull/340 "Move docs to seperate docs folder [documentation]" +[#339]: https://github.com/jprichardson/node-fs-extra/pull/339 "Remove walk() & walkSync() [feature-walk]" +[#338]: https://github.com/jprichardson/node-fs-extra/issues/338 "Remove walk() and walkSync() [feature-walk]" +[#337]: https://github.com/jprichardson/node-fs-extra/issues/337 "copy doesn't return a yieldable value" +[#336]: https://github.com/jprichardson/node-fs-extra/pull/336 "Docs enhanced walk sync [documentation, feature-walk]" +[#335]: https://github.com/jprichardson/node-fs-extra/pull/335 "Refactor move() tests [feature-move]" +[#334]: https://github.com/jprichardson/node-fs-extra/pull/334 "Cleanup lib/move/index.js [feature-move]" +[#333]: https://github.com/jprichardson/node-fs-extra/pull/333 "Rename clobber to overwrite [feature-copy, feature-move]" +[#332]: https://github.com/jprichardson/node-fs-extra/pull/332 "BREAKING: Drop Node v0.12 & io.js support" +[#331]: https://github.com/jprichardson/node-fs-extra/issues/331 "Add support for chmodr [enhancement, future]" +[#330]: https://github.com/jprichardson/node-fs-extra/pull/330 "BREAKING: Do not error when copy destination exists & clobber: false [feature-copy]" +[#329]: https://github.com/jprichardson/node-fs-extra/issues/329 "Does .walk() scale to large directories? [question]" +[#328]: https://github.com/jprichardson/node-fs-extra/issues/328 "Copying files corrupts [feature-copy, needs-confirmed]" +[#327]: https://github.com/jprichardson/node-fs-extra/pull/327 "Use writeStream 'finish' event instead of 'close' [bug, feature-copy]" +[#326]: https://github.com/jprichardson/node-fs-extra/issues/326 "fs.copy fails with chmod error when disk under heavy use [bug, feature-copy]" +[#325]: https://github.com/jprichardson/node-fs-extra/issues/325 "ensureDir is difficult to promisify [enhancement]" +[#324]: https://github.com/jprichardson/node-fs-extra/pull/324 "copySync() should apply filter to directories like copy() [bug, feature-copy]" +[#323]: https://github.com/jprichardson/node-fs-extra/issues/323 "Support for `dest` being a directory when using `copy*()`?" +[#322]: https://github.com/jprichardson/node-fs-extra/pull/322 "Add fs-promise as fs-extra-promise alternative" +[#321]: https://github.com/jprichardson/node-fs-extra/issues/321 "fs.copy() with clobber set to false return EEXIST error [feature-copy]" +[#320]: https://github.com/jprichardson/node-fs-extra/issues/320 "fs.copySync: Error: EPERM: operation not permitted, unlink " +[#319]: https://github.com/jprichardson/node-fs-extra/issues/319 "Create directory if not exists" +[#318]: https://github.com/jprichardson/node-fs-extra/issues/318 "Support glob patterns [enhancement, future]" +[#317]: https://github.com/jprichardson/node-fs-extra/pull/317 "Adding copy sync test for src file without write perms" +[#316]: https://github.com/jprichardson/node-fs-extra/pull/316 "Remove move()'s broken limit option [feature-move]" +[#315]: https://github.com/jprichardson/node-fs-extra/pull/315 "Fix move clobber tests to work around graceful-fs bug." +[#314]: https://github.com/jprichardson/node-fs-extra/issues/314 "move() limit option [documentation, enhancement, feature-move]" +[#313]: https://github.com/jprichardson/node-fs-extra/pull/313 "Test that remove() ignores glob characters." +[#312]: https://github.com/jprichardson/node-fs-extra/pull/312 "Enhance walkSync() to return items with path and stats [feature-walk]" +[#311]: https://github.com/jprichardson/node-fs-extra/issues/311 "move() not work when dest name not provided [feature-move]" +[#310]: https://github.com/jprichardson/node-fs-extra/issues/310 "Edit walkSync to return items like what walk emits [documentation, enhancement, feature-walk]" +[#309]: https://github.com/jprichardson/node-fs-extra/issues/309 "moveSync support [enhancement, feature-move]" +[#308]: https://github.com/jprichardson/node-fs-extra/pull/308 "Fix incorrect anchor link" +[#307]: https://github.com/jprichardson/node-fs-extra/pull/307 "Fix coverage" +[#306]: https://github.com/jprichardson/node-fs-extra/pull/306 "Update devDeps, fix lint error" +[#305]: https://github.com/jprichardson/node-fs-extra/pull/305 "Re-add Coveralls" +[#304]: https://github.com/jprichardson/node-fs-extra/pull/304 "Remove path-is-absolute [enhancement]" +[#303]: https://github.com/jprichardson/node-fs-extra/pull/303 "Document copySync filter inconsistency [documentation, feature-copy]" +[#302]: https://github.com/jprichardson/node-fs-extra/pull/302 "fix(console): depreciated -> deprecated" +[#301]: https://github.com/jprichardson/node-fs-extra/pull/301 "Remove chmod call from copySync [feature-copy]" +[#300]: https://github.com/jprichardson/node-fs-extra/pull/300 "Inline Rimraf [enhancement, feature-move, feature-remove]" +[#299]: https://github.com/jprichardson/node-fs-extra/pull/299 "Warn when filter is a RegExp [feature-copy]" +[#298]: https://github.com/jprichardson/node-fs-extra/issues/298 "API Docs [documentation]" +[#297]: https://github.com/jprichardson/node-fs-extra/pull/297 "Warn about using preserveTimestamps on 32-bit node" +[#296]: https://github.com/jprichardson/node-fs-extra/pull/296 "Improve EEXIST error message for copySync [enhancement]" +[#295]: https://github.com/jprichardson/node-fs-extra/pull/295 "Depreciate using regular expressions for copy's filter option [documentation]" +[#294]: https://github.com/jprichardson/node-fs-extra/pull/294 "BREAKING: Refactor lib/copy/ncp.js [feature-copy]" +[#293]: https://github.com/jprichardson/node-fs-extra/pull/293 "Update CI configs" +[#292]: https://github.com/jprichardson/node-fs-extra/issues/292 "Rewrite lib/copy/ncp.js [enhancement, feature-copy]" +[#291]: https://github.com/jprichardson/node-fs-extra/pull/291 "Escape '$' in replacement string for async file copying" +[#290]: https://github.com/jprichardson/node-fs-extra/issues/290 "Exclude files pattern while copying using copy.config.js [question]" +[#289]: https://github.com/jprichardson/node-fs-extra/pull/289 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error" +[#288]: https://github.com/jprichardson/node-fs-extra/pull/288 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error" +[#287]: https://github.com/jprichardson/node-fs-extra/issues/287 "emptyDir() callback arguments are inconsistent [enhancement, feature-remove]" +[#286]: https://github.com/jprichardson/node-fs-extra/pull/286 "Added walkSync function" +[#285]: https://github.com/jprichardson/node-fs-extra/issues/285 "CITGM test failing on s390" +[#284]: https://github.com/jprichardson/node-fs-extra/issues/284 "outputFile method is missing a check to determine if existing item is a folder or not" +[#283]: https://github.com/jprichardson/node-fs-extra/pull/283 "Apply filter also on directories and symlinks for copySync()" +[#282]: https://github.com/jprichardson/node-fs-extra/pull/282 "Apply filter also on directories and symlinks for copySync()" +[#281]: https://github.com/jprichardson/node-fs-extra/issues/281 "remove function executes "successfully" but doesn't do anything?" +[#280]: https://github.com/jprichardson/node-fs-extra/pull/280 "Disable rimraf globbing" +[#279]: https://github.com/jprichardson/node-fs-extra/issues/279 "Some code is vendored instead of included [awaiting-reply]" +[#278]: https://github.com/jprichardson/node-fs-extra/issues/278 "copy() does not preserve file/directory ownership" +[#277]: https://github.com/jprichardson/node-fs-extra/pull/277 "Mention defaults for clobber and dereference options" +[#276]: https://github.com/jprichardson/node-fs-extra/issues/276 "Cannot connect to Shared Folder [awaiting-reply]" +[#275]: https://github.com/jprichardson/node-fs-extra/issues/275 "EMFILE, too many open files on Mac OS with JSON API" +[#274]: https://github.com/jprichardson/node-fs-extra/issues/274 "Use with memory-fs? [enhancement, future]" +[#273]: https://github.com/jprichardson/node-fs-extra/pull/273 "tests: rename `remote.test.js` to `remove.test.js`" +[#272]: https://github.com/jprichardson/node-fs-extra/issues/272 "Copy clobber flag never err even when true [bug, feature-copy]" +[#271]: https://github.com/jprichardson/node-fs-extra/issues/271 "Unclosed file handle on futimes error" +[#270]: https://github.com/jprichardson/node-fs-extra/issues/270 "copy not working as desired on Windows [feature-copy, platform-windows]" +[#269]: https://github.com/jprichardson/node-fs-extra/issues/269 "Copying with preserveTimeStamps: true is inaccurate using 32bit node [feature-copy]" +[#268]: https://github.com/jprichardson/node-fs-extra/pull/268 "port fix for mkdirp issue #111" +[#267]: https://github.com/jprichardson/node-fs-extra/issues/267 "WARN deprecated wrench@1.5.9: wrench.js is deprecated!" +[#266]: https://github.com/jprichardson/node-fs-extra/issues/266 "fs-extra" +[#265]: https://github.com/jprichardson/node-fs-extra/issues/265 "Link the `fs.stat fs.exists` etc. methods for replace the `fs` module forever?" +[#264]: https://github.com/jprichardson/node-fs-extra/issues/264 "Renaming a file using move fails when a file inside is open (at least on windows) [wont-fix]" +[#263]: https://github.com/jprichardson/node-fs-extra/issues/263 "ENOSYS: function not implemented, link [needs-confirmed]" +[#262]: https://github.com/jprichardson/node-fs-extra/issues/262 "Add .exists() and .existsSync()" +[#261]: https://github.com/jprichardson/node-fs-extra/issues/261 "Cannot read property 'prototype' of undefined" +[#260]: https://github.com/jprichardson/node-fs-extra/pull/260 "use more specific path for method require" +[#259]: https://github.com/jprichardson/node-fs-extra/issues/259 "Feature Request: isEmpty" +[#258]: https://github.com/jprichardson/node-fs-extra/issues/258 "copy files does not preserve file timestamp" +[#257]: https://github.com/jprichardson/node-fs-extra/issues/257 "Copying a file on windows fails" +[#256]: https://github.com/jprichardson/node-fs-extra/pull/256 "Updated Readme " +[#255]: https://github.com/jprichardson/node-fs-extra/issues/255 "Update rimraf required version" +[#254]: https://github.com/jprichardson/node-fs-extra/issues/254 "request for readTree, readTreeSync, walkSync method" +[#253]: https://github.com/jprichardson/node-fs-extra/issues/253 "outputFile does not touch mtime when file exists" +[#252]: https://github.com/jprichardson/node-fs-extra/pull/252 "Fixing problem when copying file with no write permission" +[#251]: https://github.com/jprichardson/node-fs-extra/issues/251 "Just wanted to say thank you" +[#250]: https://github.com/jprichardson/node-fs-extra/issues/250 "`fs.remove()` not removing files (works with `rm -rf`)" +[#249]: https://github.com/jprichardson/node-fs-extra/issues/249 "Just a Question ... Remove Servers" +[#248]: https://github.com/jprichardson/node-fs-extra/issues/248 "Allow option to not preserve permissions for copy" +[#247]: https://github.com/jprichardson/node-fs-extra/issues/247 "Add TypeScript typing directly in the fs-extra package" +[#246]: https://github.com/jprichardson/node-fs-extra/issues/246 "fse.remove() && fse.removeSync() don't throw error on ENOENT file" +[#245]: https://github.com/jprichardson/node-fs-extra/issues/245 "filter for empty dir [enhancement]" +[#244]: https://github.com/jprichardson/node-fs-extra/issues/244 "copySync doesn't apply the filter to directories" +[#243]: https://github.com/jprichardson/node-fs-extra/issues/243 "Can I request fs.walk() to be synchronous?" +[#242]: https://github.com/jprichardson/node-fs-extra/issues/242 "Accidentally truncates file names ending with $$ [bug, feature-copy]" +[#241]: https://github.com/jprichardson/node-fs-extra/pull/241 "Remove link to createOutputStream" +[#240]: https://github.com/jprichardson/node-fs-extra/issues/240 "walkSync request" +[#239]: https://github.com/jprichardson/node-fs-extra/issues/239 "Depreciate regular expressions for copy's filter [documentation, feature-copy]" +[#238]: https://github.com/jprichardson/node-fs-extra/issues/238 "Can't write to files while in a worker thread." +[#237]: https://github.com/jprichardson/node-fs-extra/issues/237 ".ensureDir(..) fails silently when passed an invalid path..." +[#236]: https://github.com/jprichardson/node-fs-extra/issues/236 "[Removed] Filed under wrong repo" +[#235]: https://github.com/jprichardson/node-fs-extra/pull/235 "Adds symlink dereference option to `fse.copySync` (#191)" +[#234]: https://github.com/jprichardson/node-fs-extra/issues/234 "ensureDirSync fails silent when EACCES: permission denied on travis-ci" +[#233]: https://github.com/jprichardson/node-fs-extra/issues/233 "please make sure the first argument in callback is error object [feature-copy]" +[#232]: https://github.com/jprichardson/node-fs-extra/issues/232 "Copy a folder content to its child folder. " +[#231]: https://github.com/jprichardson/node-fs-extra/issues/231 "Adding read/write/output functions for YAML" +[#230]: https://github.com/jprichardson/node-fs-extra/pull/230 "throw error if src and dest are the same to avoid zeroing out + test" +[#229]: https://github.com/jprichardson/node-fs-extra/pull/229 "fix 'TypeError: callback is not a function' in emptyDir" +[#228]: https://github.com/jprichardson/node-fs-extra/pull/228 "Throw error when target is empty so file is not accidentally zeroed out" +[#227]: https://github.com/jprichardson/node-fs-extra/issues/227 "Uncatchable errors when there are invalid arguments [feature-move]" +[#226]: https://github.com/jprichardson/node-fs-extra/issues/226 "Moving to the current directory" +[#225]: https://github.com/jprichardson/node-fs-extra/issues/225 "EBUSY: resource busy or locked, unlink" +[#224]: https://github.com/jprichardson/node-fs-extra/issues/224 "fse.copy ENOENT error" +[#223]: https://github.com/jprichardson/node-fs-extra/issues/223 "Suspicious behavior of fs.existsSync" +[#222]: https://github.com/jprichardson/node-fs-extra/pull/222 "A clearer description of emtpyDir function" +[#221]: https://github.com/jprichardson/node-fs-extra/pull/221 "Update README.md" +[#220]: https://github.com/jprichardson/node-fs-extra/pull/220 "Non-breaking feature: add option 'passStats' to copy methods." +[#219]: https://github.com/jprichardson/node-fs-extra/pull/219 "Add closing parenthesis in copySync example" +[#218]: https://github.com/jprichardson/node-fs-extra/pull/218 "fix #187 #70 options.filter bug" +[#217]: https://github.com/jprichardson/node-fs-extra/pull/217 "fix #187 #70 options.filter bug" +[#216]: https://github.com/jprichardson/node-fs-extra/pull/216 "fix #187 #70 options.filter bug" +[#215]: https://github.com/jprichardson/node-fs-extra/pull/215 "fse.copy throws error when only src and dest provided [bug, documentation, feature-copy]" +[#214]: https://github.com/jprichardson/node-fs-extra/pull/214 "Fixing copySync anchor tag" +[#213]: https://github.com/jprichardson/node-fs-extra/issues/213 "Merge extfs with this repo" +[#212]: https://github.com/jprichardson/node-fs-extra/pull/212 "Update year to 2016 in README.md and LICENSE" +[#211]: https://github.com/jprichardson/node-fs-extra/issues/211 "Not copying all files" +[#210]: https://github.com/jprichardson/node-fs-extra/issues/210 "copy/copySync behave differently when copying a symbolic file [bug, documentation, feature-copy]" +[#209]: https://github.com/jprichardson/node-fs-extra/issues/209 "In Windows invalid directory name causes infinite loop in ensureDir(). [bug]" +[#208]: https://github.com/jprichardson/node-fs-extra/pull/208 "fix options.preserveTimestamps to false in copy-sync by default [feature-copy]" +[#207]: https://github.com/jprichardson/node-fs-extra/issues/207 "Add `compare` suite of functions" +[#206]: https://github.com/jprichardson/node-fs-extra/issues/206 "outputFileSync" +[#205]: https://github.com/jprichardson/node-fs-extra/issues/205 "fix documents about copy/copySync [documentation, feature-copy]" +[#204]: https://github.com/jprichardson/node-fs-extra/pull/204 "allow copy of block and character device files" +[#203]: https://github.com/jprichardson/node-fs-extra/issues/203 "copy method's argument options couldn't be undefined [bug, feature-copy]" +[#202]: https://github.com/jprichardson/node-fs-extra/issues/202 "why there is not a walkSync method?" +[#201]: https://github.com/jprichardson/node-fs-extra/issues/201 "clobber for directories [feature-copy, future]" +[#200]: https://github.com/jprichardson/node-fs-extra/issues/200 "'copySync' doesn't work in sync" +[#199]: https://github.com/jprichardson/node-fs-extra/issues/199 "fs.copySync fails if user does not own file [bug, feature-copy]" +[#198]: https://github.com/jprichardson/node-fs-extra/issues/198 "handle copying between identical files [feature-copy]" +[#197]: https://github.com/jprichardson/node-fs-extra/issues/197 "Missing documentation for `outputFile` `options` 3rd parameter [documentation]" +[#196]: https://github.com/jprichardson/node-fs-extra/issues/196 "copy filter: async function and/or function called with `fs.stat` result [future]" +[#195]: https://github.com/jprichardson/node-fs-extra/issues/195 "How to override with outputFile?" +[#194]: https://github.com/jprichardson/node-fs-extra/pull/194 "allow ensureFile(Sync) to provide data to be written to created file" +[#193]: https://github.com/jprichardson/node-fs-extra/issues/193 "`fs.copy` fails silently if source file is /dev/null [bug, feature-copy]" +[#192]: https://github.com/jprichardson/node-fs-extra/issues/192 "Remove fs.createOutputStream()" +[#191]: https://github.com/jprichardson/node-fs-extra/issues/191 "How to copy symlinks to target as normal folders [feature-copy]" +[#190]: https://github.com/jprichardson/node-fs-extra/pull/190 "copySync to overwrite destination file if readonly and clobber true" +[#189]: https://github.com/jprichardson/node-fs-extra/pull/189 "move.test fix to support CRLF on Windows" +[#188]: https://github.com/jprichardson/node-fs-extra/issues/188 "move.test failing on windows platform" +[#187]: https://github.com/jprichardson/node-fs-extra/issues/187 "Not filter each file, stops on first false [feature-copy]" +[#186]: https://github.com/jprichardson/node-fs-extra/issues/186 "Do you need a .size() function in this module? [future]" +[#185]: https://github.com/jprichardson/node-fs-extra/issues/185 "Doesn't work on NodeJS v4.x" +[#184]: https://github.com/jprichardson/node-fs-extra/issues/184 "CLI equivalent for fs-extra" +[#183]: https://github.com/jprichardson/node-fs-extra/issues/183 "with clobber true, copy and copySync behave differently if destination file is read only [bug, feature-copy]" +[#182]: https://github.com/jprichardson/node-fs-extra/issues/182 "ensureDir(dir, callback) second callback parameter not specified" +[#181]: https://github.com/jprichardson/node-fs-extra/issues/181 "Add ability to remove file securely [enhancement, wont-fix]" +[#180]: https://github.com/jprichardson/node-fs-extra/issues/180 "Filter option doesn't work the same way in copy and copySync [bug, feature-copy]" +[#179]: https://github.com/jprichardson/node-fs-extra/issues/179 "Include opendir" +[#178]: https://github.com/jprichardson/node-fs-extra/issues/178 "ENOTEMPTY is thrown on removeSync " +[#177]: https://github.com/jprichardson/node-fs-extra/issues/177 "fix `remove()` wildcards (introduced by rimraf) [feature-remove]" +[#176]: https://github.com/jprichardson/node-fs-extra/issues/176 "createOutputStream doesn't emit 'end' event" +[#175]: https://github.com/jprichardson/node-fs-extra/issues/175 "[Feature Request].moveSync support [feature-move, future]" +[#174]: https://github.com/jprichardson/node-fs-extra/pull/174 "Fix copy formatting and document options.filter" +[#173]: https://github.com/jprichardson/node-fs-extra/issues/173 "Feature Request: writeJson should mkdirs" +[#172]: https://github.com/jprichardson/node-fs-extra/issues/172 "rename `clobber` flags to `overwrite`" +[#171]: https://github.com/jprichardson/node-fs-extra/issues/171 "remove unnecessary aliases" +[#170]: https://github.com/jprichardson/node-fs-extra/pull/170 "More robust handling of errors moving across virtual drives" +[#169]: https://github.com/jprichardson/node-fs-extra/pull/169 "suppress ensureLink & ensureSymlink dest exists error" +[#168]: https://github.com/jprichardson/node-fs-extra/pull/168 "suppress ensurelink dest exists error" +[#167]: https://github.com/jprichardson/node-fs-extra/pull/167 "Adds basic (string, buffer) support for ensureFile content [future]" +[#166]: https://github.com/jprichardson/node-fs-extra/pull/166 "Adds basic (string, buffer) support for ensureFile content" +[#165]: https://github.com/jprichardson/node-fs-extra/pull/165 "ensure for link & symlink" +[#164]: https://github.com/jprichardson/node-fs-extra/issues/164 "Feature Request: ensureFile to take optional argument for file content" +[#163]: https://github.com/jprichardson/node-fs-extra/issues/163 "ouputJson not formatted out of the box [bug]" +[#162]: https://github.com/jprichardson/node-fs-extra/pull/162 "ensure symlink & link" +[#161]: https://github.com/jprichardson/node-fs-extra/pull/161 "ensure symlink & link" +[#160]: https://github.com/jprichardson/node-fs-extra/pull/160 "ensure symlink & link" +[#159]: https://github.com/jprichardson/node-fs-extra/pull/159 "ensure symlink & link" +[#158]: https://github.com/jprichardson/node-fs-extra/issues/158 "Feature Request: ensureLink and ensureSymlink methods" +[#157]: https://github.com/jprichardson/node-fs-extra/issues/157 "writeJson isn't formatted" +[#156]: https://github.com/jprichardson/node-fs-extra/issues/156 "Promise.promisifyAll doesn't work for some methods" +[#155]: https://github.com/jprichardson/node-fs-extra/issues/155 "Readme" +[#154]: https://github.com/jprichardson/node-fs-extra/issues/154 "/tmp/millis-test-sync" +[#153]: https://github.com/jprichardson/node-fs-extra/pull/153 "Make preserveTimes also work on read-only files. Closes #152" +[#152]: https://github.com/jprichardson/node-fs-extra/issues/152 "fs.copy fails for read-only files with preserveTimestamp=true [feature-copy]" +[#151]: https://github.com/jprichardson/node-fs-extra/issues/151 "TOC does not work correctly on npm [documentation]" +[#150]: https://github.com/jprichardson/node-fs-extra/issues/150 "Remove test file fixtures, create with code." +[#149]: https://github.com/jprichardson/node-fs-extra/issues/149 "/tmp/millis-test-sync" +[#148]: https://github.com/jprichardson/node-fs-extra/issues/148 "split out `Sync` methods in documentation" +[#147]: https://github.com/jprichardson/node-fs-extra/issues/147 "Adding rmdirIfEmpty" +[#146]: https://github.com/jprichardson/node-fs-extra/pull/146 "ensure test.js works" +[#145]: https://github.com/jprichardson/node-fs-extra/issues/145 "Add `fs.exists` and `fs.existsSync` if it doesn't exist." +[#144]: https://github.com/jprichardson/node-fs-extra/issues/144 "tests failing" +[#143]: https://github.com/jprichardson/node-fs-extra/issues/143 "update graceful-fs" +[#142]: https://github.com/jprichardson/node-fs-extra/issues/142 "PrependFile Feature" +[#141]: https://github.com/jprichardson/node-fs-extra/pull/141 "Add option to preserve timestamps" +[#140]: https://github.com/jprichardson/node-fs-extra/issues/140 "Json file reading fails with 'utf8'" +[#139]: https://github.com/jprichardson/node-fs-extra/pull/139 "Preserve file timestamp on copy. Closes #138" +[#138]: https://github.com/jprichardson/node-fs-extra/issues/138 "Preserve timestamps on copying files" +[#137]: https://github.com/jprichardson/node-fs-extra/issues/137 "outputFile/outputJson: Unexpected end of input" +[#136]: https://github.com/jprichardson/node-fs-extra/pull/136 "Update license attribute" +[#135]: https://github.com/jprichardson/node-fs-extra/issues/135 "emptyDir throws Error if no callback is provided" +[#134]: https://github.com/jprichardson/node-fs-extra/pull/134 "Handle EEXIST error when clobbering dir" +[#133]: https://github.com/jprichardson/node-fs-extra/pull/133 "Travis runs with `sudo: false`" +[#132]: https://github.com/jprichardson/node-fs-extra/pull/132 "isDirectory method" +[#131]: https://github.com/jprichardson/node-fs-extra/issues/131 "copySync is not working iojs 1.8.4 on linux [feature-copy]" +[#130]: https://github.com/jprichardson/node-fs-extra/pull/130 "Please review additional features." +[#129]: https://github.com/jprichardson/node-fs-extra/pull/129 "can you review this feature?" +[#128]: https://github.com/jprichardson/node-fs-extra/issues/128 "fsExtra.move(filepath, newPath) broken;" +[#127]: https://github.com/jprichardson/node-fs-extra/issues/127 "consider using fs.access to remove deprecated warnings for fs.exists" +[#126]: https://github.com/jprichardson/node-fs-extra/issues/126 " TypeError: Object # has no method 'access'" +[#125]: https://github.com/jprichardson/node-fs-extra/issues/125 "Question: What do the *Sync function do different from non-sync" +[#124]: https://github.com/jprichardson/node-fs-extra/issues/124 "move with clobber option 'ENOTEMPTY'" +[#123]: https://github.com/jprichardson/node-fs-extra/issues/123 "Only copy the content of a directory" +[#122]: https://github.com/jprichardson/node-fs-extra/pull/122 "Update section links in README to match current section ids." +[#121]: https://github.com/jprichardson/node-fs-extra/issues/121 "emptyDir is undefined" +[#120]: https://github.com/jprichardson/node-fs-extra/issues/120 "usage bug caused by shallow cloning methods of 'graceful-fs'" +[#119]: https://github.com/jprichardson/node-fs-extra/issues/119 "mkdirs and ensureDir never invoke callback and consume CPU indefinitely if provided a path with invalid characters on Windows" +[#118]: https://github.com/jprichardson/node-fs-extra/pull/118 "createOutputStream" +[#117]: https://github.com/jprichardson/node-fs-extra/pull/117 "Fixed issue with slash separated paths on windows" +[#116]: https://github.com/jprichardson/node-fs-extra/issues/116 "copySync can only copy directories not files [documentation, feature-copy]" +[#115]: https://github.com/jprichardson/node-fs-extra/issues/115 ".Copy & .CopySync [feature-copy]" +[#114]: https://github.com/jprichardson/node-fs-extra/issues/114 "Fails to move (rename) directory to non-empty directory even with clobber: true" +[#113]: https://github.com/jprichardson/node-fs-extra/issues/113 "fs.copy seems to callback early if the destination file already exists" +[#112]: https://github.com/jprichardson/node-fs-extra/pull/112 "Copying a file into an existing directory" +[#111]: https://github.com/jprichardson/node-fs-extra/pull/111 "Moving a file into an existing directory " +[#110]: https://github.com/jprichardson/node-fs-extra/pull/110 "Moving a file into an existing directory" +[#109]: https://github.com/jprichardson/node-fs-extra/issues/109 "fs.move across windows drives fails" +[#108]: https://github.com/jprichardson/node-fs-extra/issues/108 "fse.move directories across multiple devices doesn't work" +[#107]: https://github.com/jprichardson/node-fs-extra/pull/107 "Check if dest path is an existing dir and copy or move source in it" +[#106]: https://github.com/jprichardson/node-fs-extra/issues/106 "fse.copySync crashes while copying across devices D: [feature-copy]" +[#105]: https://github.com/jprichardson/node-fs-extra/issues/105 "fs.copy hangs on iojs" +[#104]: https://github.com/jprichardson/node-fs-extra/issues/104 "fse.move deletes folders [bug]" +[#103]: https://github.com/jprichardson/node-fs-extra/issues/103 "Error: EMFILE with copy" +[#102]: https://github.com/jprichardson/node-fs-extra/issues/102 "touch / touchSync was removed ?" +[#101]: https://github.com/jprichardson/node-fs-extra/issues/101 "fs-extra promisified" +[#100]: https://github.com/jprichardson/node-fs-extra/pull/100 "copy: options object or filter to pass to ncp" +[#99]: https://github.com/jprichardson/node-fs-extra/issues/99 "ensureDir() modes [future]" +[#98]: https://github.com/jprichardson/node-fs-extra/issues/98 "fs.copy() incorrect async behavior [bug]" +[#97]: https://github.com/jprichardson/node-fs-extra/pull/97 "use path.join; fix copySync bug" +[#96]: https://github.com/jprichardson/node-fs-extra/issues/96 "destFolderExists in copySync is always undefined." +[#95]: https://github.com/jprichardson/node-fs-extra/pull/95 "Using graceful-ncp instead of ncp" +[#94]: https://github.com/jprichardson/node-fs-extra/issues/94 "Error: EEXIST, file already exists '../mkdirp/bin/cmd.js' on fs.copySync() [enhancement, feature-copy]" +[#93]: https://github.com/jprichardson/node-fs-extra/issues/93 "Confusing error if drive not mounted [enhancement]" +[#92]: https://github.com/jprichardson/node-fs-extra/issues/92 "Problems with Bluebird" +[#91]: https://github.com/jprichardson/node-fs-extra/issues/91 "fs.copySync('/test', '/haha') is different with 'cp -r /test /haha' [enhancement]" +[#90]: https://github.com/jprichardson/node-fs-extra/issues/90 "Folder creation and file copy is Happening in 64 bit machine but not in 32 bit machine" +[#89]: https://github.com/jprichardson/node-fs-extra/issues/89 "Error: EEXIST using fs-extra's fs.copy to copy a directory on Windows" +[#88]: https://github.com/jprichardson/node-fs-extra/issues/88 "Stacking those libraries" +[#87]: https://github.com/jprichardson/node-fs-extra/issues/87 "createWriteStream + outputFile = ?" +[#86]: https://github.com/jprichardson/node-fs-extra/issues/86 "no moveSync?" +[#85]: https://github.com/jprichardson/node-fs-extra/pull/85 "Copy symlinks in copySync" +[#84]: https://github.com/jprichardson/node-fs-extra/issues/84 "Push latest version to npm ?" +[#83]: https://github.com/jprichardson/node-fs-extra/issues/83 "Prevent copying a directory into itself [feature-copy]" +[#82]: https://github.com/jprichardson/node-fs-extra/pull/82 "README updates for move" +[#81]: https://github.com/jprichardson/node-fs-extra/issues/81 "fd leak after fs.move" +[#80]: https://github.com/jprichardson/node-fs-extra/pull/80 "Preserve file mode in copySync" +[#79]: https://github.com/jprichardson/node-fs-extra/issues/79 "fs.copy only .html file empty" +[#78]: https://github.com/jprichardson/node-fs-extra/pull/78 "copySync was not applying filters to directories" +[#77]: https://github.com/jprichardson/node-fs-extra/issues/77 "Create README reference to bluebird" +[#76]: https://github.com/jprichardson/node-fs-extra/issues/76 "Create README reference to typescript" +[#75]: https://github.com/jprichardson/node-fs-extra/issues/75 "add glob as a dep? [question]" +[#74]: https://github.com/jprichardson/node-fs-extra/pull/74 "including new emptydir module" +[#73]: https://github.com/jprichardson/node-fs-extra/pull/73 "add dependency status in readme" +[#72]: https://github.com/jprichardson/node-fs-extra/pull/72 "Use svg instead of png to get better image quality" +[#71]: https://github.com/jprichardson/node-fs-extra/issues/71 "fse.copy not working on Windows 7 x64 OS, but, copySync does work" +[#70]: https://github.com/jprichardson/node-fs-extra/issues/70 "Not filter each file, stops on first false [bug]" +[#69]: https://github.com/jprichardson/node-fs-extra/issues/69 "How to check if folder exist and read the folder name" +[#68]: https://github.com/jprichardson/node-fs-extra/issues/68 "consider flag to readJsonSync (throw false) [enhancement]" +[#67]: https://github.com/jprichardson/node-fs-extra/issues/67 "docs for readJson incorrectly states that is accepts options" +[#66]: https://github.com/jprichardson/node-fs-extra/issues/66 "ENAMETOOLONG" +[#65]: https://github.com/jprichardson/node-fs-extra/issues/65 "exclude filter in fs.copy" +[#64]: https://github.com/jprichardson/node-fs-extra/issues/64 "Announce: mfs - monitor your fs-extra calls" +[#63]: https://github.com/jprichardson/node-fs-extra/issues/63 "Walk" +[#62]: https://github.com/jprichardson/node-fs-extra/issues/62 "npm install fs-extra doesn't work" +[#61]: https://github.com/jprichardson/node-fs-extra/issues/61 "No longer supports node 0.8 due to use of `^` in package.json dependencies" +[#60]: https://github.com/jprichardson/node-fs-extra/issues/60 "chmod & chown for mkdirs" +[#59]: https://github.com/jprichardson/node-fs-extra/issues/59 "Consider including mkdirp and making fs-extra "--use_strict" safe [question]" +[#58]: https://github.com/jprichardson/node-fs-extra/issues/58 "Stack trace not included in fs.copy error" +[#57]: https://github.com/jprichardson/node-fs-extra/issues/57 "Possible to include wildcards in delete?" +[#56]: https://github.com/jprichardson/node-fs-extra/issues/56 "Crash when have no access to write to destination file in copy " +[#55]: https://github.com/jprichardson/node-fs-extra/issues/55 "Is it possible to have any console output similar to Grunt copy module?" +[#54]: https://github.com/jprichardson/node-fs-extra/issues/54 "`copy` does not preserve file ownership and permissons" +[#53]: https://github.com/jprichardson/node-fs-extra/issues/53 "outputFile() - ability to write data in appending mode" +[#52]: https://github.com/jprichardson/node-fs-extra/pull/52 "This fixes (what I think) is a bug in copySync" +[#51]: https://github.com/jprichardson/node-fs-extra/pull/51 "Add a Bitdeli Badge to README" +[#50]: https://github.com/jprichardson/node-fs-extra/issues/50 "Replace mechanism in createFile" +[#49]: https://github.com/jprichardson/node-fs-extra/pull/49 "update rimraf to v2.2.6" +[#48]: https://github.com/jprichardson/node-fs-extra/issues/48 "fs.copy issue [bug]" +[#47]: https://github.com/jprichardson/node-fs-extra/issues/47 "Bug in copy - callback called on readStream "close" - Fixed in ncp 0.5.0" +[#46]: https://github.com/jprichardson/node-fs-extra/pull/46 "update copyright year" +[#45]: https://github.com/jprichardson/node-fs-extra/pull/45 "Added note about fse.outputFile() being the one that overwrites" +[#44]: https://github.com/jprichardson/node-fs-extra/pull/44 "Proposal: Stream support" +[#43]: https://github.com/jprichardson/node-fs-extra/issues/43 "Better error reporting " +[#42]: https://github.com/jprichardson/node-fs-extra/issues/42 "Performance issue?" +[#41]: https://github.com/jprichardson/node-fs-extra/pull/41 "There does seem to be a synchronous version now" +[#40]: https://github.com/jprichardson/node-fs-extra/issues/40 "fs.copy throw unexplained error ENOENT, utime " +[#39]: https://github.com/jprichardson/node-fs-extra/pull/39 "Added regression test for copy() return callback on error" +[#38]: https://github.com/jprichardson/node-fs-extra/pull/38 "Return err in copy() fstat cb, because stat could be undefined or null" +[#37]: https://github.com/jprichardson/node-fs-extra/issues/37 "Maybe include a line reader? [enhancement, question]" +[#36]: https://github.com/jprichardson/node-fs-extra/pull/36 "`filter` parameter `fs.copy` and `fs.copySync`" +[#35]: https://github.com/jprichardson/node-fs-extra/pull/35 "`filter` parameter `fs.copy` and `fs.copySync` " +[#34]: https://github.com/jprichardson/node-fs-extra/issues/34 "update docs to include options for JSON methods [enhancement]" +[#33]: https://github.com/jprichardson/node-fs-extra/pull/33 "fs_extra.copySync" +[#32]: https://github.com/jprichardson/node-fs-extra/issues/32 "update to latest jsonfile [enhancement]" +[#31]: https://github.com/jprichardson/node-fs-extra/issues/31 "Add ensure methods [enhancement]" +[#30]: https://github.com/jprichardson/node-fs-extra/issues/30 "update package.json optional dep `graceful-fs`" +[#29]: https://github.com/jprichardson/node-fs-extra/issues/29 "Copy failing if dest directory doesn't exist. Is this intended?" +[#28]: https://github.com/jprichardson/node-fs-extra/issues/28 "homepage field must be a string url. Deleted." +[#27]: https://github.com/jprichardson/node-fs-extra/issues/27 "Update Readme" +[#26]: https://github.com/jprichardson/node-fs-extra/issues/26 "Add readdir recursive method. [enhancement]" +[#25]: https://github.com/jprichardson/node-fs-extra/pull/25 "adding an `.npmignore` file" +[#24]: https://github.com/jprichardson/node-fs-extra/issues/24 "[bug] cannot run in strict mode [bug]" +[#23]: https://github.com/jprichardson/node-fs-extra/issues/23 "`writeJSON()` should create parent directories" +[#22]: https://github.com/jprichardson/node-fs-extra/pull/22 "Add a limit option to mkdirs()" +[#21]: https://github.com/jprichardson/node-fs-extra/issues/21 "touch() in 0.10.0" +[#20]: https://github.com/jprichardson/node-fs-extra/issues/20 "fs.remove yields callback before directory is really deleted" +[#19]: https://github.com/jprichardson/node-fs-extra/issues/19 "fs.copy err is empty array" +[#18]: https://github.com/jprichardson/node-fs-extra/pull/18 "Exposed copyFile Function" +[#17]: https://github.com/jprichardson/node-fs-extra/issues/17 "Use `require("graceful-fs")` if found instead of `require("fs")`" +[#16]: https://github.com/jprichardson/node-fs-extra/pull/16 "Update README.md" +[#15]: https://github.com/jprichardson/node-fs-extra/issues/15 "Implement cp -r but sync aka copySync. [enhancement]" +[#14]: https://github.com/jprichardson/node-fs-extra/issues/14 "fs.mkdirSync is broken in 0.3.1" +[#13]: https://github.com/jprichardson/node-fs-extra/issues/13 "Thoughts on including a directory tree / file watcher? [enhancement, question]" +[#12]: https://github.com/jprichardson/node-fs-extra/issues/12 "copyFile & copyFileSync are global" +[#11]: https://github.com/jprichardson/node-fs-extra/issues/11 "Thoughts on including a file walker? [enhancement, question]" +[#10]: https://github.com/jprichardson/node-fs-extra/issues/10 "move / moveFile API [enhancement]" +[#9]: https://github.com/jprichardson/node-fs-extra/issues/9 "don't import normal fs stuff into fs-extra" +[#8]: https://github.com/jprichardson/node-fs-extra/pull/8 "Update rimraf to latest version" +[#6]: https://github.com/jprichardson/node-fs-extra/issues/6 "Remove CoffeeScript development dependency" +[#5]: https://github.com/jprichardson/node-fs-extra/issues/5 "comments on naming" +[#4]: https://github.com/jprichardson/node-fs-extra/issues/4 "version bump to 0.2" +[#3]: https://github.com/jprichardson/node-fs-extra/pull/3 "Hi! I fixed some code for you!" +[#2]: https://github.com/jprichardson/node-fs-extra/issues/2 "Merge with fs.extra and mkdirp" +[#1]: https://github.com/jprichardson/node-fs-extra/issues/1 "file-extra npm !exist" diff --git a/node_modules/fs-extra/LICENSE b/node_modules/fs-extra/LICENSE new file mode 100644 index 0000000..93546df --- /dev/null +++ b/node_modules/fs-extra/LICENSE @@ -0,0 +1,15 @@ +(The MIT License) + +Copyright (c) 2011-2017 JP Richardson + +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/fs-extra/README.md b/node_modules/fs-extra/README.md new file mode 100644 index 0000000..cee4399 --- /dev/null +++ b/node_modules/fs-extra/README.md @@ -0,0 +1,251 @@ +Node.js: fs-extra +================= + +`fs-extra` adds file system methods that aren't included in the native `fs` module. It is a drop in replacement for `fs`. + +[![npm Package](https://img.shields.io/npm/v/fs-extra.svg?style=flat-square)](https://www.npmjs.org/package/fs-extra) +[![build status](https://api.travis-ci.org/jprichardson/node-fs-extra.svg)](http://travis-ci.org/jprichardson/node-fs-extra) +[![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-fs-extra/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-fs-extra/branch/master) +[![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra) +[![Coverage Status](https://img.shields.io/coveralls/jprichardson/node-fs-extra.svg)](https://coveralls.io/r/jprichardson/node-fs-extra) + +Standard JavaScript + + +Why? +---- + +I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects. + + + + +Installation +------------ + + npm install --save fs-extra + + + +Usage +----- + +`fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are unmodified and attached to `fs-extra`. + +You don't ever need to include the original `fs` module again: + +```js +const fs = require('fs') // this is no longer necessary +``` + +you can now do this: + +```js +const fs = require('fs-extra') +``` + +or if you prefer to make it clear that you're using `fs-extra` and not `fs`, you may want +to name your `fs` variable `fse` like so: + +```js +const fse = require('fs-extra') +``` + +you can also keep both, but it's redundant: + +```js +const fs = require('fs') +const fse = require('fs-extra') +``` + +Sync vs Async +------------- +Most methods are async by default (they take a callback with an `Error` as first argument). + +Sync methods on the other hand will throw if an error occurs. + +Example: + +```js +const fs = require('fs-extra') + +fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { + if (err) return console.error(err) + console.log("success!") +}); + +try { + fs.copySync('/tmp/myfile', '/tmp/mynewfile') + console.log("success!") +} catch (err) { + console.error(err) +} +``` + + +Methods +------- + +### Async + +- [copy](docs/copy.md) +- [emptyDir](docs/emptyDir.md) +- [ensureFile](docs/ensureFile.md) +- [ensureDir](docs/ensureDir.md) +- [ensureLink](docs/ensureLink.md) +- [ensureSymlink](docs/ensureSymlink.md) +- [mkdirs](docs/ensureDir.md) +- [move](docs/move.md) +- [outputFile](docs/outputFile.md) +- [outputJson](docs/outputJson.md) +- [readJson](docs/readJson.md) +- [remove](docs/remove.md) +- [writeJson](docs/writeJson.md) + +### Sync + +- [copySync](docs/copy-sync.md) +- [emptyDirSync](docs/emptyDir-sync.md) +- [ensureFileSync](docs/ensureFile-sync.md) +- [ensureDirSync](docs/ensureDir-sync.md) +- [ensureLinkSync](docs/ensureLink-sync.md) +- [ensureSymlinkSync](docs/ensureSymlink-sync.md) +- [mkdirsSync](docs/ensureDir-sync.md) +- [moveSync](docs/move-sync.md) +- [outputFileSync](docs/outputFile-sync.md) +- [outputJsonSync](docs/outputJson-sync.md) +- [readJsonSync](docs/readJson-sync.md) +- [removeSync](docs/remove-sync.md) +- [writeJsonSync](docs/writeJson-sync.md) + + +**NOTE:** You can still use the native Node.js methods. They are copied over to `fs-extra`. + +### What happened to `walk()` and `walkSync()`? + +They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync). + + +Third Party +----------- + +### Promises + +Use [Bluebird](https://github.com/petkaantonov/bluebird). See https://github.com/petkaantonov/bluebird/blob/master/API.md#promisification. `fs-extra` is +explicitly listed as supported. + +```js +const Promise = require('bluebird') +const fs = Promise.promisifyAll(require('fs-extra')) +``` + +Or you can use a dedicated package: + +- [`fs-extra-promise`](https://github.com/overlookmotel/fs-extra-promise) uses Bluebird. +- [`fs-promise`](https://github.com/kevinbeaty/fs-promise) uses + [Any Promise](https://github.com/kevinbeaty/any-promise) and also covers + [`mz/fs`](https://github.com/normalize/mz/blob/master/fs.js). +- [`fs-p`](https://github.com/grammarly/fs-p) - TypeScript-friendly promises implementation + + +### TypeScript + +If you like TypeScript, you can use `fs-extra` with it: https://github.com/borisyankov/DefinitelyTyped/tree/master/fs-extra + + +### File / Directory Watching + +If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar). + + +### Misc. + +- [mfs](https://github.com/cadorn/mfs) - Monitor your fs-extra calls. + + + +Hacking on fs-extra +------------------- + +Wanna hack on `fs-extra`? Great! Your help is needed! [fs-extra is one of the most depended upon Node.js packages](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project +uses [JavaScript Standard Style](https://github.com/feross/standard) - if the name or style choices bother you, +you're gonna have to get over it :) If `standard` is good enough for `npm`, it's good enough for `fs-extra`. + +[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard) + +What's needed? +- First, take a look at existing issues. Those are probably going to be where the priority lies. +- More tests for edge cases. Specifically on different platforms. There can never be enough tests. +- Improve test coverage. See coveralls output for more info. + +Note: If you make any big changes, **you should definitely file an issue for discussion first.** + +### Running the Test Suite + +fs-extra contains hundreds of tests. + +- `npm run lint`: runs the linter ([standard](http://standardjs.com/)) +- `npm run unit`: runs the unit tests +- `npm test`: runs both the linter and the tests + + +### Windows + +If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's +because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's +account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7 +However, I didn't have much luck doing this. + +Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows. +I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command: + + net use z: "\\vmware-host\Shared Folders" + +I can then navigate to my `fs-extra` directory and run the tests. + + +Naming +------ + +I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here: + +* https://github.com/jprichardson/node-fs-extra/issues/2 +* https://github.com/flatiron/utile/issues/11 +* https://github.com/ryanmcgrath/wrench-js/issues/29 +* https://github.com/substack/node-mkdirp/issues/17 + +First, I believe that in as many cases as possible, the [Node.js naming schemes](http://nodejs.org/api/fs.html) should be chosen. However, there are problems with the Node.js own naming schemes. + +For example, `fs.readFile()` and `fs.readdir()`: the **F** is capitalized in *File* and the **d** is not capitalized in *dir*. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: `fs.mkdir()`, `fs.rmdir()`, `fs.chown()`, etc. + +We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: `cp`, `cp -r`, `mkdir -p`, and `rm -rf`? + +My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too. + +So, if you want to remove a file or a directory regardless of whether it has contents, just call `fs.remove(path)`. If you want to copy a file or a directory whether it has contents, just call `fs.copy(source, destination)`. If you want to create a directory regardless of whether its parent directories exist, just call `fs.mkdirs(path)` or `fs.mkdirp(path)`. + + +Credit +------ + +`fs-extra` wouldn't be possible without using the modules from the following authors: + +- [Isaac Shlueter](https://github.com/isaacs) +- [Charlie McConnel](https://github.com/avianflu) +- [James Halliday](https://github.com/substack) +- [Andrew Kelley](https://github.com/andrewrk) + + + + +License +------- + +Licensed under MIT + +Copyright (c) 2011-2017 [JP Richardson](https://github.com/jprichardson) + +[1]: http://nodejs.org/docs/latest/api/fs.html + + +[jsonfile]: https://github.com/jprichardson/node-jsonfile diff --git a/node_modules/fs-extra/docs/copy-sync.md b/node_modules/fs-extra/docs/copy-sync.md new file mode 100644 index 0000000..8e61c2b --- /dev/null +++ b/node_modules/fs-extra/docs/copy-sync.md @@ -0,0 +1,37 @@ +# copySync(src, dest, [options]) + +Copy a file or directory. The directory can have contents. Like `cp -r`. + +- `src` `` +- `dest` `` +- `options` `` + - `overwrite` ``: overwrite existing file or directory, default is `true`. _Note that the copy operation will silently fail if you set this to `false` and the destination exists._ Use the `errorOnExist` option to change this behavior. + - `errorOnExist` ``: when `overwrite` is `false` and the destination exists, throw an error. Default is `false`. + - `dereference` ``: dereference symlinks, default is `false`. + - `preserveTimestamps` ``: will set last modification and access times to the ones of the original source files, default is `false`. + - `filter` ``: Function to filter copied files. Return `true` to include, `false` to exclude. This can also be a RegExp, however this is deprecated (See [issue #239](https://github.com/jprichardson/node-fs-extra/issues/239) for background). + +## Example: + +```js +const fs = require('fs-extra') + +// copy file +fs.copySync('/tmp/myfile', '/tmp/mynewfile') + +// copy directory, even if it has subdirectories or files +fs.copySync('/tmp/mydir', '/tmp/mynewdir') +``` + +**Using filter function** + +```js +const fs = require('fs-extra') + +const filterFunc = (src, dest) => { + // your logic here + // it will be copied if return true +} + +fs.copySync('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc }) +``` diff --git a/node_modules/fs-extra/docs/copy.md b/node_modules/fs-extra/docs/copy.md new file mode 100644 index 0000000..a4f75e9 --- /dev/null +++ b/node_modules/fs-extra/docs/copy.md @@ -0,0 +1,48 @@ +# copy(src, dest, [options], callback) + +Copy a file or directory. The directory can have contents. Like `cp -r`. + +- `src` `` +- `dest` `` +- `options` `` + - `overwrite` ``: overwrite existing file or directory, default is `true`. _Note that the copy operation will silently fail if you set this to `false` and the destination exists._ Use the `errorOnExist` option to change this behavior. + - `errorOnExist` ``: when `overwrite` is `false` and the destination exists, throw an error. Default is `false`. + - `dereference` ``: dereference symlinks, default is `false`. + - `preserveTimestamps` ``: will set last modification and access times to the ones of the original source files, default is `false`. + - `filter` ``: Function to filter copied files. Return `true` to include, `false` to exclude. This can also be a RegExp, however this is deprecated (See [issue #239](https://github.com/jprichardson/node-fs-extra/issues/239) for background). +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +fs.copy('/tmp/myfile', '/tmp/mynewfile', err => { + if (err) return console.error(err) + + console.log('success!') +}) // copies file + +fs.copy('/tmp/mydir', '/tmp/mynewdir', err => { + if (err) return console.error(err) + + console.log('success!') +}) // copies directory, even if it has subdirectories or files +``` + +**Using filter function** + +```js +const fs = require('fs-extra') + +const filterFunc = (src, dest) => { + // your logic here + // it will be copied if return true +} + +fs.copy('/tmp/mydir', '/tmp/mynewdir', { filter: filterFunc }, err => { + if (err) return console.error(err) + + console.log('success!') +}) +``` diff --git a/node_modules/fs-extra/docs/emptyDir-sync.md b/node_modules/fs-extra/docs/emptyDir-sync.md new file mode 100644 index 0000000..7decdbc --- /dev/null +++ b/node_modules/fs-extra/docs/emptyDir-sync.md @@ -0,0 +1,16 @@ +# emptyDirSync(dir) + +Ensures that a directory is empty. Deletes directory contents if the directory is not empty. If the directory does not exist, it is created. The directory itself is not deleted. + +**Alias:** `emptydirSync()` + +- `dir` `` + +## Example: + +```js +const fs = require('fs-extra') + +// assume this directory has a lot of files and folders +fs.emptyDirSync('/tmp/some/dir') +``` diff --git a/node_modules/fs-extra/docs/emptyDir.md b/node_modules/fs-extra/docs/emptyDir.md new file mode 100644 index 0000000..43292e3 --- /dev/null +++ b/node_modules/fs-extra/docs/emptyDir.md @@ -0,0 +1,21 @@ +# emptyDir(dir, [callback]) + +Ensures that a directory is empty. Deletes directory contents if the directory is not empty. If the directory does not exist, it is created. The directory itself is not deleted. + +**Alias:** `emptydir()` + +- `dir` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +// assume this directory has a lot of files and folders +fs.emptyDir('/tmp/some/dir', err => { + if (err) return console.error(err) + + console.log('success!') +}) +``` diff --git a/node_modules/fs-extra/docs/ensureDir-sync.md b/node_modules/fs-extra/docs/ensureDir-sync.md new file mode 100644 index 0000000..8f083d2 --- /dev/null +++ b/node_modules/fs-extra/docs/ensureDir-sync.md @@ -0,0 +1,17 @@ +# ensureDirSync(dir) + +Ensures that the directory exists. If the directory structure does not exist, it is created. Like `mkdir -p`. + +**Aliases:** `mkdirsSync()`, `mkdirpSync()` + +- `dir` `` + +## Example: + +```js +const fs = require('fs-extra') + +const dir = '/tmp/this/path/does/not/exist' +fs.ensureDirSync(dir) +// dir has now been created, including the directory it is to be placed in +``` diff --git a/node_modules/fs-extra/docs/ensureDir.md b/node_modules/fs-extra/docs/ensureDir.md new file mode 100644 index 0000000..1f8acfb --- /dev/null +++ b/node_modules/fs-extra/docs/ensureDir.md @@ -0,0 +1,20 @@ +# ensureDir(dir, callback) + +Ensures that the directory exists. If the directory structure does not exist, it is created. Like `mkdir -p`. + +**Aliases:** `mkdirs()`, `mkdirp()` + +- `dir` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +const dir = '/tmp/this/path/does/not/exist' +fs.ensureDir(dir, err => { + console.log(err) // => null + // dir has now been created, including the directory it is to be placed in +}) +``` diff --git a/node_modules/fs-extra/docs/ensureFile-sync.md b/node_modules/fs-extra/docs/ensureFile-sync.md new file mode 100644 index 0000000..25ac39d --- /dev/null +++ b/node_modules/fs-extra/docs/ensureFile-sync.md @@ -0,0 +1,17 @@ +# ensureFileSync(file) + +Ensures that the file exists. If the file that is requested to be created is in directories that do not exist, these directories are created. If the file already exists, it is **NOT MODIFIED**. + +**Alias:** `createFileSync()` + +- `file` `` + +## Example: + +```js +const fs = require('fs-extra') + +const file = '/tmp/this/path/does/not/exist/file.txt' +fs.ensureFileSync(file) +// file has now been created, including the directory it is to be placed in +``` diff --git a/node_modules/fs-extra/docs/ensureFile.md b/node_modules/fs-extra/docs/ensureFile.md new file mode 100644 index 0000000..1567e60 --- /dev/null +++ b/node_modules/fs-extra/docs/ensureFile.md @@ -0,0 +1,20 @@ +# ensureFile(file, callback) + +Ensures that the file exists. If the file that is requested to be created is in directories that do not exist, these directories are created. If the file already exists, it is **NOT MODIFIED**. + +**Alias:** `createFile()` + +- `file` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +const file = '/tmp/this/path/does/not/exist/file.txt' +fs.ensureFile(file, err => { + console.log(err) // => null + // file has now been created, including the directory it is to be placed in +}) +``` diff --git a/node_modules/fs-extra/docs/ensureLink-sync.md b/node_modules/fs-extra/docs/ensureLink-sync.md new file mode 100644 index 0000000..74769d3 --- /dev/null +++ b/node_modules/fs-extra/docs/ensureLink-sync.md @@ -0,0 +1,17 @@ +# ensureLinkSync(srcpath, dstpath) + +Ensures that the link exists. If the directory structure does not exist, it is created. + +- `srcpath` `` +- `dstpath` `` + +## Example: + +```js +const fs = require('fs-extra') + +const srcpath = '/tmp/file.txt' +const dstpath = '/tmp/this/path/does/not/exist/file.txt' +fs.ensureLinkSync(srcpath, dstpath) +// link has now been created, including the directory it is to be placed in +``` diff --git a/node_modules/fs-extra/docs/ensureLink.md b/node_modules/fs-extra/docs/ensureLink.md new file mode 100644 index 0000000..3cf38c5 --- /dev/null +++ b/node_modules/fs-extra/docs/ensureLink.md @@ -0,0 +1,20 @@ +# ensureLink(srcpath, dstpath, callback) + +Ensures that the link exists. If the directory structure does not exist, it is created. + +- `srcpath` `` +- `dstpath` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +const srcpath = '/tmp/file.txt' +const dstpath = '/tmp/this/path/does/not/exist/file.txt' +fs.ensureLink(srcpath, dstpath, err => { + console.log(err) // => null + // link has now been created, including the directory it is to be placed in +}) +``` diff --git a/node_modules/fs-extra/docs/ensureSymlink-sync.md b/node_modules/fs-extra/docs/ensureSymlink-sync.md new file mode 100644 index 0000000..328d4c4 --- /dev/null +++ b/node_modules/fs-extra/docs/ensureSymlink-sync.md @@ -0,0 +1,18 @@ +# ensureSymlinkSync(srcpath, dstpath, [type]) + +Ensures that the symlink exists. If the directory structure does not exist, it is created. + +- `srcpath` `` +- `dstpath` `` +- `type` `` + +## Example: + +```js +const fs = require('fs-extra') + +const srcpath = '/tmp/file.txt' +const dstpath = '/tmp/this/path/does/not/exist/file.txt' +fs.ensureSymlinkSync(srcpath, dstpath) +// symlink has now been created, including the directory it is to be placed in +``` diff --git a/node_modules/fs-extra/docs/ensureSymlink.md b/node_modules/fs-extra/docs/ensureSymlink.md new file mode 100644 index 0000000..b6c9695 --- /dev/null +++ b/node_modules/fs-extra/docs/ensureSymlink.md @@ -0,0 +1,21 @@ +# ensureSymlink(srcpath, dstpath, [type], callback) + +Ensures that the symlink exists. If the directory structure does not exist, it is created. + +- `srcpath` `` +- `dstpath` `` +- `type` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +const srcpath = '/tmp/file.txt' +const dstpath = '/tmp/this/path/does/not/exist/file.txt' +fs.ensureSymlink(srcpath, dstpath, err => { + console.log(err) // => null + // symlink has now been created, including the directory it is to be placed in +}) +``` diff --git a/node_modules/fs-extra/docs/move-sync.md b/node_modules/fs-extra/docs/move-sync.md new file mode 100644 index 0000000..cd701fe --- /dev/null +++ b/node_modules/fs-extra/docs/move-sync.md @@ -0,0 +1,24 @@ +# moveSync(src, dest, [options]) + +Moves a file or directory, even across devices. + +- `src` `` +- `dest` `` +- `options` `` + - `overwrite` ``: overwrite existing file or directory, default is `false`. + +## Example: + +```js +const fs = require('fs-extra') + +fs.moveSync('/tmp/somefile', '/tmp/does/not/exist/yet/somefile') +``` + +**Using `overwrite` option** + +```js +const fs = require('fs-extra') + +fs.moveSync('/tmp/somedir', '/tmp/may/already/existed/somedir', { overwrite: true }) +``` diff --git a/node_modules/fs-extra/docs/move.md b/node_modules/fs-extra/docs/move.md new file mode 100644 index 0000000..547af7c --- /dev/null +++ b/node_modules/fs-extra/docs/move.md @@ -0,0 +1,33 @@ +# move(src, dest, [options], callback) + +Moves a file or directory, even across devices. + +- `src` `` +- `dest` `` +- `options` `` + - `overwrite` ``: overwrite existing file or directory, default is `false`. +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', err => { + if (err) return console.error(err) + + console.log('success!') +}) +``` + +**Using `overwrite` option** + +```js +const fs = require('fs-extra') + +fs.move('/tmp/somedir', '/tmp/may/already/existed/somedir', { overwrite: true }, err => { + if (err) return console.error(err) + + console.log('success!') +}) +``` diff --git a/node_modules/fs-extra/docs/outputFile-sync.md b/node_modules/fs-extra/docs/outputFile-sync.md new file mode 100644 index 0000000..38eee8b --- /dev/null +++ b/node_modules/fs-extra/docs/outputFile-sync.md @@ -0,0 +1,19 @@ +# outputFileSync(file, data, [options]) + +Almost the same as `writeFileSync` (i.e. it [overwrites](http://pages.citebite.com/v2o5n8l2f5reb)), except that if the parent directory does not exist, it's created. `file` must be a file path (a buffer or a file descriptor is not allowed). `options` are what you'd pass to [`fs.writeFileSync()`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options). + +- `file` `` +- `data` ` | | ` +- `options` ` | ` + +## Example: + +```js +const fs = require('fs-extra') + +const file = '/tmp/this/path/does/not/exist/file.txt' +fs.outputFileSync(file, 'hello!') + +const data = fs.readFileSync(file, 'utf8') +console.log(data) // => hello! +``` diff --git a/node_modules/fs-extra/docs/outputFile.md b/node_modules/fs-extra/docs/outputFile.md new file mode 100644 index 0000000..494cba3 --- /dev/null +++ b/node_modules/fs-extra/docs/outputFile.md @@ -0,0 +1,23 @@ +# outputFile(file, data, [options], callback) + +Almost the same as `writeFile` (i.e. it [overwrites](http://pages.citebite.com/v2o5n8l2f5reb)), except that if the parent directory does not exist, it's created. `file` must be a file path (a buffer or a file descriptor is not allowed). `options` are what you'd pass to [`fs.writeFile()`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback). + +- `file` `` +- `data` ` | | ` +- `options` ` | ` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +const file = '/tmp/this/path/does/not/exist/file.txt' +fs.outputFile(file, 'hello!', err => { + console.log(err) // => null + + fs.readFile(file, 'utf8', (err, data) => { + console.log(data) // => hello! + }) +}) +``` diff --git a/node_modules/fs-extra/docs/outputJson-sync.md b/node_modules/fs-extra/docs/outputJson-sync.md new file mode 100644 index 0000000..cab6316 --- /dev/null +++ b/node_modules/fs-extra/docs/outputJson-sync.md @@ -0,0 +1,22 @@ +# outputJsonSync(file, object, [options]) + +Almost the same as [`writeJsonSync`](writeJson-sync.md), except that if the directory does not exist, it's created. +`options` are what you'd pass to [`jsonFile.writeFileSync()`](https://github.com/jprichardson/node-jsonfile#writefilesyncfilename-obj-options). + +**Alias:** `outputJSONSync()` + +- `file` `` +- `object` `` +- `options` `` + +## Example: + +```js +const fs = require('fs-extra') + +const file = '/tmp/this/path/does/not/exist/file.json' +fs.outputJsonSync(file, {name: 'JP'}) + +const data = fs.readJsonSync(file) +console.log(data.name) // => JP +``` diff --git a/node_modules/fs-extra/docs/outputJson.md b/node_modules/fs-extra/docs/outputJson.md new file mode 100644 index 0000000..58917b8 --- /dev/null +++ b/node_modules/fs-extra/docs/outputJson.md @@ -0,0 +1,26 @@ +# outputJson(file, object, [options], callback) + +Almost the same as [`writeJson`](writeJson.md), except that if the directory does not exist, it's created. +`options` are what you'd pass to [`jsonFile.writeFile()`](https://github.com/jprichardson/node-jsonfile#writefilefilename-options-callback). + +**Alias:** `outputJSON()` + +- `file` `` +- `object` `` +- `options` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +const file = '/tmp/this/path/does/not/exist/file.json' +fs.outputJson(file, {name: 'JP'}, err => { + console.log(err) // => null + + fs.readJson(file, (err, data) => { + console.log(data.name) // => JP + }) +}) +``` diff --git a/node_modules/fs-extra/docs/readJson-sync.md b/node_modules/fs-extra/docs/readJson-sync.md new file mode 100644 index 0000000..a135637 --- /dev/null +++ b/node_modules/fs-extra/docs/readJson-sync.md @@ -0,0 +1,33 @@ +# readJsonSync(file, [options]) + +Reads a JSON file and then parses it into an object. `options` are the same +that you'd pass to [`jsonFile.readFileSync`](https://github.com/jprichardson/node-jsonfile#readfilesyncfilename-options). + +**Alias:** `readJSONSync()` + +- `file` `` +- `options` `` + +## Example: + +```js +const fs = require('fs-extra') + +const packageObj = fs.readJsonSync('./package.json') +console.log(packageObj.version) // => 2.0.0 +``` + +--- + +`readJsonSync()` can take a `throws` option set to `false` and it won't throw if the JSON is invalid. Example: + +```js +const fs = require('fs-extra') + +const file = '/tmp/some-invalid.json' +const data = '{not valid JSON' +fs.writeFileSync(file, data) + +const obj = fs.readJsonSync(file, { throws: false }) +console.log(obj) // => null +``` diff --git a/node_modules/fs-extra/docs/readJson.md b/node_modules/fs-extra/docs/readJson.md new file mode 100644 index 0000000..acaf19c --- /dev/null +++ b/node_modules/fs-extra/docs/readJson.md @@ -0,0 +1,40 @@ +# readJson(file, [options], callback) + +Reads a JSON file and then parses it into an object. `options` are the same +that you'd pass to [`jsonFile.readFile`](https://github.com/jprichardson/node-jsonfile#readfilefilename-options-callback). + +**Alias:** `readJSON()` + +- `file` `` +- `options` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +fs.readJson('./package.json', (err, packageObj) => { + if (err) console.error(err) + + console.log(packageObj.version) // => 0.1.3 +}) +``` + +--- + +`readJson()` can take a `throws` option set to `false` and it won't throw if the JSON is invalid. Example: + +```js +const fs = require('fs-extra') + +const file = '/tmp/some-invalid.json' +const data = '{not valid JSON' +fs.writeFileSync(file, data) + +fs.readJson(file, { throws: false }, (err, obj) => { + if (err) console.error(err) + + console.log(obj) // => null +}) +``` diff --git a/node_modules/fs-extra/docs/remove-sync.md b/node_modules/fs-extra/docs/remove-sync.md new file mode 100644 index 0000000..fb01fe8 --- /dev/null +++ b/node_modules/fs-extra/docs/remove-sync.md @@ -0,0 +1,16 @@ +# removeSync(path) + +Removes a file or directory. The directory can have contents. Like `rm -rf`. + +- `path` `` + +## Example: + +```js +const fs = require('fs-extra') + +// remove file +fs.removeSync('/tmp/myfile') + +fs.removeSync('/home/jprichardson') // I just deleted my entire HOME directory. +``` diff --git a/node_modules/fs-extra/docs/remove.md b/node_modules/fs-extra/docs/remove.md new file mode 100644 index 0000000..68f9162 --- /dev/null +++ b/node_modules/fs-extra/docs/remove.md @@ -0,0 +1,25 @@ +# remove(path, callback) + +Removes a file or directory. The directory can have contents. Like `rm -rf`. + +- `path` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +// remove file +fs.remove('/tmp/myfile', err => { + if (err) return console.error(err) + + console.log('success!') +}) + +fs.remove('/home/jprichardson', err => { + if (err) return console.error(err) + + console.log('success!') // I just deleted my entire HOME directory. +}) +``` diff --git a/node_modules/fs-extra/docs/writeJson-sync.md b/node_modules/fs-extra/docs/writeJson-sync.md new file mode 100644 index 0000000..9e649bb --- /dev/null +++ b/node_modules/fs-extra/docs/writeJson-sync.md @@ -0,0 +1,21 @@ +# writeJsonSync(file, object, [options]) + +Writes an object to a JSON file. `options` are the same that +you'd pass to [`jsonFile.writeFileSync()`](https://github.com/jprichardson/node-jsonfile#writefilesyncfilename-obj-options). + +**Alias:** `writeJSONSync()` + +- `file` `` +- `object` `` +- `options` `` + +## Example: + +```js +const fs = require('fs-extra') + +fs.writeJsonSync('./package.json', {name: 'fs-extra'}) +``` +--- + +**See also:** [`outputJsonSync()`](outputJson-sync.md) diff --git a/node_modules/fs-extra/docs/writeJson.md b/node_modules/fs-extra/docs/writeJson.md new file mode 100644 index 0000000..3f8f042 --- /dev/null +++ b/node_modules/fs-extra/docs/writeJson.md @@ -0,0 +1,27 @@ +# writeJson(file, object, [options], callback) + +Writes an object to a JSON file. `options` are the same that +you'd pass to [`jsonFile.writeFile()`](https://github.com/jprichardson/node-jsonfile#writefilefilename-options-callback). + +**Alias:** `writeJSON()` + +- `file` `` +- `object` `` +- `options` `` +- `callback` `` + +## Example: + +```js +const fs = require('fs-extra') + +fs.writeJson('./package.json', {name: 'fs-extra'}, err => { + if (err) return console.error(err) + + console.log('success!') +}) +``` + +--- + +**See also:** [`outputJson()`](outputJson.md) diff --git a/node_modules/fs-extra/lib/copy-sync/copy-file-sync.js b/node_modules/fs-extra/lib/copy-sync/copy-file-sync.js new file mode 100644 index 0000000..4e4cd3f --- /dev/null +++ b/node_modules/fs-extra/lib/copy-sync/copy-file-sync.js @@ -0,0 +1,41 @@ +'use strict' + +const fs = require('graceful-fs') + +const BUF_LENGTH = 64 * 1024 +const _buff = new Buffer(BUF_LENGTH) + +function copyFileSync (srcFile, destFile, options) { + const overwrite = options.overwrite + const errorOnExist = options.errorOnExist + const preserveTimestamps = options.preserveTimestamps + + if (fs.existsSync(destFile)) { + if (overwrite) { + fs.unlinkSync(destFile) + } else if (errorOnExist) { + throw new Error(`${destFile} already exists`) + } else return + } + + const fdr = fs.openSync(srcFile, 'r') + const stat = fs.fstatSync(fdr) + const fdw = fs.openSync(destFile, 'w', stat.mode) + let bytesRead = 1 + let pos = 0 + + while (bytesRead > 0) { + bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos) + fs.writeSync(fdw, _buff, 0, bytesRead) + pos += bytesRead + } + + if (preserveTimestamps) { + fs.futimesSync(fdw, stat.atime, stat.mtime) + } + + fs.closeSync(fdr) + fs.closeSync(fdw) +} + +module.exports = copyFileSync diff --git a/node_modules/fs-extra/lib/copy-sync/copy-sync.js b/node_modules/fs-extra/lib/copy-sync/copy-sync.js new file mode 100644 index 0000000..9d5639c --- /dev/null +++ b/node_modules/fs-extra/lib/copy-sync/copy-sync.js @@ -0,0 +1,62 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const copyFileSync = require('./copy-file-sync') +const mkdir = require('../mkdirs') + +function copySync (src, dest, options) { + if (typeof options === 'function' || options instanceof RegExp) { + options = {filter: options} + } + + options = options || {} + options.recursive = !!options.recursive + + // default to true for now + options.clobber = 'clobber' in options ? !!options.clobber : true + // overwrite falls back to clobber + options.overwrite = 'overwrite' in options ? !!options.overwrite : options.clobber + options.dereference = 'dereference' in options ? !!options.dereference : false + options.preserveTimestamps = 'preserveTimestamps' in options ? !!options.preserveTimestamps : false + + options.filter = options.filter || function () { return true } + + // Warn about using preserveTimestamps on 32-bit node: + if (options.preserveTimestamps && process.arch === 'ia32') { + console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n + see https://github.com/jprichardson/node-fs-extra/issues/269`) + } + + const stats = (options.recursive && !options.dereference) ? fs.lstatSync(src) : fs.statSync(src) + const destFolder = path.dirname(dest) + const destFolderExists = fs.existsSync(destFolder) + let performCopy = false + + if (options.filter instanceof RegExp) { + console.warn('Warning: fs-extra: Passing a RegExp filter is deprecated, use a function') + performCopy = options.filter.test(src) + } else if (typeof options.filter === 'function') performCopy = options.filter(src, dest) + + if (stats.isFile() && performCopy) { + if (!destFolderExists) mkdir.mkdirsSync(destFolder) + copyFileSync(src, dest, { + overwrite: options.overwrite, + errorOnExist: options.errorOnExist, + preserveTimestamps: options.preserveTimestamps + }) + } else if (stats.isDirectory() && performCopy) { + if (!fs.existsSync(dest)) mkdir.mkdirsSync(dest) + const contents = fs.readdirSync(src) + contents.forEach(content => { + const opts = options + opts.recursive = true + copySync(path.join(src, content), path.join(dest, content), opts) + }) + } else if (options.recursive && stats.isSymbolicLink() && performCopy) { + const srcPath = fs.readlinkSync(src) + fs.symlinkSync(srcPath, dest) + } +} + +module.exports = copySync diff --git a/node_modules/fs-extra/lib/copy-sync/index.js b/node_modules/fs-extra/lib/copy-sync/index.js new file mode 100644 index 0000000..ebc7e0b --- /dev/null +++ b/node_modules/fs-extra/lib/copy-sync/index.js @@ -0,0 +1,3 @@ +module.exports = { + copySync: require('./copy-sync') +} diff --git a/node_modules/fs-extra/lib/copy/copy.js b/node_modules/fs-extra/lib/copy/copy.js new file mode 100644 index 0000000..d66c898 --- /dev/null +++ b/node_modules/fs-extra/lib/copy/copy.js @@ -0,0 +1,52 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const ncp = require('./ncp') +const mkdir = require('../mkdirs') + +function copy (src, dest, options, callback) { + if (typeof options === 'function' && !callback) { + callback = options + options = {} + } else if (typeof options === 'function' || options instanceof RegExp) { + options = {filter: options} + } + callback = callback || function () {} + options = options || {} + + // Warn about using preserveTimestamps on 32-bit node: + if (options.preserveTimestamps && process.arch === 'ia32') { + console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n + see https://github.com/jprichardson/node-fs-extra/issues/269`) + } + + // don't allow src and dest to be the same + const basePath = process.cwd() + const currentPath = path.resolve(basePath, src) + const targetPath = path.resolve(basePath, dest) + if (currentPath === targetPath) return callback(new Error('Source and destination must not be the same.')) + + fs.lstat(src, (err, stats) => { + if (err) return callback(err) + + let dir = null + if (stats.isDirectory()) { + const parts = dest.split(path.sep) + parts.pop() + dir = parts.join(path.sep) + } else { + dir = path.dirname(dest) + } + + fs.exists(dir, dirExists => { + if (dirExists) return ncp(src, dest, options, callback) + mkdir.mkdirs(dir, err => { + if (err) return callback(err) + ncp(src, dest, options, callback) + }) + }) + }) +} + +module.exports = copy diff --git a/node_modules/fs-extra/lib/copy/index.js b/node_modules/fs-extra/lib/copy/index.js new file mode 100644 index 0000000..3e09016 --- /dev/null +++ b/node_modules/fs-extra/lib/copy/index.js @@ -0,0 +1,3 @@ +module.exports = { + copy: require('./copy') +} diff --git a/node_modules/fs-extra/lib/copy/ncp.js b/node_modules/fs-extra/lib/copy/ncp.js new file mode 100644 index 0000000..9670ee0 --- /dev/null +++ b/node_modules/fs-extra/lib/copy/ncp.js @@ -0,0 +1,234 @@ +// imported from ncp (this is temporary, will rewrite) + +var fs = require('graceful-fs') +var path = require('path') +var utimes = require('../util/utimes') + +function ncp (source, dest, options, callback) { + if (!callback) { + callback = options + options = {} + } + + var basePath = process.cwd() + var currentPath = path.resolve(basePath, source) + var targetPath = path.resolve(basePath, dest) + + var filter = options.filter + var transform = options.transform + var overwrite = options.overwrite + // If overwrite is undefined, use clobber, otherwise default to true: + if (overwrite === undefined) overwrite = options.clobber + if (overwrite === undefined) overwrite = true + var errorOnExist = options.errorOnExist + var dereference = options.dereference + var preserveTimestamps = options.preserveTimestamps === true + + var started = 0 + var finished = 0 + var running = 0 + + var errored = false + + startCopy(currentPath) + + function startCopy (source) { + started++ + if (filter) { + if (filter instanceof RegExp) { + console.warn('Warning: fs-extra: Passing a RegExp filter is deprecated, use a function') + if (!filter.test(source)) { + return doneOne(true) + } + } else if (typeof filter === 'function') { + if (!filter(source, dest)) { + return doneOne(true) + } + } + } + return getStats(source) + } + + function getStats (source) { + var stat = dereference ? fs.stat : fs.lstat + running++ + stat(source, function (err, stats) { + if (err) return onError(err) + + // We need to get the mode from the stats object and preserve it. + var item = { + name: source, + mode: stats.mode, + mtime: stats.mtime, // modified time + atime: stats.atime, // access time + stats: stats // temporary + } + + if (stats.isDirectory()) { + return onDir(item) + } else if (stats.isFile() || stats.isCharacterDevice() || stats.isBlockDevice()) { + return onFile(item) + } else if (stats.isSymbolicLink()) { + // Symlinks don't really need to know about the mode. + return onLink(source) + } + }) + } + + function onFile (file) { + var target = file.name.replace(currentPath, targetPath.replace('$', '$$$$')) // escapes '$' with '$$' + isWritable(target, function (writable) { + if (writable) { + copyFile(file, target) + } else { + if (overwrite) { + rmFile(target, function () { + copyFile(file, target) + }) + } else if (errorOnExist) { + onError(new Error(target + ' already exists')) + } else { + doneOne() + } + } + }) + } + + function copyFile (file, target) { + var readStream = fs.createReadStream(file.name) + var writeStream = fs.createWriteStream(target, { mode: file.mode }) + + readStream.on('error', onError) + writeStream.on('error', onError) + + if (transform) { + transform(readStream, writeStream, file) + } else { + writeStream.on('open', function () { + readStream.pipe(writeStream) + }) + } + + writeStream.once('close', function () { + fs.chmod(target, file.mode, function (err) { + if (err) return onError(err) + if (preserveTimestamps) { + utimes.utimesMillis(target, file.atime, file.mtime, function (err) { + if (err) return onError(err) + return doneOne() + }) + } else { + doneOne() + } + }) + }) + } + + function rmFile (file, done) { + fs.unlink(file, function (err) { + if (err) return onError(err) + return done() + }) + } + + function onDir (dir) { + var target = dir.name.replace(currentPath, targetPath.replace('$', '$$$$')) // escapes '$' with '$$' + isWritable(target, function (writable) { + if (writable) { + return mkDir(dir, target) + } + copyDir(dir.name) + }) + } + + function mkDir (dir, target) { + fs.mkdir(target, dir.mode, function (err) { + if (err) return onError(err) + // despite setting mode in fs.mkdir, doesn't seem to work + // so we set it here. + fs.chmod(target, dir.mode, function (err) { + if (err) return onError(err) + copyDir(dir.name) + }) + }) + } + + function copyDir (dir) { + fs.readdir(dir, function (err, items) { + if (err) return onError(err) + items.forEach(function (item) { + startCopy(path.join(dir, item)) + }) + return doneOne() + }) + } + + function onLink (link) { + var target = link.replace(currentPath, targetPath) + fs.readlink(link, function (err, resolvedPath) { + if (err) return onError(err) + checkLink(resolvedPath, target) + }) + } + + function checkLink (resolvedPath, target) { + if (dereference) { + resolvedPath = path.resolve(basePath, resolvedPath) + } + isWritable(target, function (writable) { + if (writable) { + return makeLink(resolvedPath, target) + } + fs.readlink(target, function (err, targetDest) { + if (err) return onError(err) + + if (dereference) { + targetDest = path.resolve(basePath, targetDest) + } + if (targetDest === resolvedPath) { + return doneOne() + } + return rmFile(target, function () { + makeLink(resolvedPath, target) + }) + }) + }) + } + + function makeLink (linkPath, target) { + fs.symlink(linkPath, target, function (err) { + if (err) return onError(err) + return doneOne() + }) + } + + function isWritable (path, done) { + fs.lstat(path, function (err) { + if (err) { + if (err.code === 'ENOENT') return done(true) + return done(false) + } + return done(false) + }) + } + + function onError (err) { + // ensure callback is defined & called only once: + if (!errored && callback !== undefined) { + errored = true + return callback(err) + } + } + + function doneOne (skipped) { + if (!skipped) running-- + finished++ + if ((started === finished) && (running === 0)) { + if (callback !== undefined) { + return callback(null) + } + } + } +} + +module.exports = ncp diff --git a/node_modules/fs-extra/lib/empty/index.js b/node_modules/fs-extra/lib/empty/index.js new file mode 100644 index 0000000..180c3f7 --- /dev/null +++ b/node_modules/fs-extra/lib/empty/index.js @@ -0,0 +1,47 @@ +'use strict' + +const fs = require('fs') +const path = require('path') +const mkdir = require('../mkdirs') +const remove = require('../remove') + +function emptyDir (dir, callback) { + callback = callback || function () {} + fs.readdir(dir, (err, items) => { + if (err) return mkdir.mkdirs(dir, callback) + + items = items.map(item => path.join(dir, item)) + + deleteItem() + + function deleteItem () { + const item = items.pop() + if (!item) return callback() + remove.remove(item, err => { + if (err) return callback(err) + deleteItem() + }) + } + }) +} + +function emptyDirSync (dir) { + let items + try { + items = fs.readdirSync(dir) + } catch (err) { + return mkdir.mkdirsSync(dir) + } + + items.forEach(item => { + item = path.join(dir, item) + remove.removeSync(item) + }) +} + +module.exports = { + emptyDirSync, + emptydirSync: emptyDirSync, + emptyDir, + emptydir: emptyDir +} diff --git a/node_modules/fs-extra/lib/ensure/file.js b/node_modules/fs-extra/lib/ensure/file.js new file mode 100644 index 0000000..031d130 --- /dev/null +++ b/node_modules/fs-extra/lib/ensure/file.js @@ -0,0 +1,45 @@ +'use strict' + +const path = require('path') +const fs = require('graceful-fs') +const mkdir = require('../mkdirs') + +function createFile (file, callback) { + function makeFile () { + fs.writeFile(file, '', err => { + if (err) return callback(err) + callback() + }) + } + + fs.exists(file, fileExists => { + if (fileExists) return callback() + const dir = path.dirname(file) + fs.exists(dir, dirExists => { + if (dirExists) return makeFile() + mkdir.mkdirs(dir, err => { + if (err) return callback(err) + makeFile() + }) + }) + }) +} + +function createFileSync (file) { + if (fs.existsSync(file)) return + + const dir = path.dirname(file) + if (!fs.existsSync(dir)) { + mkdir.mkdirsSync(dir) + } + + fs.writeFileSync(file, '') +} + +module.exports = { + createFile, + createFileSync, + // alias + ensureFile: createFile, + ensureFileSync: createFileSync +} diff --git a/node_modules/fs-extra/lib/ensure/index.js b/node_modules/fs-extra/lib/ensure/index.js new file mode 100644 index 0000000..c1f67b7 --- /dev/null +++ b/node_modules/fs-extra/lib/ensure/index.js @@ -0,0 +1,23 @@ +'use strict' + +const file = require('./file') +const link = require('./link') +const symlink = require('./symlink') + +module.exports = { + // file + createFile: file.createFile, + createFileSync: file.createFileSync, + ensureFile: file.createFile, + ensureFileSync: file.createFileSync, + // link + createLink: link.createLink, + createLinkSync: link.createLinkSync, + ensureLink: link.createLink, + ensureLinkSync: link.createLinkSync, + // symlink + createSymlink: symlink.createSymlink, + createSymlinkSync: symlink.createSymlinkSync, + ensureSymlink: symlink.createSymlink, + ensureSymlinkSync: symlink.createSymlinkSync +} diff --git a/node_modules/fs-extra/lib/ensure/link.js b/node_modules/fs-extra/lib/ensure/link.js new file mode 100644 index 0000000..8284fae --- /dev/null +++ b/node_modules/fs-extra/lib/ensure/link.js @@ -0,0 +1,60 @@ +'use strict' + +const path = require('path') +const fs = require('graceful-fs') +const mkdir = require('../mkdirs') + +function createLink (srcpath, dstpath, callback) { + function makeLink (srcpath, dstpath) { + fs.link(srcpath, dstpath, err => { + if (err) return callback(err) + callback(null) + }) + } + + fs.exists(dstpath, destinationExists => { + if (destinationExists) return callback(null) + fs.lstat(srcpath, (err, stat) => { + if (err) { + err.message = err.message.replace('lstat', 'ensureLink') + return callback(err) + } + + const dir = path.dirname(dstpath) + fs.exists(dir, dirExists => { + if (dirExists) return makeLink(srcpath, dstpath) + mkdir.mkdirs(dir, err => { + if (err) return callback(err) + makeLink(srcpath, dstpath) + }) + }) + }) + }) +} + +function createLinkSync (srcpath, dstpath, callback) { + const destinationExists = fs.existsSync(dstpath) + if (destinationExists) return undefined + + try { + fs.lstatSync(srcpath) + } catch (err) { + err.message = err.message.replace('lstat', 'ensureLink') + throw err + } + + const dir = path.dirname(dstpath) + const dirExists = fs.existsSync(dir) + if (dirExists) return fs.linkSync(srcpath, dstpath) + mkdir.mkdirsSync(dir) + + return fs.linkSync(srcpath, dstpath) +} + +module.exports = { + createLink, + createLinkSync, + // alias + ensureLink: createLink, + ensureLinkSync: createLinkSync +} diff --git a/node_modules/fs-extra/lib/ensure/symlink-paths.js b/node_modules/fs-extra/lib/ensure/symlink-paths.js new file mode 100644 index 0000000..e52d039 --- /dev/null +++ b/node_modules/fs-extra/lib/ensure/symlink-paths.js @@ -0,0 +1,97 @@ +'use strict' + +const path = require('path') +const fs = require('graceful-fs') + +/** + * Function that returns two types of paths, one relative to symlink, and one + * relative to the current working directory. Checks if path is absolute or + * relative. If the path is relative, this function checks if the path is + * relative to symlink or relative to current working directory. This is an + * initiative to find a smarter `srcpath` to supply when building symlinks. + * This allows you to determine which path to use out of one of three possible + * types of source paths. The first is an absolute path. This is detected by + * `path.isAbsolute()`. When an absolute path is provided, it is checked to + * see if it exists. If it does it's used, if not an error is returned + * (callback)/ thrown (sync). The other two options for `srcpath` are a + * relative url. By default Node's `fs.symlink` works by creating a symlink + * using `dstpath` and expects the `srcpath` to be relative to the newly + * created symlink. If you provide a `srcpath` that does not exist on the file + * system it results in a broken symlink. To minimize this, the function + * checks to see if the 'relative to symlink' source file exists, and if it + * does it will use it. If it does not, it checks if there's a file that + * exists that is relative to the current working directory, if does its used. + * This preserves the expectations of the original fs.symlink spec and adds + * the ability to pass in `relative to current working direcotry` paths. + */ + +function symlinkPaths (srcpath, dstpath, callback) { + if (path.isAbsolute(srcpath)) { + return fs.lstat(srcpath, (err, stat) => { + if (err) { + err.message = err.message.replace('lstat', 'ensureSymlink') + return callback(err) + } + return callback(null, { + 'toCwd': srcpath, + 'toDst': srcpath + }) + }) + } else { + const dstdir = path.dirname(dstpath) + const relativeToDst = path.join(dstdir, srcpath) + return fs.exists(relativeToDst, exists => { + if (exists) { + return callback(null, { + 'toCwd': relativeToDst, + 'toDst': srcpath + }) + } else { + return fs.lstat(srcpath, (err, stat) => { + if (err) { + err.message = err.message.replace('lstat', 'ensureSymlink') + return callback(err) + } + return callback(null, { + 'toCwd': srcpath, + 'toDst': path.relative(dstdir, srcpath) + }) + }) + } + }) + } +} + +function symlinkPathsSync (srcpath, dstpath) { + let exists + if (path.isAbsolute(srcpath)) { + exists = fs.existsSync(srcpath) + if (!exists) throw new Error('absolute srcpath does not exist') + return { + 'toCwd': srcpath, + 'toDst': srcpath + } + } else { + const dstdir = path.dirname(dstpath) + const relativeToDst = path.join(dstdir, srcpath) + exists = fs.existsSync(relativeToDst) + if (exists) { + return { + 'toCwd': relativeToDst, + 'toDst': srcpath + } + } else { + exists = fs.existsSync(srcpath) + if (!exists) throw new Error('relative srcpath does not exist') + return { + 'toCwd': srcpath, + 'toDst': path.relative(dstdir, srcpath) + } + } + } +} + +module.exports = { + symlinkPaths, + symlinkPathsSync +} diff --git a/node_modules/fs-extra/lib/ensure/symlink-type.js b/node_modules/fs-extra/lib/ensure/symlink-type.js new file mode 100644 index 0000000..4f8787c --- /dev/null +++ b/node_modules/fs-extra/lib/ensure/symlink-type.js @@ -0,0 +1,31 @@ +'use strict' + +const fs = require('graceful-fs') + +function symlinkType (srcpath, type, callback) { + callback = (typeof type === 'function') ? type : callback + type = (typeof type === 'function') ? false : type + if (type) return callback(null, type) + fs.lstat(srcpath, (err, stats) => { + if (err) return callback(null, 'file') + type = (stats && stats.isDirectory()) ? 'dir' : 'file' + callback(null, type) + }) +} + +function symlinkTypeSync (srcpath, type) { + let stats + + if (type) return type + try { + stats = fs.lstatSync(srcpath) + } catch (e) { + return 'file' + } + return (stats && stats.isDirectory()) ? 'dir' : 'file' +} + +module.exports = { + symlinkType, + symlinkTypeSync +} diff --git a/node_modules/fs-extra/lib/ensure/symlink.js b/node_modules/fs-extra/lib/ensure/symlink.js new file mode 100644 index 0000000..2ea9e06 --- /dev/null +++ b/node_modules/fs-extra/lib/ensure/symlink.js @@ -0,0 +1,64 @@ +'use strict' + +const path = require('path') +const fs = require('graceful-fs') +const _mkdirs = require('../mkdirs') +const mkdirs = _mkdirs.mkdirs +const mkdirsSync = _mkdirs.mkdirsSync + +const _symlinkPaths = require('./symlink-paths') +const symlinkPaths = _symlinkPaths.symlinkPaths +const symlinkPathsSync = _symlinkPaths.symlinkPathsSync + +const _symlinkType = require('./symlink-type') +const symlinkType = _symlinkType.symlinkType +const symlinkTypeSync = _symlinkType.symlinkTypeSync + +function createSymlink (srcpath, dstpath, type, callback) { + callback = (typeof type === 'function') ? type : callback + type = (typeof type === 'function') ? false : type + + fs.exists(dstpath, destinationExists => { + if (destinationExists) return callback(null) + symlinkPaths(srcpath, dstpath, (err, relative) => { + if (err) return callback(err) + srcpath = relative.toDst + symlinkType(relative.toCwd, type, (err, type) => { + if (err) return callback(err) + const dir = path.dirname(dstpath) + fs.exists(dir, dirExists => { + if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) + mkdirs(dir, err => { + if (err) return callback(err) + fs.symlink(srcpath, dstpath, type, callback) + }) + }) + }) + }) + }) +} + +function createSymlinkSync (srcpath, dstpath, type, callback) { + callback = (typeof type === 'function') ? type : callback + type = (typeof type === 'function') ? false : type + + const destinationExists = fs.existsSync(dstpath) + if (destinationExists) return undefined + + const relative = symlinkPathsSync(srcpath, dstpath) + srcpath = relative.toDst + type = symlinkTypeSync(relative.toCwd, type) + const dir = path.dirname(dstpath) + const exists = fs.existsSync(dir) + if (exists) return fs.symlinkSync(srcpath, dstpath, type) + mkdirsSync(dir) + return fs.symlinkSync(srcpath, dstpath, type) +} + +module.exports = { + createSymlink, + createSymlinkSync, + // alias + ensureSymlink: createSymlink, + ensureSymlinkSync: createSymlinkSync +} diff --git a/node_modules/fs-extra/lib/index.js b/node_modules/fs-extra/lib/index.js new file mode 100644 index 0000000..d25fd54 --- /dev/null +++ b/node_modules/fs-extra/lib/index.js @@ -0,0 +1,37 @@ +'use strict' + +const assign = require('./util/assign') + +const fse = {} +const gfs = require('graceful-fs') + +// attach fs methods to fse +Object.keys(gfs).forEach(key => { + fse[key] = gfs[key] +}) + +const fs = fse + +assign(fs, require('./copy')) +assign(fs, require('./copy-sync')) +assign(fs, require('./mkdirs')) +assign(fs, require('./remove')) +assign(fs, require('./json')) +assign(fs, require('./move')) +assign(fs, require('./move-sync')) +assign(fs, require('./empty')) +assign(fs, require('./ensure')) +assign(fs, require('./output')) + +module.exports = fs + +// maintain backwards compatibility for awhile +const jsonfile = {} +Object.defineProperty(jsonfile, 'spaces', { + get: () => fs.spaces, // found in ./json + set: val => { + fs.spaces = val + } +}) + +module.exports.jsonfile = jsonfile // so users of fs-extra can modify jsonFile.spaces diff --git a/node_modules/fs-extra/lib/json/index.js b/node_modules/fs-extra/lib/json/index.js new file mode 100644 index 0000000..4229311 --- /dev/null +++ b/node_modules/fs-extra/lib/json/index.js @@ -0,0 +1,11 @@ +'use strict' + +const jsonFile = require('./jsonfile') + +jsonFile.outputJsonSync = require('./output-json-sync') +jsonFile.outputJson = require('./output-json') +// aliases +jsonFile.outputJSONSync = require('./output-json-sync') +jsonFile.outputJSON = require('./output-json') + +module.exports = jsonFile diff --git a/node_modules/fs-extra/lib/json/jsonfile.js b/node_modules/fs-extra/lib/json/jsonfile.js new file mode 100644 index 0000000..e3630ee --- /dev/null +++ b/node_modules/fs-extra/lib/json/jsonfile.js @@ -0,0 +1,16 @@ +'use strict' + +const jsonFile = require('jsonfile') + +module.exports = { + // jsonfile exports + readJson: jsonFile.readFile, + readJSON: jsonFile.readFile, + readJsonSync: jsonFile.readFileSync, + readJSONSync: jsonFile.readFileSync, + writeJson: jsonFile.writeFile, + writeJSON: jsonFile.writeFile, + writeJsonSync: jsonFile.writeFileSync, + writeJSONSync: jsonFile.writeFileSync, + spaces: 2 // default in fs-extra +} diff --git a/node_modules/fs-extra/lib/json/output-json-sync.js b/node_modules/fs-extra/lib/json/output-json-sync.js new file mode 100644 index 0000000..6f76710 --- /dev/null +++ b/node_modules/fs-extra/lib/json/output-json-sync.js @@ -0,0 +1,18 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const mkdir = require('../mkdirs') +const jsonFile = require('./jsonfile') + +function outputJsonSync (file, data, options) { + const dir = path.dirname(file) + + if (!fs.existsSync(dir)) { + mkdir.mkdirsSync(dir) + } + + jsonFile.writeJsonSync(file, data, options) +} + +module.exports = outputJsonSync diff --git a/node_modules/fs-extra/lib/json/output-json.js b/node_modules/fs-extra/lib/json/output-json.js new file mode 100644 index 0000000..2f928c5 --- /dev/null +++ b/node_modules/fs-extra/lib/json/output-json.js @@ -0,0 +1,26 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const mkdir = require('../mkdirs') +const jsonFile = require('./jsonfile') + +function outputJson (file, data, options, callback) { + if (typeof options === 'function') { + callback = options + options = {} + } + + const dir = path.dirname(file) + + fs.exists(dir, itDoes => { + if (itDoes) return jsonFile.writeJson(file, data, options, callback) + + mkdir.mkdirs(dir, err => { + if (err) return callback(err) + jsonFile.writeJson(file, data, options, callback) + }) + }) +} + +module.exports = outputJson diff --git a/node_modules/fs-extra/lib/mkdirs/index.js b/node_modules/fs-extra/lib/mkdirs/index.js new file mode 100644 index 0000000..2611217 --- /dev/null +++ b/node_modules/fs-extra/lib/mkdirs/index.js @@ -0,0 +1,9 @@ +module.exports = { + mkdirs: require('./mkdirs'), + mkdirsSync: require('./mkdirs-sync'), + // alias + mkdirp: require('./mkdirs'), + mkdirpSync: require('./mkdirs-sync'), + ensureDir: require('./mkdirs'), + ensureDirSync: require('./mkdirs-sync') +} diff --git a/node_modules/fs-extra/lib/mkdirs/mkdirs-sync.js b/node_modules/fs-extra/lib/mkdirs/mkdirs-sync.js new file mode 100644 index 0000000..a3ece40 --- /dev/null +++ b/node_modules/fs-extra/lib/mkdirs/mkdirs-sync.js @@ -0,0 +1,59 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const invalidWin32Path = require('./win32').invalidWin32Path + +const o777 = parseInt('0777', 8) + +function mkdirsSync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts } + } + + let mode = opts.mode + const xfs = opts.fs || fs + + if (process.platform === 'win32' && invalidWin32Path(p)) { + const errInval = new Error(p + ' contains invalid WIN32 path characters.') + errInval.code = 'EINVAL' + throw errInval + } + + if (mode === undefined) { + mode = o777 & (~process.umask()) + } + if (!made) made = null + + p = path.resolve(p) + + try { + xfs.mkdirSync(p, mode) + made = made || p + } catch (err0) { + switch (err0.code) { + case 'ENOENT': + if (path.dirname(p) === p) throw err0 + made = mkdirsSync(path.dirname(p), opts, made) + mkdirsSync(p, opts, made) + break + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + let stat + try { + stat = xfs.statSync(p) + } catch (err1) { + throw err0 + } + if (!stat.isDirectory()) throw err0 + break + } + } + + return made +} + +module.exports = mkdirsSync diff --git a/node_modules/fs-extra/lib/mkdirs/mkdirs.js b/node_modules/fs-extra/lib/mkdirs/mkdirs.js new file mode 100644 index 0000000..1897533 --- /dev/null +++ b/node_modules/fs-extra/lib/mkdirs/mkdirs.js @@ -0,0 +1,63 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const invalidWin32Path = require('./win32').invalidWin32Path + +const o777 = parseInt('0777', 8) + +function mkdirs (p, opts, callback, made) { + if (typeof opts === 'function') { + callback = opts + opts = {} + } else if (!opts || typeof opts !== 'object') { + opts = { mode: opts } + } + + if (process.platform === 'win32' && invalidWin32Path(p)) { + const errInval = new Error(p + ' contains invalid WIN32 path characters.') + errInval.code = 'EINVAL' + return callback(errInval) + } + + let mode = opts.mode + const xfs = opts.fs || fs + + if (mode === undefined) { + mode = o777 & (~process.umask()) + } + if (!made) made = null + + callback = callback || function () {} + p = path.resolve(p) + + xfs.mkdir(p, mode, er => { + if (!er) { + made = made || p + return callback(null, made) + } + switch (er.code) { + case 'ENOENT': + if (path.dirname(p) === p) return callback(er) + mkdirs(path.dirname(p), opts, (er, made) => { + if (er) callback(er, made) + else mkdirs(p, opts, callback, made) + }) + break + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, (er2, stat) => { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) callback(er, made) + else callback(null, made) + }) + break + } + }) +} + +module.exports = mkdirs diff --git a/node_modules/fs-extra/lib/mkdirs/win32.js b/node_modules/fs-extra/lib/mkdirs/win32.js new file mode 100644 index 0000000..99b3920 --- /dev/null +++ b/node_modules/fs-extra/lib/mkdirs/win32.js @@ -0,0 +1,25 @@ +'use strict' + +const path = require('path') + +// get drive on windows +function getRootPath (p) { + p = path.normalize(path.resolve(p)).split(path.sep) + if (p.length > 0) return p[0] + return null +} + +// http://stackoverflow.com/a/62888/10333 contains more accurate +// TODO: expand to include the rest +const INVALID_PATH_CHARS = /[<>:"|?*]/ + +function invalidWin32Path (p) { + const rp = getRootPath(p) + p = p.replace(rp, '') + return INVALID_PATH_CHARS.test(p) +} + +module.exports = { + getRootPath, + invalidWin32Path +} diff --git a/node_modules/fs-extra/lib/move-sync/index.js b/node_modules/fs-extra/lib/move-sync/index.js new file mode 100644 index 0000000..3c2aa93 --- /dev/null +++ b/node_modules/fs-extra/lib/move-sync/index.js @@ -0,0 +1,117 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const copySync = require('../copy-sync').copySync +const removeSync = require('../remove').removeSync +const mkdirpSync = require('../mkdirs').mkdirsSync + +function moveSync (src, dest, options) { + options = options || {} + const overwrite = options.overwrite || options.clobber || false + + src = path.resolve(src) + dest = path.resolve(dest) + + if (src === dest) return + + if (isSrcSubdir(src, dest)) throw new Error(`Cannot move '${src}' into itself '${dest}'.`) + + mkdirpSync(path.dirname(dest)) + tryRenameSync() + + function tryRenameSync () { + if (overwrite) { + try { + return fs.renameSync(src, dest) + } catch (err) { + if (err.code === 'ENOTEMPTY' || err.code === 'EEXIST' || err.code === 'EPERM') { + removeSync(dest) + options.overwrite = false // just overwriteed it, no need to do it again + return moveSync(src, dest, options) + } + + if (err.code !== 'EXDEV') throw err + return moveSyncAcrossDevice(src, dest, overwrite) + } + } else { + try { + fs.linkSync(src, dest) + return fs.unlinkSync(src) + } catch (err) { + if (err.code === 'EXDEV' || err.code === 'EISDIR' || err.code === 'EPERM' || err.code === 'ENOTSUP') { + return moveSyncAcrossDevice(src, dest, overwrite) + } + throw err + } + } + } +} + +function moveSyncAcrossDevice (src, dest, overwrite) { + const stat = fs.statSync(src) + + if (stat.isDirectory()) { + return moveDirSyncAcrossDevice(src, dest, overwrite) + } else { + return moveFileSyncAcrossDevice(src, dest, overwrite) + } +} + +function moveFileSyncAcrossDevice (src, dest, overwrite) { + const BUF_LENGTH = 64 * 1024 + const _buff = new Buffer(BUF_LENGTH) + + const flags = overwrite ? 'w' : 'wx' + + const fdr = fs.openSync(src, 'r') + const stat = fs.fstatSync(fdr) + const fdw = fs.openSync(dest, flags, stat.mode) + let bytesRead = 1 + let pos = 0 + + while (bytesRead > 0) { + bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos) + fs.writeSync(fdw, _buff, 0, bytesRead) + pos += bytesRead + } + + fs.closeSync(fdr) + fs.closeSync(fdw) + return fs.unlinkSync(src) +} + +function moveDirSyncAcrossDevice (src, dest, overwrite) { + const options = { + overwrite: false + } + + if (overwrite) { + removeSync(dest) + tryCopySync() + } else { + tryCopySync() + } + + function tryCopySync () { + copySync(src, dest, options) + return removeSync(src) + } +} + +// return true if dest is a subdir of src, otherwise false. +// extract dest base dir and check if that is the same as src basename +function isSrcSubdir (src, dest) { + try { + return fs.statSync(src).isDirectory() && + src !== dest && + dest.indexOf(src) > -1 && + dest.split(path.dirname(src) + path.sep)[1].split(path.sep)[0] === path.basename(src) + } catch (e) { + return false + } +} + +module.exports = { + moveSync +} diff --git a/node_modules/fs-extra/lib/move/index.js b/node_modules/fs-extra/lib/move/index.js new file mode 100644 index 0000000..6bbdaf4 --- /dev/null +++ b/node_modules/fs-extra/lib/move/index.js @@ -0,0 +1,161 @@ +'use strict' + +// most of this code was written by Andrew Kelley +// licensed under the BSD license: see +// https://github.com/andrewrk/node-mv/blob/master/package.json + +// this needs a cleanup + +const fs = require('graceful-fs') +const ncp = require('../copy/ncp') +const path = require('path') +const remove = require('../remove').remove +const mkdirp = require('../mkdirs').mkdirs + +function move (source, dest, options, callback) { + if (typeof options === 'function') { + callback = options + options = {} + } + + const shouldMkdirp = ('mkdirp' in options) ? options.mkdirp : true + const overwrite = options.overwrite || options.clobber || false + + if (shouldMkdirp) { + mkdirs() + } else { + doRename() + } + + function mkdirs () { + mkdirp(path.dirname(dest), err => { + if (err) return callback(err) + doRename() + }) + } + + function doRename () { + if (path.resolve(source) === path.resolve(dest)) { + setImmediate(callback) + } else if (overwrite) { + fs.rename(source, dest, err => { + if (!err) return callback() + + if (err.code === 'ENOTEMPTY' || err.code === 'EEXIST') { + remove(dest, err => { + if (err) return callback(err) + options.overwrite = false // just overwriteed it, no need to do it again + move(source, dest, options, callback) + }) + return + } + + // weird Windows shit + if (err.code === 'EPERM') { + setTimeout(() => { + remove(dest, err => { + if (err) return callback(err) + options.overwrite = false + move(source, dest, options, callback) + }) + }, 200) + return + } + + if (err.code !== 'EXDEV') return callback(err) + moveAcrossDevice(source, dest, overwrite, callback) + }) + } else { + fs.link(source, dest, err => { + if (err) { + if (err.code === 'EXDEV' || err.code === 'EISDIR' || err.code === 'EPERM' || err.code === 'ENOTSUP') { + moveAcrossDevice(source, dest, overwrite, callback) + return + } + callback(err) + return + } + fs.unlink(source, callback) + }) + } + } +} + +function moveAcrossDevice (source, dest, overwrite, callback) { + fs.stat(source, (err, stat) => { + if (err) { + callback(err) + return + } + + if (stat.isDirectory()) { + moveDirAcrossDevice(source, dest, overwrite, callback) + } else { + moveFileAcrossDevice(source, dest, overwrite, callback) + } + }) +} + +function moveFileAcrossDevice (source, dest, overwrite, callback) { + const flags = overwrite ? 'w' : 'wx' + const ins = fs.createReadStream(source) + const outs = fs.createWriteStream(dest, { flags }) + + ins.on('error', err => { + ins.destroy() + outs.destroy() + outs.removeListener('close', onClose) + + // may want to create a directory but `out` line above + // creates an empty file for us: See #108 + // don't care about error here + fs.unlink(dest, () => { + // note: `err` here is from the input stream errror + if (err.code === 'EISDIR' || err.code === 'EPERM') { + moveDirAcrossDevice(source, dest, overwrite, callback) + } else { + callback(err) + } + }) + }) + + outs.on('error', err => { + ins.destroy() + outs.destroy() + outs.removeListener('close', onClose) + callback(err) + }) + + outs.once('close', onClose) + ins.pipe(outs) + + function onClose () { + fs.unlink(source, callback) + } +} + +function moveDirAcrossDevice (source, dest, overwrite, callback) { + const options = { + overwrite: false + } + + if (overwrite) { + remove(dest, err => { + if (err) return callback(err) + startNcp() + }) + } else { + startNcp() + } + + function startNcp () { + ncp(source, dest, options, err => { + if (err) return callback(err) + remove(source, callback) + }) + } +} + +module.exports = { + move +} diff --git a/node_modules/fs-extra/lib/output/index.js b/node_modules/fs-extra/lib/output/index.js new file mode 100644 index 0000000..f4eb9bb --- /dev/null +++ b/node_modules/fs-extra/lib/output/index.js @@ -0,0 +1,37 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const mkdir = require('../mkdirs') + +function outputFile (file, data, encoding, callback) { + if (typeof encoding === 'function') { + callback = encoding + encoding = 'utf8' + } + + const dir = path.dirname(file) + fs.exists(dir, itDoes => { + if (itDoes) return fs.writeFile(file, data, encoding, callback) + + mkdir.mkdirs(dir, err => { + if (err) return callback(err) + + fs.writeFile(file, data, encoding, callback) + }) + }) +} + +function outputFileSync (file, data, encoding) { + const dir = path.dirname(file) + if (fs.existsSync(dir)) { + return fs.writeFileSync.apply(fs, arguments) + } + mkdir.mkdirsSync(dir) + fs.writeFileSync.apply(fs, arguments) +} + +module.exports = { + outputFile, + outputFileSync +} diff --git a/node_modules/fs-extra/lib/remove/index.js b/node_modules/fs-extra/lib/remove/index.js new file mode 100644 index 0000000..0e3b5dd --- /dev/null +++ b/node_modules/fs-extra/lib/remove/index.js @@ -0,0 +1,17 @@ +'use strict' + +const rimraf = require('./rimraf') + +function removeSync (dir) { + return rimraf.sync(dir, {disableGlob: true}) +} + +function remove (dir, callback) { + const options = {disableGlob: true} + return callback ? rimraf(dir, options, callback) : rimraf(dir, options, function () {}) +} + +module.exports = { + remove, + removeSync +} diff --git a/node_modules/fs-extra/lib/remove/rimraf.js b/node_modules/fs-extra/lib/remove/rimraf.js new file mode 100644 index 0000000..141a82d --- /dev/null +++ b/node_modules/fs-extra/lib/remove/rimraf.js @@ -0,0 +1,296 @@ +'use strict' + +const fs = require('graceful-fs') +const path = require('path') +const assert = require('assert') + +const isWindows = (process.platform === 'win32') + +function defaults (options) { + const methods = [ + 'unlink', + 'chmod', + 'stat', + 'lstat', + 'rmdir', + 'readdir' + ] + methods.forEach(m => { + options[m] = options[m] || fs[m] + m = m + 'Sync' + options[m] = options[m] || fs[m] + }) + + options.maxBusyTries = options.maxBusyTries || 3 +} + +function rimraf (p, options, cb) { + let busyTries = 0 + + if (typeof options === 'function') { + cb = options + options = {} + } + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert.equal(typeof cb, 'function', 'rimraf: callback function required') + assert(options, 'rimraf: invalid options argument provided') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + defaults(options) + + rimraf_(p, options, function CB (er) { + if (er) { + if (isWindows && (er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && + busyTries < options.maxBusyTries) { + busyTries++ + let time = busyTries * 100 + // try again, with the same exact callback as this one. + return setTimeout(() => rimraf_(p, options, CB), time) + } + + // already gone + if (er.code === 'ENOENT') er = null + } + + cb(er) + }) +} + +// Two possible strategies. +// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR +// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR +// +// Both result in an extra syscall when you guess wrong. However, there +// are likely far more normal files in the world than directories. This +// is based on the assumption that a the average number of files per +// directory is >= 1. +// +// If anyone ever complains about this, then I guess the strategy could +// be made configurable somehow. But until then, YAGNI. +function rimraf_ (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + // sunos lets the root user unlink directories, which is... weird. + // so we have to lstat here and make sure it's not a dir. + options.lstat(p, (er, st) => { + if (er && er.code === 'ENOENT') { + return cb(null) + } + + // Windows can EPERM on stat. Life is suffering. + if (er && er.code === 'EPERM' && isWindows) { + return fixWinEPERM(p, options, er, cb) + } + + if (st && st.isDirectory()) { + return rmdir(p, options, er, cb) + } + + options.unlink(p, er => { + if (er) { + if (er.code === 'ENOENT') { + return cb(null) + } + if (er.code === 'EPERM') { + return (isWindows) + ? fixWinEPERM(p, options, er, cb) + : rmdir(p, options, er, cb) + } + if (er.code === 'EISDIR') { + return rmdir(p, options, er, cb) + } + } + return cb(er) + }) + }) +} + +function fixWinEPERM (p, options, er, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + if (er) { + assert(er instanceof Error) + } + + options.chmod(p, 666, er2 => { + if (er2) { + cb(er2.code === 'ENOENT' ? null : er) + } else { + options.stat(p, (er3, stats) => { + if (er3) { + cb(er3.code === 'ENOENT' ? null : er) + } else if (stats.isDirectory()) { + rmdir(p, options, er, cb) + } else { + options.unlink(p, cb) + } + }) + } + }) +} + +function fixWinEPERMSync (p, options, er) { + let stats + + assert(p) + assert(options) + if (er) { + assert(er instanceof Error) + } + + try { + options.chmodSync(p, 666) + } catch (er2) { + if (er2.code === 'ENOENT') { + return + } else { + throw er + } + } + + try { + stats = options.statSync(p) + } catch (er3) { + if (er3.code === 'ENOENT') { + return + } else { + throw er + } + } + + if (stats.isDirectory()) { + rmdirSync(p, options, er) + } else { + options.unlinkSync(p) + } +} + +function rmdir (p, options, originalEr, cb) { + assert(p) + assert(options) + if (originalEr) { + assert(originalEr instanceof Error) + } + assert(typeof cb === 'function') + + // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) + // if we guessed wrong, and it's not a directory, then + // raise the original error. + options.rmdir(p, er => { + if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { + rmkids(p, options, cb) + } else if (er && er.code === 'ENOTDIR') { + cb(originalEr) + } else { + cb(er) + } + }) +} + +function rmkids (p, options, cb) { + assert(p) + assert(options) + assert(typeof cb === 'function') + + options.readdir(p, (er, files) => { + if (er) return cb(er) + + let n = files.length + let errState + + if (n === 0) return options.rmdir(p, cb) + + files.forEach(f => { + rimraf(path.join(p, f), options, er => { + if (errState) { + return + } + if (er) return cb(errState = er) + if (--n === 0) { + options.rmdir(p, cb) + } + }) + }) + }) +} + +// this looks simpler, and is strictly *faster*, but will +// tie up the JavaScript thread and fail on excessively +// deep directory trees. +function rimrafSync (p, options) { + let st + + options = options || {} + defaults(options) + + assert(p, 'rimraf: missing path') + assert.equal(typeof p, 'string', 'rimraf: path should be a string') + assert(options, 'rimraf: missing options') + assert.equal(typeof options, 'object', 'rimraf: options should be object') + + try { + st = options.lstatSync(p) + } catch (er) { + if (er.code === 'ENOENT') { + return + } + + // Windows can EPERM on stat. Life is suffering. + if (er.code === 'EPERM' && isWindows) { + fixWinEPERMSync(p, options, er) + } + } + + try { + // sunos lets the root user unlink directories, which is... weird. + if (st && st.isDirectory()) { + rmdirSync(p, options, null) + } else { + options.unlinkSync(p) + } + } catch (er) { + if (er.code === 'ENOENT') { + return + } else if (er.code === 'EPERM') { + return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) + } else if (er.code !== 'EISDIR') { + throw er + } + rmdirSync(p, options, er) + } +} + +function rmdirSync (p, options, originalEr) { + assert(p) + assert(options) + if (originalEr) { + assert(originalEr instanceof Error) + } + + try { + options.rmdirSync(p) + } catch (er) { + if (er.code === 'ENOENT') { + return + } else if (er.code === 'ENOTDIR') { + throw originalEr + } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { + rmkidsSync(p, options) + } + } +} + +function rmkidsSync (p, options) { + assert(p) + assert(options) + options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) + options.rmdirSync(p, options) +} + +module.exports = rimraf +rimraf.sync = rimrafSync diff --git a/node_modules/fs-extra/lib/util/assign.js b/node_modules/fs-extra/lib/util/assign.js new file mode 100644 index 0000000..317e5ec --- /dev/null +++ b/node_modules/fs-extra/lib/util/assign.js @@ -0,0 +1,16 @@ +'use strict' + +// simple mutable assign +function assign () { + const args = [].slice.call(arguments).filter(i => i) + const dest = args.shift() + args.forEach(src => { + Object.keys(src).forEach(key => { + dest[key] = src[key] + }) + }) + + return dest +} + +module.exports = assign diff --git a/node_modules/fs-extra/lib/util/utimes.js b/node_modules/fs-extra/lib/util/utimes.js new file mode 100644 index 0000000..4c32099 --- /dev/null +++ b/node_modules/fs-extra/lib/util/utimes.js @@ -0,0 +1,72 @@ +'use strict' + +const fs = require('graceful-fs') +const os = require('os') +const path = require('path') + +// HFS, ext{2,3}, FAT do not, Node.js v0.10 does not +function hasMillisResSync () { + let tmpfile = path.join('millis-test-sync' + Date.now().toString() + Math.random().toString().slice(2)) + tmpfile = path.join(os.tmpdir(), tmpfile) + + // 550 millis past UNIX epoch + const d = new Date(1435410243862) + fs.writeFileSync(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141') + const fd = fs.openSync(tmpfile, 'r+') + fs.futimesSync(fd, d, d) + fs.closeSync(fd) + return fs.statSync(tmpfile).mtime > 1435410243000 +} + +function hasMillisRes (callback) { + let tmpfile = path.join('millis-test' + Date.now().toString() + Math.random().toString().slice(2)) + tmpfile = path.join(os.tmpdir(), tmpfile) + + // 550 millis past UNIX epoch + const d = new Date(1435410243862) + fs.writeFile(tmpfile, 'https://github.com/jprichardson/node-fs-extra/pull/141', err => { + if (err) return callback(err) + fs.open(tmpfile, 'r+', (err, fd) => { + if (err) return callback(err) + fs.futimes(fd, d, d, err => { + if (err) return callback(err) + fs.close(fd, err => { + if (err) return callback(err) + fs.stat(tmpfile, (err, stats) => { + if (err) return callback(err) + callback(null, stats.mtime > 1435410243000) + }) + }) + }) + }) + }) +} + +function timeRemoveMillis (timestamp) { + if (typeof timestamp === 'number') { + return Math.floor(timestamp / 1000) * 1000 + } else if (timestamp instanceof Date) { + return new Date(Math.floor(timestamp.getTime() / 1000) * 1000) + } else { + throw new Error('fs-extra: timeRemoveMillis() unknown parameter type') + } +} + +function utimesMillis (path, atime, mtime, callback) { + // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) + fs.open(path, 'r+', (err, fd) => { + if (err) return callback(err) + fs.futimes(fd, atime, mtime, futimesErr => { + fs.close(fd, closeErr => { + if (callback) callback(futimesErr || closeErr) + }) + }) + }) +} + +module.exports = { + hasMillisRes, + hasMillisResSync, + timeRemoveMillis, + utimesMillis +} diff --git a/node_modules/fs-extra/package.json b/node_modules/fs-extra/package.json new file mode 100644 index 0000000..51103bf --- /dev/null +++ b/node_modules/fs-extra/package.json @@ -0,0 +1,96 @@ +{ + "_args": [ + [ + "fs-extra@2.1.2", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "fs-extra@2.1.2", + "_id": "fs-extra@2.1.2", + "_inBundle": false, + "_integrity": "sha1-BGxwFjzvmq1GsOSn+kZ/si1x3jU=", + "_location": "/fs-extra", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "fs-extra@2.1.2", + "name": "fs-extra", + "escapedName": "fs-extra", + "rawSpec": "2.1.2", + "saveSpec": null, + "fetchSpec": "2.1.2" + }, + "_requiredBy": [ + "/node-latex" + ], + "_resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-2.1.2.tgz", + "_spec": "2.1.2", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "JP Richardson", + "email": "jprichardson@gmail.com" + }, + "bugs": { + "url": "https://github.com/jprichardson/node-fs-extra/issues" + }, + "dependencies": { + "graceful-fs": "^4.1.2", + "jsonfile": "^2.1.0" + }, + "description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as mkdir -p, cp -r, and rm -rf.", + "devDependencies": { + "coveralls": "^2.11.2", + "istanbul": "^0.4.5", + "klaw": "^1.0.0", + "klaw-sync": "^1.1.2", + "minimist": "^1.1.1", + "mocha": "^3.1.2", + "proxyquire": "^1.7.10", + "read-dir-files": "^0.1.1", + "rimraf": "^2.2.8", + "secure-random": "^1.1.1", + "standard": "^8.5.0" + }, + "homepage": "https://github.com/jprichardson/node-fs-extra", + "keywords": [ + "fs", + "file", + "file system", + "copy", + "directory", + "extra", + "mkdirp", + "mkdir", + "mkdirs", + "recursive", + "json", + "read", + "write", + "extra", + "delete", + "remove", + "touch", + "create", + "text", + "output", + "move" + ], + "license": "MIT", + "main": "./lib/index", + "name": "fs-extra", + "repository": { + "type": "git", + "url": "git+https://github.com/jprichardson/node-fs-extra.git" + }, + "scripts": { + "coverage": "istanbul cover -i 'lib/**' -x '**/__tests__/**' test.js", + "coveralls": "npm run coverage && coveralls < coverage/lcov.info", + "lint": "standard", + "test": "npm run lint && npm run unit", + "test-find": "find ./lib/**/__tests__ -name *.test.js | xargs mocha", + "unit": "node test.js" + }, + "version": "2.1.2" +} diff --git a/node_modules/fs.realpath/LICENSE b/node_modules/fs.realpath/LICENSE new file mode 100644 index 0000000..5bd884c --- /dev/null +++ b/node_modules/fs.realpath/LICENSE @@ -0,0 +1,43 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +---- + +This library bundles a version of the `fs.realpath` and `fs.realpathSync` +methods from Node.js v0.10 under the terms of the Node.js MIT license. + +Node's license follows, also included at the header of `old.js` which contains +the licensed code: + + 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. diff --git a/node_modules/fs.realpath/README.md b/node_modules/fs.realpath/README.md new file mode 100644 index 0000000..a42ceac --- /dev/null +++ b/node_modules/fs.realpath/README.md @@ -0,0 +1,33 @@ +# fs.realpath + +A backwards-compatible fs.realpath for Node v6 and above + +In Node v6, the JavaScript implementation of fs.realpath was replaced +with a faster (but less resilient) native implementation. That raises +new and platform-specific errors and cannot handle long or excessively +symlink-looping paths. + +This module handles those cases by detecting the new errors and +falling back to the JavaScript implementation. On versions of Node +prior to v6, it has no effect. + +## USAGE + +```js +var rp = require('fs.realpath') + +// async version +rp.realpath(someLongAndLoopingPath, function (er, real) { + // the ELOOP was handled, but it was a bit slower +}) + +// sync version +var real = rp.realpathSync(someLongAndLoopingPath) + +// monkeypatch at your own risk! +// This replaces the fs.realpath/fs.realpathSync builtins +rp.monkeypatch() + +// un-do the monkeypatching +rp.unmonkeypatch() +``` diff --git a/node_modules/fs.realpath/index.js b/node_modules/fs.realpath/index.js new file mode 100644 index 0000000..b09c7c7 --- /dev/null +++ b/node_modules/fs.realpath/index.js @@ -0,0 +1,66 @@ +module.exports = realpath +realpath.realpath = realpath +realpath.sync = realpathSync +realpath.realpathSync = realpathSync +realpath.monkeypatch = monkeypatch +realpath.unmonkeypatch = unmonkeypatch + +var fs = require('fs') +var origRealpath = fs.realpath +var origRealpathSync = fs.realpathSync + +var version = process.version +var ok = /^v[0-5]\./.test(version) +var old = require('./old.js') + +function newError (er) { + return er && er.syscall === 'realpath' && ( + er.code === 'ELOOP' || + er.code === 'ENOMEM' || + er.code === 'ENAMETOOLONG' + ) +} + +function realpath (p, cache, cb) { + if (ok) { + return origRealpath(p, cache, cb) + } + + if (typeof cache === 'function') { + cb = cache + cache = null + } + origRealpath(p, cache, function (er, result) { + if (newError(er)) { + old.realpath(p, cache, cb) + } else { + cb(er, result) + } + }) +} + +function realpathSync (p, cache) { + if (ok) { + return origRealpathSync(p, cache) + } + + try { + return origRealpathSync(p, cache) + } catch (er) { + if (newError(er)) { + return old.realpathSync(p, cache) + } else { + throw er + } + } +} + +function monkeypatch () { + fs.realpath = realpath + fs.realpathSync = realpathSync +} + +function unmonkeypatch () { + fs.realpath = origRealpath + fs.realpathSync = origRealpathSync +} diff --git a/node_modules/fs.realpath/old.js b/node_modules/fs.realpath/old.js new file mode 100644 index 0000000..b40305e --- /dev/null +++ b/node_modules/fs.realpath/old.js @@ -0,0 +1,303 @@ +// 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 pathModule = require('path'); +var isWindows = process.platform === 'win32'; +var fs = require('fs'); + +// JavaScript implementation of realpath, ported from node pre-v6 + +var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); + +function rethrow() { + // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and + // is fairly slow to generate. + var callback; + if (DEBUG) { + var backtrace = new Error; + callback = debugCallback; + } else + callback = missingCallback; + + return callback; + + function debugCallback(err) { + if (err) { + backtrace.message = err.message; + err = backtrace; + missingCallback(err); + } + } + + function missingCallback(err) { + if (err) { + if (process.throwDeprecation) + throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs + else if (!process.noDeprecation) { + var msg = 'fs: missing callback ' + (err.stack || err.message); + if (process.traceDeprecation) + console.trace(msg); + else + console.error(msg); + } + } + } +} + +function maybeCallback(cb) { + return typeof cb === 'function' ? cb : rethrow(); +} + +var normalize = pathModule.normalize; + +// Regexp that finds the next partion of a (partial) path +// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] +if (isWindows) { + var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; +} else { + var nextPartRe = /(.*?)(?:[\/]+|$)/g; +} + +// Regex to find the device root, including trailing slash. E.g. 'c:\\'. +if (isWindows) { + var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; +} else { + var splitRootRe = /^[\/]*/; +} + +exports.realpathSync = function realpathSync(p, cache) { + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return cache[p]; + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstatSync(base); + knownHard[base] = true; + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + // NB: p.length changes. + while (pos < p.length) { + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + continue; + } + + var resolvedLink; + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // some known symbolic link. no need to stat again. + resolvedLink = cache[base]; + } else { + var stat = fs.lstatSync(base); + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + continue; + } + + // read the link if it wasn't read before + // dev/ino always return 0 on windows, so skip the check. + var linkTarget = null; + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + linkTarget = seenLinks[id]; + } + } + if (linkTarget === null) { + fs.statSync(base); + linkTarget = fs.readlinkSync(base); + } + resolvedLink = pathModule.resolve(previous, linkTarget); + // track this, if given a cache. + if (cache) cache[base] = resolvedLink; + if (!isWindows) seenLinks[id] = linkTarget; + } + + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } + + if (cache) cache[original] = p; + + return p; +}; + + +exports.realpath = function realpath(p, cache, cb) { + if (typeof cb !== 'function') { + cb = maybeCallback(cache); + cache = null; + } + + // make p is absolute + p = pathModule.resolve(p); + + if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { + return process.nextTick(cb.bind(null, null, cache[p])); + } + + var original = p, + seenLinks = {}, + knownHard = {}; + + // current character position in p + var pos; + // the partial path so far, including a trailing slash if any + var current; + // the partial path without a trailing slash (except when pointing at a root) + var base; + // the partial path scanned in the previous round, with slash + var previous; + + start(); + + function start() { + // Skip over roots + var m = splitRootRe.exec(p); + pos = m[0].length; + current = m[0]; + base = m[0]; + previous = ''; + + // On windows, check that the root exists. On unix there is no need. + if (isWindows && !knownHard[base]) { + fs.lstat(base, function(err) { + if (err) return cb(err); + knownHard[base] = true; + LOOP(); + }); + } else { + process.nextTick(LOOP); + } + } + + // walk down the path, swapping out linked pathparts for their real + // values + function LOOP() { + // stop if scanned past end of path + if (pos >= p.length) { + if (cache) cache[original] = p; + return cb(null, p); + } + + // find the next part + nextPartRe.lastIndex = pos; + var result = nextPartRe.exec(p); + previous = current; + current += result[0]; + base = previous + result[1]; + pos = nextPartRe.lastIndex; + + // continue if not a symlink + if (knownHard[base] || (cache && cache[base] === base)) { + return process.nextTick(LOOP); + } + + if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { + // known symbolic link. no need to stat again. + return gotResolvedLink(cache[base]); + } + + return fs.lstat(base, gotStat); + } + + function gotStat(err, stat) { + if (err) return cb(err); + + // if not a symlink, skip to the next path part + if (!stat.isSymbolicLink()) { + knownHard[base] = true; + if (cache) cache[base] = base; + return process.nextTick(LOOP); + } + + // stat & read the link if not read before + // call gotTarget as soon as the link target is known + // dev/ino always return 0 on windows, so skip the check. + if (!isWindows) { + var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); + if (seenLinks.hasOwnProperty(id)) { + return gotTarget(null, seenLinks[id], base); + } + } + fs.stat(base, function(err) { + if (err) return cb(err); + + fs.readlink(base, function(err, target) { + if (!isWindows) seenLinks[id] = target; + gotTarget(err, target); + }); + }); + } + + function gotTarget(err, target, base) { + if (err) return cb(err); + + var resolvedLink = pathModule.resolve(previous, target); + if (cache) cache[base] = resolvedLink; + gotResolvedLink(resolvedLink); + } + + function gotResolvedLink(resolvedLink) { + // resolve the link, then start over + p = pathModule.resolve(resolvedLink, p.slice(pos)); + start(); + } +}; diff --git a/node_modules/fs.realpath/package.json b/node_modules/fs.realpath/package.json new file mode 100644 index 0000000..e224957 --- /dev/null +++ b/node_modules/fs.realpath/package.json @@ -0,0 +1,63 @@ +{ + "_args": [ + [ + "fs.realpath@1.0.0", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "fs.realpath@1.0.0", + "_id": "fs.realpath@1.0.0", + "_inBundle": false, + "_integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", + "_location": "/fs.realpath", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "fs.realpath@1.0.0", + "name": "fs.realpath", + "escapedName": "fs.realpath", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "_spec": "1.0.0", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/fs.realpath/issues" + }, + "dependencies": {}, + "description": "Use node's fs.realpath, but fall back to the JS implementation if the native one fails", + "devDependencies": {}, + "files": [ + "old.js", + "index.js" + ], + "homepage": "https://github.com/isaacs/fs.realpath#readme", + "keywords": [ + "realpath", + "fs", + "polyfill" + ], + "license": "ISC", + "main": "index.js", + "name": "fs.realpath", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/fs.realpath.git" + }, + "scripts": { + "test": "tap test/*.js --cov" + }, + "version": "1.0.0" +} diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE new file mode 100644 index 0000000..42ca266 --- /dev/null +++ b/node_modules/glob/LICENSE @@ -0,0 +1,21 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +## Glob Logo + +Glob's logo created by Tanya Brassie , licensed +under a Creative Commons Attribution-ShareAlike 4.0 International License +https://creativecommons.org/licenses/by-sa/4.0/ diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md new file mode 100644 index 0000000..0916a48 --- /dev/null +++ b/node_modules/glob/README.md @@ -0,0 +1,375 @@ +# Glob + +Match files using the patterns the shell uses, like stars and stuff. + +[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master) + +This is a glob implementation in JavaScript. It uses the `minimatch` +library to do its matching. + +![](logo/glob.png) + +## Usage + +Install with npm + +``` +npm i glob +``` + +```javascript +var glob = require("glob") + +// options is optional +glob("**/*.js", options, function (er, files) { + // files is an array of filenames. + // If the `nonull` option is set, and nothing + // was found, then files is ["**/*.js"] + // er is an error object or null. +}) +``` + +## Glob Primer + +"Globs" are the patterns you type when you do stuff like `ls *.js` on +the command line, or put `build/*` in a `.gitignore` file. + +Before parsing the path part patterns, braced sections are expanded +into a set. Braced sections start with `{` and end with `}`, with any +number of comma-delimited sections within. Braced sections may contain +slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`. + +The following characters have special magic meaning when used in a +path portion: + +* `*` Matches 0 or more characters in a single path portion +* `?` Matches 1 character +* `[...]` Matches a range of characters, similar to a RegExp range. + If the first character of the range is `!` or `^` then it matches + any character not in the range. +* `!(pattern|pattern|pattern)` Matches anything that does not match + any of the patterns provided. +* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the + patterns provided. +* `+(pattern|pattern|pattern)` Matches one or more occurrences of the + patterns provided. +* `*(a|b|c)` Matches zero or more occurrences of the patterns provided +* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns + provided +* `**` If a "globstar" is alone in a path portion, then it matches + zero or more directories and subdirectories searching for matches. + It does not crawl symlinked directories. + +### Dots + +If a file or directory path portion has a `.` as the first character, +then it will not match any glob pattern unless that pattern's +corresponding path part also has a `.` as its first character. + +For example, the pattern `a/.*/c` would match the file at `a/.b/c`. +However the pattern `a/*/c` would not, because `*` does not start with +a dot character. + +You can make glob treat dots as normal characters by setting +`dot:true` in the options. + +### Basename Matching + +If you set `matchBase:true` in the options, and the pattern has no +slashes in it, then it will seek for any file anywhere in the tree +with a matching basename. For example, `*.js` would match +`test/simple/basic.js`. + +### Empty Sets + +If no matching files are found, then an empty array is returned. This +differs from the shell, where the pattern itself is returned. For +example: + + $ echo a*s*d*f + a*s*d*f + +To get the bash-style behavior, set the `nonull:true` in the options. + +### See Also: + +* `man sh` +* `man bash` (Search for "Pattern Matching") +* `man 3 fnmatch` +* `man 5 gitignore` +* [minimatch documentation](https://github.com/isaacs/minimatch) + +## glob.hasMagic(pattern, [options]) + +Returns `true` if there are any special characters in the pattern, and +`false` otherwise. + +Note that the options affect the results. If `noext:true` is set in +the options object, then `+(a|b)` will not be considered a magic +pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}` +then that is considered magical, unless `nobrace:true` is set in the +options. + +## glob(pattern, [options], cb) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* `cb` `{Function}` + * `err` `{Error | null}` + * `matches` `{Array}` filenames found matching the pattern + +Perform an asynchronous glob search. + +## glob.sync(pattern, [options]) + +* `pattern` `{String}` Pattern to be matched +* `options` `{Object}` +* return: `{Array}` filenames found matching the pattern + +Perform a synchronous glob search. + +## Class: glob.Glob + +Create a Glob object by instantiating the `glob.Glob` class. + +```javascript +var Glob = require("glob").Glob +var mg = new Glob(pattern, options, cb) +``` + +It's an EventEmitter, and starts walking the filesystem to find matches +immediately. + +### new glob.Glob(pattern, [options], [cb]) + +* `pattern` `{String}` pattern to search for +* `options` `{Object}` +* `cb` `{Function}` Called when an error occurs, or matches are found + * `err` `{Error | null}` + * `matches` `{Array}` filenames found matching the pattern + +Note that if the `sync` flag is set in the options, then matches will +be immediately available on the `g.found` member. + +### Properties + +* `minimatch` The minimatch object that the glob uses. +* `options` The options object passed in. +* `aborted` Boolean which is set to true when calling `abort()`. There + is no way at this time to continue a glob search after aborting, but + you can re-use the statCache to avoid having to duplicate syscalls. +* `cache` Convenience object. Each field has the following possible + values: + * `false` - Path does not exist + * `true` - Path exists + * `'FILE'` - Path exists, and is not a directory + * `'DIR'` - Path exists, and is a directory + * `[file, entries, ...]` - Path exists, is a directory, and the + array value is the results of `fs.readdir` +* `statCache` Cache of `fs.stat` results, to prevent statting the same + path multiple times. +* `symlinks` A record of which paths are symbolic links, which is + relevant in resolving `**` patterns. +* `realpathCache` An optional object which is passed to `fs.realpath` + to minimize unnecessary syscalls. It is stored on the instantiated + Glob object, and may be re-used. + +### Events + +* `end` When the matching is finished, this is emitted with all the + matches found. If the `nonull` option is set, and no match was found, + then the `matches` list contains the original pattern. The matches + are sorted, unless the `nosort` flag is set. +* `match` Every time a match is found, this is emitted with the specific + thing that matched. It is not deduplicated or resolved to a realpath. +* `error` Emitted when an unexpected error is encountered, or whenever + any fs error occurs if `options.strict` is set. +* `abort` When `abort()` is called, this event is raised. + +### Methods + +* `pause` Temporarily stop the search +* `resume` Resume the search +* `abort` Stop the search forever + +### Options + +All the options that can be passed to Minimatch can also be passed to +Glob to change pattern matching behavior. Also, some have been added, +or have glob-specific ramifications. + +All options are false by default, unless otherwise noted. + +All options are added to the Glob object, as well. + +If you are running many `glob` operations, you can pass a Glob object +as the `options` argument to a subsequent operation to shortcut some +`stat` and `readdir` calls. At the very least, you may pass in shared +`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that +parallel glob operations will be sped up by sharing information about +the filesystem. + +* `cwd` The current working directory in which to search. Defaults + to `process.cwd()`. +* `root` The place where patterns starting with `/` will be mounted + onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix + systems, and `C:\` or some such on Windows.) +* `dot` Include `.dot` files in normal matches and `globstar` matches. + Note that an explicit dot in a portion of the pattern will always + match dot files. +* `nomount` By default, a pattern starting with a forward-slash will be + "mounted" onto the root setting, so that a valid filesystem path is + returned. Set this flag to disable that behavior. +* `mark` Add a `/` character to directory matches. Note that this + requires additional stat calls. +* `nosort` Don't sort the results. +* `stat` Set to true to stat *all* results. This reduces performance + somewhat, and is completely unnecessary, unless `readdir` is presumed + to be an untrustworthy indicator of file existence. +* `silent` When an unusual error is encountered when attempting to + read a directory, a warning will be printed to stderr. Set the + `silent` option to true to suppress these warnings. +* `strict` When an unusual error is encountered when attempting to + read a directory, the process will just continue on in search of + other matches. Set the `strict` option to raise an error in these + cases. +* `cache` See `cache` property above. Pass in a previously generated + cache object to save some fs calls. +* `statCache` A cache of results of filesystem information, to prevent + unnecessary stat calls. While it should not normally be necessary + to set this, you may pass the statCache from one glob() call to the + options object of another, if you know that the filesystem will not + change between calls. (See "Race Conditions" below.) +* `symlinks` A cache of known symbolic links. You may pass in a + previously generated `symlinks` object to save `lstat` calls when + resolving `**` matches. +* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead. +* `nounique` In some cases, brace-expanded patterns can result in the + same file showing up multiple times in the result set. By default, + this implementation prevents duplicates in the result set. Set this + flag to disable that behavior. +* `nonull` Set to never return an empty set, instead returning a set + containing the pattern itself. This is the default in glob(3). +* `debug` Set to enable debug logging in minimatch and glob. +* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets. +* `noglobstar` Do not match `**` against multiple filenames. (Ie, + treat it as a normal `*` instead.) +* `noext` Do not match `+(a|b)` "extglob" patterns. +* `nocase` Perform a case-insensitive match. Note: on + case-insensitive filesystems, non-magic patterns will match by + default, since `stat` and `readdir` will not raise errors. +* `matchBase` Perform a basename-only match if the pattern does not + contain any slash characters. That is, `*.js` would be treated as + equivalent to `**/*.js`, matching all js files in all directories. +* `nodir` Do not match directories, only files. (Note: to match + *only* directories, simply put a `/` at the end of the pattern.) +* `ignore` Add a pattern or an array of glob patterns to exclude matches. + Note: `ignore` patterns are *always* in `dot:true` mode, regardless + of any other settings. +* `follow` Follow symlinked directories when expanding `**` patterns. + Note that this can result in a lot of duplicate references in the + presence of cyclic links. +* `realpath` Set to true to call `fs.realpath` on all of the results. + In the case of a symlink that cannot be resolved, the full absolute + path to the matched entry is returned (though it will usually be a + broken symlink) +* `absolute` Set to true to always receive absolute paths for matched + files. Unlike `realpath`, this also affects the values returned in + the `match` event. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between node-glob and other +implementations, and are intentional. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.3, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +Note that symlinked directories are not crawled as part of a `**`, +though their contents may match against subsequent portions of the +pattern. This prevents infinite loops and duplicates and the like. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then glob returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +### Comments and Negation + +Previously, this module let you mark a pattern as a "comment" if it +started with a `#` character, or a "negated" pattern if it started +with a `!` character. + +These options were deprecated in version 5, and removed in version 6. + +To specify things that should not match, use the `ignore` option. + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes will always +be interpreted as escape characters, not path separators. + +Results from absolute patterns such as `/foo/*` are mounted onto the +root setting using `path.join`. On windows, this will by default result +in `/foo/*` matching `C:\foo\bar.txt`. + +## Race Conditions + +Glob searching, by its very nature, is susceptible to race conditions, +since it relies on directory walking and such. + +As a result, it is possible that a file that exists when glob looks for +it may have been deleted or modified by the time it returns the result. + +As part of its internal implementation, this program caches all stat +and readdir calls that it makes, in order to cut down on system +overhead. However, this also makes it even more susceptible to races, +especially if the cache or statCache objects are reused between glob +calls. + +Users are thus advised not to use a glob result as a guarantee of +filesystem state in the face of rapid changes. For the vast majority +of operations, this is never a problem. + +## Glob Logo +Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo). + +The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/). + +## Contributing + +Any change to behavior (including bugfixes) must come with a test. + +Patches that fail tests or reduce performance will be rejected. + +``` +# to run tests +npm test + +# to re-generate test fixtures +npm run test-regen + +# to benchmark against bash/zsh +npm run bench + +# to profile javascript +npm run prof +``` + +![](oh-my-glob.gif) diff --git a/node_modules/glob/changelog.md b/node_modules/glob/changelog.md new file mode 100644 index 0000000..4163677 --- /dev/null +++ b/node_modules/glob/changelog.md @@ -0,0 +1,67 @@ +## 7.0 + +- Raise error if `options.cwd` is specified, and not a directory + +## 6.0 + +- Remove comment and negation pattern support +- Ignore patterns are always in `dot:true` mode + +## 5.0 + +- Deprecate comment and negation patterns +- Fix regression in `mark` and `nodir` options from making all cache + keys absolute path. +- Abort if `fs.readdir` returns an error that's unexpected +- Don't emit `match` events for ignored items +- Treat ENOTSUP like ENOTDIR in readdir + +## 4.5 + +- Add `options.follow` to always follow directory symlinks in globstar +- Add `options.realpath` to call `fs.realpath` on all results +- Always cache based on absolute path + +## 4.4 + +- Add `options.ignore` +- Fix handling of broken symlinks + +## 4.3 + +- Bump minimatch to 2.x +- Pass all tests on Windows + +## 4.2 + +- Add `glob.hasMagic` function +- Add `options.nodir` flag + +## 4.1 + +- Refactor sync and async implementations for performance +- Throw if callback provided to sync glob function +- Treat symbolic links in globstar results the same as Bash 4.3 + +## 4.0 + +- Use `^` for dependency versions (bumped major because this breaks + older npm versions) +- Ensure callbacks are only ever called once +- switch to ISC license + +## 3.x + +- Rewrite in JavaScript +- Add support for setting root, cwd, and windows support +- Cache many fs calls +- Add globstar support +- emit match events + +## 2.x + +- Use `glob.h` and `fnmatch.h` from NetBSD + +## 1.x + +- `glob.h` static binding. diff --git a/node_modules/glob/common.js b/node_modules/glob/common.js new file mode 100644 index 0000000..66651bb --- /dev/null +++ b/node_modules/glob/common.js @@ -0,0 +1,240 @@ +exports.alphasort = alphasort +exports.alphasorti = alphasorti +exports.setopts = setopts +exports.ownProp = ownProp +exports.makeAbs = makeAbs +exports.finish = finish +exports.mark = mark +exports.isIgnored = isIgnored +exports.childrenIgnored = childrenIgnored + +function ownProp (obj, field) { + return Object.prototype.hasOwnProperty.call(obj, field) +} + +var path = require("path") +var minimatch = require("minimatch") +var isAbsolute = require("path-is-absolute") +var Minimatch = minimatch.Minimatch + +function alphasorti (a, b) { + return a.toLowerCase().localeCompare(b.toLowerCase()) +} + +function alphasort (a, b) { + return a.localeCompare(b) +} + +function setupIgnores (self, options) { + self.ignore = options.ignore || [] + + if (!Array.isArray(self.ignore)) + self.ignore = [self.ignore] + + if (self.ignore.length) { + self.ignore = self.ignore.map(ignoreMap) + } +} + +// ignore patterns are always in dot:true mode. +function ignoreMap (pattern) { + var gmatcher = null + if (pattern.slice(-3) === '/**') { + var gpattern = pattern.replace(/(\/\*\*)+$/, '') + gmatcher = new Minimatch(gpattern, { dot: true }) + } + + return { + matcher: new Minimatch(pattern, { dot: true }), + gmatcher: gmatcher + } +} + +function setopts (self, pattern, options) { + if (!options) + options = {} + + // base-matching: just use globstar for that. + if (options.matchBase && -1 === pattern.indexOf("/")) { + if (options.noglobstar) { + throw new Error("base matching requires globstar") + } + pattern = "**/" + pattern + } + + self.silent = !!options.silent + self.pattern = pattern + self.strict = options.strict !== false + self.realpath = !!options.realpath + self.realpathCache = options.realpathCache || Object.create(null) + self.follow = !!options.follow + self.dot = !!options.dot + self.mark = !!options.mark + self.nodir = !!options.nodir + if (self.nodir) + self.mark = true + self.sync = !!options.sync + self.nounique = !!options.nounique + self.nonull = !!options.nonull + self.nosort = !!options.nosort + self.nocase = !!options.nocase + self.stat = !!options.stat + self.noprocess = !!options.noprocess + self.absolute = !!options.absolute + + self.maxLength = options.maxLength || Infinity + self.cache = options.cache || Object.create(null) + self.statCache = options.statCache || Object.create(null) + self.symlinks = options.symlinks || Object.create(null) + + setupIgnores(self, options) + + self.changedCwd = false + var cwd = process.cwd() + if (!ownProp(options, "cwd")) + self.cwd = cwd + else { + self.cwd = path.resolve(options.cwd) + self.changedCwd = self.cwd !== cwd + } + + self.root = options.root || path.resolve(self.cwd, "/") + self.root = path.resolve(self.root) + if (process.platform === "win32") + self.root = self.root.replace(/\\/g, "/") + + // TODO: is an absolute `cwd` supposed to be resolved against `root`? + // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') + self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) + if (process.platform === "win32") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + self.nomount = !!options.nomount + + // disable comments and negation in Minimatch. + // Note that they are not supported in Glob itself anyway. + options.nonegate = true + options.nocomment = true + + self.minimatch = new Minimatch(pattern, options) + self.options = self.minimatch.options +} + +function finish (self) { + var nou = self.nounique + var all = nou ? [] : Object.create(null) + + for (var i = 0, l = self.matches.length; i < l; i ++) { + var matches = self.matches[i] + if (!matches || Object.keys(matches).length === 0) { + if (self.nonull) { + // do like the shell, and spit out the literal glob + var literal = self.minimatch.globSet[i] + if (nou) + all.push(literal) + else + all[literal] = true + } + } else { + // had matches + var m = Object.keys(matches) + if (nou) + all.push.apply(all, m) + else + m.forEach(function (m) { + all[m] = true + }) + } + } + + if (!nou) + all = Object.keys(all) + + if (!self.nosort) + all = all.sort(self.nocase ? alphasorti : alphasort) + + // at *some* point we statted all of these + if (self.mark) { + for (var i = 0; i < all.length; i++) { + all[i] = self._mark(all[i]) + } + if (self.nodir) { + all = all.filter(function (e) { + var notDir = !(/\/$/.test(e)) + var c = self.cache[e] || self.cache[makeAbs(self, e)] + if (notDir && c) + notDir = c !== 'DIR' && !Array.isArray(c) + return notDir + }) + } + } + + if (self.ignore.length) + all = all.filter(function(m) { + return !isIgnored(self, m) + }) + + self.found = all +} + +function mark (self, p) { + var abs = makeAbs(self, p) + var c = self.cache[abs] + var m = p + if (c) { + var isDir = c === 'DIR' || Array.isArray(c) + var slash = p.slice(-1) === '/' + + if (isDir && !slash) + m += '/' + else if (!isDir && slash) + m = m.slice(0, -1) + + if (m !== p) { + var mabs = makeAbs(self, m) + self.statCache[mabs] = self.statCache[abs] + self.cache[mabs] = self.cache[abs] + } + } + + return m +} + +// lotta situps... +function makeAbs (self, f) { + var abs = f + if (f.charAt(0) === '/') { + abs = path.join(self.root, f) + } else if (isAbsolute(f) || f === '') { + abs = f + } else if (self.changedCwd) { + abs = path.resolve(self.cwd, f) + } else { + abs = path.resolve(f) + } + + if (process.platform === 'win32') + abs = abs.replace(/\\/g, '/') + + return abs +} + + +// Return true, if pattern ends with globstar '**', for the accompanying parent directory. +// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents +function isIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) + }) +} + +function childrenIgnored (self, path) { + if (!self.ignore.length) + return false + + return self.ignore.some(function(item) { + return !!(item.gmatcher && item.gmatcher.match(path)) + }) +} diff --git a/node_modules/glob/glob.js b/node_modules/glob/glob.js new file mode 100644 index 0000000..58dec0f --- /dev/null +++ b/node_modules/glob/glob.js @@ -0,0 +1,790 @@ +// Approach: +// +// 1. Get the minimatch set +// 2. For each pattern in the set, PROCESS(pattern, false) +// 3. Store matches per-set, then uniq them +// +// PROCESS(pattern, inGlobStar) +// Get the first [n] items from pattern that are all strings +// Join these together. This is PREFIX. +// If there is no more remaining, then stat(PREFIX) and +// add to matches if it succeeds. END. +// +// If inGlobStar and PREFIX is symlink and points to dir +// set ENTRIES = [] +// else readdir(PREFIX) as ENTRIES +// If fail, END +// +// with ENTRIES +// If pattern[n] is GLOBSTAR +// // handle the case where the globstar match is empty +// // by pruning it out, and testing the resulting pattern +// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) +// // handle other cases. +// for ENTRY in ENTRIES (not dotfiles) +// // attach globstar + tail onto the entry +// // Mark that this entry is a globstar match +// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) +// +// else // not globstar +// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) +// Test ENTRY against pattern[n] +// If fails, continue +// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) +// +// Caveat: +// Cache all stats and readdirs results to minimize syscall. Since all +// we ever care about is existence and directory-ness, we can just keep +// `true` for files, and [children,...] for directories, or `false` for +// things that don't exist. + +module.exports = glob + +var fs = require('fs') +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var inherits = require('inherits') +var EE = require('events').EventEmitter +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var globSync = require('./sync.js') +var common = require('./common.js') +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var inflight = require('inflight') +var util = require('util') +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +var once = require('once') + +function glob (pattern, options, cb) { + if (typeof options === 'function') cb = options, options = {} + if (!options) options = {} + + if (options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return globSync(pattern, options) + } + + return new Glob(pattern, options, cb) +} + +glob.sync = globSync +var GlobSync = glob.GlobSync = globSync.GlobSync + +// old api surface +glob.glob = glob + +function extend (origin, add) { + if (add === null || typeof add !== 'object') { + return origin + } + + var keys = Object.keys(add) + var i = keys.length + while (i--) { + origin[keys[i]] = add[keys[i]] + } + return origin +} + +glob.hasMagic = function (pattern, options_) { + var options = extend({}, options_) + options.noprocess = true + + var g = new Glob(pattern, options) + var set = g.minimatch.set + + if (!pattern) + return false + + if (set.length > 1) + return true + + for (var j = 0; j < set[0].length; j++) { + if (typeof set[0][j] !== 'string') + return true + } + + return false +} + +glob.Glob = Glob +inherits(Glob, EE) +function Glob (pattern, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + + if (options && options.sync) { + if (cb) + throw new TypeError('callback provided to sync glob') + return new GlobSync(pattern, options) + } + + if (!(this instanceof Glob)) + return new Glob(pattern, options, cb) + + setopts(this, pattern, options) + this._didRealPath = false + + // process each pattern in the minimatch set + var n = this.minimatch.set.length + + // The matches are stored as {: true,...} so that + // duplicates are automagically pruned. + // Later, we do an Object.keys() on these. + // Keep them as a list so we can fill in when nonull is set. + this.matches = new Array(n) + + if (typeof cb === 'function') { + cb = once(cb) + this.on('error', cb) + this.on('end', function (matches) { + cb(null, matches) + }) + } + + var self = this + this._processing = 0 + + this._emitQueue = [] + this._processQueue = [] + this.paused = false + + if (this.noprocess) + return this + + if (n === 0) + return done() + + var sync = true + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false, done) + } + sync = false + + function done () { + --self._processing + if (self._processing <= 0) { + if (sync) { + process.nextTick(function () { + self._finish() + }) + } else { + self._finish() + } + } + } +} + +Glob.prototype._finish = function () { + assert(this instanceof Glob) + if (this.aborted) + return + + if (this.realpath && !this._didRealpath) + return this._realpath() + + common.finish(this) + this.emit('end', this.found) +} + +Glob.prototype._realpath = function () { + if (this._didRealpath) + return + + this._didRealpath = true + + var n = this.matches.length + if (n === 0) + return this._finish() + + var self = this + for (var i = 0; i < this.matches.length; i++) + this._realpathSet(i, next) + + function next () { + if (--n === 0) + self._finish() + } +} + +Glob.prototype._realpathSet = function (index, cb) { + var matchset = this.matches[index] + if (!matchset) + return cb() + + var found = Object.keys(matchset) + var self = this + var n = found.length + + if (n === 0) + return cb() + + var set = this.matches[index] = Object.create(null) + found.forEach(function (p, i) { + // If there's a problem with the stat, then it means that + // one or more of the links in the realpath couldn't be + // resolved. just return the abs value in that case. + p = self._makeAbs(p) + rp.realpath(p, self.realpathCache, function (er, real) { + if (!er) + set[real] = true + else if (er.syscall === 'stat') + set[p] = true + else + self.emit('error', er) // srsly wtf right here + + if (--n === 0) { + self.matches[index] = set + cb() + } + }) + }) +} + +Glob.prototype._mark = function (p) { + return common.mark(this, p) +} + +Glob.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} + +Glob.prototype.abort = function () { + this.aborted = true + this.emit('abort') +} + +Glob.prototype.pause = function () { + if (!this.paused) { + this.paused = true + this.emit('pause') + } +} + +Glob.prototype.resume = function () { + if (this.paused) { + this.emit('resume') + this.paused = false + if (this._emitQueue.length) { + var eq = this._emitQueue.slice(0) + this._emitQueue.length = 0 + for (var i = 0; i < eq.length; i ++) { + var e = eq[i] + this._emitMatch(e[0], e[1]) + } + } + if (this._processQueue.length) { + var pq = this._processQueue.slice(0) + this._processQueue.length = 0 + for (var i = 0; i < pq.length; i ++) { + var p = pq[i] + this._processing-- + this._process(p[0], p[1], p[2], p[3]) + } + } + } +} + +Glob.prototype._process = function (pattern, index, inGlobStar, cb) { + assert(this instanceof Glob) + assert(typeof cb === 'function') + + if (this.aborted) + return + + this._processing++ + if (this.paused) { + this._processQueue.push([pattern, index, inGlobStar, cb]) + return + } + + //console.error('PROCESS %d', this._processing, pattern) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // see if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index, cb) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip _processing + if (childrenIgnored(this, read)) + return cb() + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) +} + +Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + +Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return cb() + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return cb() + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return cb() + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) { + if (prefix !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + this._process([e].concat(remain), index, inGlobStar, cb) + } + cb() +} + +Glob.prototype._emitMatch = function (index, e) { + if (this.aborted) + return + + if (isIgnored(this, e)) + return + + if (this.paused) { + this._emitQueue.push([index, e]) + return + } + + var abs = isAbsolute(e) ? e : this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) + e = abs + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + var st = this.statCache[abs] + if (st) + this.emit('stat', e, st) + + this.emit('match', e) +} + +Glob.prototype._readdirInGlobStar = function (abs, cb) { + if (this.aborted) + return + + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false, cb) + + var lstatkey = 'lstat\0' + abs + var self = this + var lstatcb = inflight(lstatkey, lstatcb_) + + if (lstatcb) + fs.lstat(abs, lstatcb) + + function lstatcb_ (er, lstat) { + if (er && er.code === 'ENOENT') + return cb() + + var isSym = lstat && lstat.isSymbolicLink() + self.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) { + self.cache[abs] = 'FILE' + cb() + } else + self._readdir(abs, false, cb) + } +} + +Glob.prototype._readdir = function (abs, inGlobStar, cb) { + if (this.aborted) + return + + cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) + if (!cb) + return + + //console.error('RD %j %j', +inGlobStar, abs) + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs, cb) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return cb() + + if (Array.isArray(c)) + return cb(null, c) + } + + var self = this + fs.readdir(abs, readdirCb(this, abs, cb)) +} + +function readdirCb (self, abs, cb) { + return function (er, entries) { + if (er) + self._readdirError(abs, er, cb) + else + self._readdirEntries(abs, entries, cb) + } +} + +Glob.prototype._readdirEntries = function (abs, entries, cb) { + if (this.aborted) + return + + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + return cb(null, entries) +} + +Glob.prototype._readdirError = function (f, er, cb) { + if (this.aborted) + return + + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + this.emit('error', error) + this.abort() + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) { + this.emit('error', er) + // If the error is handled, then we abort + // if not, we threw out of here + this.abort() + } + if (!this.silent) + console.error('glob error', er) + break + } + + return cb() +} + +Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { + var self = this + this._readdir(abs, inGlobStar, function (er, entries) { + self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + }) +} + + +Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + //console.error('pgs2', prefix, remain[0], entries) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return cb() + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false, cb) + + var isSym = this.symlinks[abs] + var len = entries.length + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return cb() + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true, cb) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true, cb) + } + + cb() +} + +Glob.prototype._processSimple = function (prefix, index, cb) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var self = this + this._stat(prefix, function (er, exists) { + self._processSimple2(prefix, index, er, exists, cb) + }) +} +Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + + //console.error('ps2', prefix, exists) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return cb() + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) + cb() +} + +// Returns either 'DIR', 'FILE', or false +Glob.prototype._stat = function (f, cb) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return cb() + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return cb(null, c) + + if (needDir && c === 'FILE') + return cb() + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (stat !== undefined) { + if (stat === false) + return cb(null, stat) + else { + var type = stat.isDirectory() ? 'DIR' : 'FILE' + if (needDir && type === 'FILE') + return cb() + else + return cb(null, type, stat) + } + } + + var self = this + var statcb = inflight('stat\0' + abs, lstatcb_) + if (statcb) + fs.lstat(abs, statcb) + + function lstatcb_ (er, lstat) { + if (lstat && lstat.isSymbolicLink()) { + // If it's a symlink, then treat it as the target, unless + // the target does not exist, then treat it as a file. + return fs.stat(abs, function (er, stat) { + if (er) + self._stat2(f, abs, null, lstat, cb) + else + self._stat2(f, abs, er, stat, cb) + }) + } else { + self._stat2(f, abs, er, lstat, cb) + } + } +} + +Glob.prototype._stat2 = function (f, abs, er, stat, cb) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return cb() + } + + var needDir = f.slice(-1) === '/' + this.statCache[abs] = stat + + if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) + return cb(null, false, stat) + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return cb() + + return cb(null, c, stat) +} diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json new file mode 100644 index 0000000..ce17b1b --- /dev/null +++ b/node_modules/glob/package.json @@ -0,0 +1,83 @@ +{ + "_args": [ + [ + "glob@7.1.6", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "glob@7.1.6", + "_id": "glob@7.1.6", + "_inBundle": false, + "_integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "_location": "/glob", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "glob@7.1.6", + "name": "glob", + "escapedName": "glob", + "rawSpec": "7.1.6", + "saveSpec": null, + "fetchSpec": "7.1.6" + }, + "_requiredBy": [ + "/rimraf" + ], + "_resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", + "_spec": "7.1.6", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/node-glob/issues" + }, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "description": "a little globber", + "devDependencies": { + "mkdirp": "0", + "rimraf": "^2.2.8", + "tap": "^12.0.1", + "tick": "0.0.6" + }, + "engines": { + "node": "*" + }, + "files": [ + "glob.js", + "sync.js", + "common.js" + ], + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "homepage": "https://github.com/isaacs/node-glob#readme", + "license": "ISC", + "main": "glob.js", + "name": "glob", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-glob.git" + }, + "scripts": { + "bench": "bash benchmark.sh", + "benchclean": "node benchclean.js", + "prepublish": "npm run benchclean", + "prof": "bash prof.sh && cat profile.txt", + "profclean": "rm -f v8.log profile.txt", + "test": "tap test/*.js --cov", + "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js" + }, + "version": "7.1.6" +} diff --git a/node_modules/glob/sync.js b/node_modules/glob/sync.js new file mode 100644 index 0000000..c952134 --- /dev/null +++ b/node_modules/glob/sync.js @@ -0,0 +1,486 @@ +module.exports = globSync +globSync.GlobSync = GlobSync + +var fs = require('fs') +var rp = require('fs.realpath') +var minimatch = require('minimatch') +var Minimatch = minimatch.Minimatch +var Glob = require('./glob.js').Glob +var util = require('util') +var path = require('path') +var assert = require('assert') +var isAbsolute = require('path-is-absolute') +var common = require('./common.js') +var alphasort = common.alphasort +var alphasorti = common.alphasorti +var setopts = common.setopts +var ownProp = common.ownProp +var childrenIgnored = common.childrenIgnored +var isIgnored = common.isIgnored + +function globSync (pattern, options) { + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + return new GlobSync(pattern, options).found +} + +function GlobSync (pattern, options) { + if (!pattern) + throw new Error('must provide pattern') + + if (typeof options === 'function' || arguments.length === 3) + throw new TypeError('callback provided to sync glob\n'+ + 'See: https://github.com/isaacs/node-glob/issues/167') + + if (!(this instanceof GlobSync)) + return new GlobSync(pattern, options) + + setopts(this, pattern, options) + + if (this.noprocess) + return this + + var n = this.minimatch.set.length + this.matches = new Array(n) + for (var i = 0; i < n; i ++) { + this._process(this.minimatch.set[i], i, false) + } + this._finish() +} + +GlobSync.prototype._finish = function () { + assert(this instanceof GlobSync) + if (this.realpath) { + var self = this + this.matches.forEach(function (matchset, index) { + var set = self.matches[index] = Object.create(null) + for (var p in matchset) { + try { + p = self._makeAbs(p) + var real = rp.realpathSync(p, self.realpathCache) + set[real] = true + } catch (er) { + if (er.syscall === 'stat') + set[self._makeAbs(p)] = true + else + throw er + } + } + }) + } + common.finish(this) +} + + +GlobSync.prototype._process = function (pattern, index, inGlobStar) { + assert(this instanceof GlobSync) + + // Get the first [n] parts of pattern that are all strings. + var n = 0 + while (typeof pattern[n] === 'string') { + n ++ + } + // now n is the index of the first one that is *not* a string. + + // See if there's anything else + var prefix + switch (n) { + // if not, then this is rather simple + case pattern.length: + this._processSimple(pattern.join('/'), index) + return + + case 0: + // pattern *starts* with some non-trivial item. + // going to readdir(cwd), but not include the prefix in matches. + prefix = null + break + + default: + // pattern has some string bits in the front. + // whatever it starts with, whether that's 'absolute' like /foo/bar, + // or 'relative' like '../baz' + prefix = pattern.slice(0, n).join('/') + break + } + + var remain = pattern.slice(n) + + // get the list of entries. + var read + if (prefix === null) + read = '.' + else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + if (!prefix || !isAbsolute(prefix)) + prefix = '/' + prefix + read = prefix + } else + read = prefix + + var abs = this._makeAbs(read) + + //if ignored, skip processing + if (childrenIgnored(this, read)) + return + + var isGlobStar = remain[0] === minimatch.GLOBSTAR + if (isGlobStar) + this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) + else + this._processReaddir(prefix, read, abs, remain, index, inGlobStar) +} + + +GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { + var entries = this._readdir(abs, inGlobStar) + + // if the abs isn't a dir, then nothing can match! + if (!entries) + return + + // It will only match dot entries if it starts with a dot, or if + // dot is set. Stuff like @(.foo|.bar) isn't allowed. + var pn = remain[0] + var negate = !!this.minimatch.negate + var rawGlob = pn._glob + var dotOk = this.dot || rawGlob.charAt(0) === '.' + + var matchedEntries = [] + for (var i = 0; i < entries.length; i++) { + var e = entries[i] + if (e.charAt(0) !== '.' || dotOk) { + var m + if (negate && !prefix) { + m = !e.match(pn) + } else { + m = e.match(pn) + } + if (m) + matchedEntries.push(e) + } + } + + var len = matchedEntries.length + // If there are no matched entries, then nothing matches. + if (len === 0) + return + + // if this is the last remaining pattern bit, then no need for + // an additional stat *unless* the user has specified mark or + // stat explicitly. We know they exist, since readdir returned + // them. + + if (remain.length === 1 && !this.mark && !this.stat) { + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + if (prefix) { + if (prefix.slice(-1) !== '/') + e = prefix + '/' + e + else + e = prefix + e + } + + if (e.charAt(0) === '/' && !this.nomount) { + e = path.join(this.root, e) + } + this._emitMatch(index, e) + } + // This was the last one, and no stats were needed + return + } + + // now test all matched entries as stand-ins for that part + // of the pattern. + remain.shift() + for (var i = 0; i < len; i ++) { + var e = matchedEntries[i] + var newPattern + if (prefix) + newPattern = [prefix, e] + else + newPattern = [e] + this._process(newPattern.concat(remain), index, inGlobStar) + } +} + + +GlobSync.prototype._emitMatch = function (index, e) { + if (isIgnored(this, e)) + return + + var abs = this._makeAbs(e) + + if (this.mark) + e = this._mark(e) + + if (this.absolute) { + e = abs + } + + if (this.matches[index][e]) + return + + if (this.nodir) { + var c = this.cache[abs] + if (c === 'DIR' || Array.isArray(c)) + return + } + + this.matches[index][e] = true + + if (this.stat) + this._stat(e) +} + + +GlobSync.prototype._readdirInGlobStar = function (abs) { + // follow all symlinked directories forever + // just proceed as if this is a non-globstar situation + if (this.follow) + return this._readdir(abs, false) + + var entries + var lstat + var stat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er.code === 'ENOENT') { + // lstat failed, doesn't exist + return null + } + } + + var isSym = lstat && lstat.isSymbolicLink() + this.symlinks[abs] = isSym + + // If it's not a symlink or a dir, then it's definitely a regular file. + // don't bother doing a readdir in that case. + if (!isSym && lstat && !lstat.isDirectory()) + this.cache[abs] = 'FILE' + else + entries = this._readdir(abs, false) + + return entries +} + +GlobSync.prototype._readdir = function (abs, inGlobStar) { + var entries + + if (inGlobStar && !ownProp(this.symlinks, abs)) + return this._readdirInGlobStar(abs) + + if (ownProp(this.cache, abs)) { + var c = this.cache[abs] + if (!c || c === 'FILE') + return null + + if (Array.isArray(c)) + return c + } + + try { + return this._readdirEntries(abs, fs.readdirSync(abs)) + } catch (er) { + this._readdirError(abs, er) + return null + } +} + +GlobSync.prototype._readdirEntries = function (abs, entries) { + // if we haven't asked to stat everything, then just + // assume that everything in there exists, so we can avoid + // having to stat it a second time. + if (!this.mark && !this.stat) { + for (var i = 0; i < entries.length; i ++) { + var e = entries[i] + if (abs === '/') + e = abs + e + else + e = abs + '/' + e + this.cache[e] = true + } + } + + this.cache[abs] = entries + + // mark and cache dir-ness + return entries +} + +GlobSync.prototype._readdirError = function (f, er) { + // handle errors, and cache the information + switch (er.code) { + case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 + case 'ENOTDIR': // totally normal. means it *does* exist. + var abs = this._makeAbs(f) + this.cache[abs] = 'FILE' + if (abs === this.cwdAbs) { + var error = new Error(er.code + ' invalid cwd ' + this.cwd) + error.path = this.cwd + error.code = er.code + throw error + } + break + + case 'ENOENT': // not terribly unusual + case 'ELOOP': + case 'ENAMETOOLONG': + case 'UNKNOWN': + this.cache[this._makeAbs(f)] = false + break + + default: // some unusual error. Treat as failure. + this.cache[this._makeAbs(f)] = false + if (this.strict) + throw er + if (!this.silent) + console.error('glob error', er) + break + } +} + +GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { + + var entries = this._readdir(abs, inGlobStar) + + // no entries means not a dir, so it can never have matches + // foo.txt/** doesn't match foo.txt + if (!entries) + return + + // test without the globstar, and with every child both below + // and replacing the globstar. + var remainWithoutGlobStar = remain.slice(1) + var gspref = prefix ? [ prefix ] : [] + var noGlobStar = gspref.concat(remainWithoutGlobStar) + + // the noGlobStar pattern exits the inGlobStar state + this._process(noGlobStar, index, false) + + var len = entries.length + var isSym = this.symlinks[abs] + + // If it's a symlink, and we're in a globstar, then stop + if (isSym && inGlobStar) + return + + for (var i = 0; i < len; i++) { + var e = entries[i] + if (e.charAt(0) === '.' && !this.dot) + continue + + // these two cases enter the inGlobStar state + var instead = gspref.concat(entries[i], remainWithoutGlobStar) + this._process(instead, index, true) + + var below = gspref.concat(entries[i], remain) + this._process(below, index, true) + } +} + +GlobSync.prototype._processSimple = function (prefix, index) { + // XXX review this. Shouldn't it be doing the mounting etc + // before doing stat? kinda weird? + var exists = this._stat(prefix) + + if (!this.matches[index]) + this.matches[index] = Object.create(null) + + // If it doesn't exist, then just mark the lack of results + if (!exists) + return + + if (prefix && isAbsolute(prefix) && !this.nomount) { + var trail = /[\/\\]$/.test(prefix) + if (prefix.charAt(0) === '/') { + prefix = path.join(this.root, prefix) + } else { + prefix = path.resolve(this.root, prefix) + if (trail) + prefix += '/' + } + } + + if (process.platform === 'win32') + prefix = prefix.replace(/\\/g, '/') + + // Mark this as a match + this._emitMatch(index, prefix) +} + +// Returns either 'DIR', 'FILE', or false +GlobSync.prototype._stat = function (f) { + var abs = this._makeAbs(f) + var needDir = f.slice(-1) === '/' + + if (f.length > this.maxLength) + return false + + if (!this.stat && ownProp(this.cache, abs)) { + var c = this.cache[abs] + + if (Array.isArray(c)) + c = 'DIR' + + // It exists, but maybe not how we need it + if (!needDir || c === 'DIR') + return c + + if (needDir && c === 'FILE') + return false + + // otherwise we have to stat, because maybe c=true + // if we know it exists, but not what it is. + } + + var exists + var stat = this.statCache[abs] + if (!stat) { + var lstat + try { + lstat = fs.lstatSync(abs) + } catch (er) { + if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { + this.statCache[abs] = false + return false + } + } + + if (lstat && lstat.isSymbolicLink()) { + try { + stat = fs.statSync(abs) + } catch (er) { + stat = lstat + } + } else { + stat = lstat + } + } + + this.statCache[abs] = stat + + var c = true + if (stat) + c = stat.isDirectory() ? 'DIR' : 'FILE' + + this.cache[abs] = this.cache[abs] || c + + if (needDir && c === 'FILE') + return false + + return c +} + +GlobSync.prototype._mark = function (p) { + return common.mark(this, p) +} + +GlobSync.prototype._makeAbs = function (f) { + return common.makeAbs(this, f) +} diff --git a/node_modules/graceful-fs/LICENSE b/node_modules/graceful-fs/LICENSE new file mode 100644 index 0000000..9d2c803 --- /dev/null +++ b/node_modules/graceful-fs/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter, Ben Noordhuis, and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/graceful-fs/README.md b/node_modules/graceful-fs/README.md new file mode 100644 index 0000000..5273a50 --- /dev/null +++ b/node_modules/graceful-fs/README.md @@ -0,0 +1,133 @@ +# graceful-fs + +graceful-fs functions as a drop-in replacement for the fs module, +making various improvements. + +The improvements are meant to normalize behavior across different +platforms and environments, and to make filesystem access more +resilient to errors. + +## Improvements over [fs module](https://nodejs.org/api/fs.html) + +* Queues up `open` and `readdir` calls, and retries them once + something closes if there is an EMFILE error from too many file + descriptors. +* fixes `lchmod` for Node versions prior to 0.6.2. +* implements `fs.lutimes` if possible. Otherwise it becomes a noop. +* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or + `lchown` if the user isn't root. +* makes `lchmod` and `lchown` become noops, if not available. +* retries reading a file if `read` results in EAGAIN error. + +On Windows, it retries renaming a file for up to one second if `EACCESS` +or `EPERM` error occurs, likely because antivirus software has locked +the directory. + +## USAGE + +```javascript +// use just like fs +var fs = require('graceful-fs') + +// now go and do stuff with it... +fs.readFileSync('some-file-or-whatever') +``` + +## Global Patching + +If you want to patch the global fs module (or any other fs-like +module) you can do this: + +```javascript +// Make sure to read the caveat below. +var realFs = require('fs') +var gracefulFs = require('graceful-fs') +gracefulFs.gracefulify(realFs) +``` + +This should only ever be done at the top-level application layer, in +order to delay on EMFILE errors from any fs-using dependencies. You +should **not** do this in a library, because it can cause unexpected +delays in other parts of the program. + +## Changes + +This module is fairly stable at this point, and used by a lot of +things. That being said, because it implements a subtle behavior +change in a core part of the node API, even modest changes can be +extremely breaking, and the versioning is thus biased towards +bumping the major when in doubt. + +The main change between major versions has been switching between +providing a fully-patched `fs` module vs monkey-patching the node core +builtin, and the approach by which a non-monkey-patched `fs` was +created. + +The goal is to trade `EMFILE` errors for slower fs operations. So, if +you try to open a zillion files, rather than crashing, `open` +operations will be queued up and wait for something else to `close`. + +There are advantages to each approach. Monkey-patching the fs means +that no `EMFILE` errors can possibly occur anywhere in your +application, because everything is using the same core `fs` module, +which is patched. However, it can also obviously cause undesirable +side-effects, especially if the module is loaded multiple times. + +Implementing a separate-but-identical patched `fs` module is more +surgical (and doesn't run the risk of patching multiple times), but +also imposes the challenge of keeping in sync with the core module. + +The current approach loads the `fs` module, and then creates a +lookalike object that has all the same methods, except a few that are +patched. It is safe to use in all versions of Node from 0.8 through +7.0. + +### v4 + +* Do not monkey-patch the fs module. This module may now be used as a + drop-in dep, and users can opt into monkey-patching the fs builtin + if their app requires it. + +### v3 + +* Monkey-patch fs, because the eval approach no longer works on recent + node. +* fixed possible type-error throw if rename fails on windows +* verify that we *never* get EMFILE errors +* Ignore ENOSYS from chmod/chown +* clarify that graceful-fs must be used as a drop-in + +### v2.1.0 + +* Use eval rather than monkey-patching fs. +* readdir: Always sort the results +* win32: requeue a file if error has an OK status + +### v2.0 + +* A return to monkey patching +* wrap process.cwd + +### v1.1 + +* wrap readFile +* Wrap fs.writeFile. +* readdir protection +* Don't clobber the fs builtin +* Handle fs.read EAGAIN errors by trying again +* Expose the curOpen counter +* No-op lchown/lchmod if not implemented +* fs.rename patch only for win32 +* Patch fs.rename to handle AV software on Windows +* Close #4 Chown should not fail on einval or eperm if non-root +* Fix isaacs/fstream#1 Only wrap fs one time +* Fix #3 Start at 1024 max files, then back off on EMFILE +* lutimes that doens't blow up on Linux +* A full on-rewrite using a queue instead of just swallowing the EMFILE error +* Wrap Read/Write streams as well + +### 1.0 + +* Update engines for node 0.6 +* Be lstat-graceful on Windows +* first diff --git a/node_modules/graceful-fs/clone.js b/node_modules/graceful-fs/clone.js new file mode 100644 index 0000000..028356c --- /dev/null +++ b/node_modules/graceful-fs/clone.js @@ -0,0 +1,19 @@ +'use strict' + +module.exports = clone + +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: obj.__proto__ } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy +} diff --git a/node_modules/graceful-fs/graceful-fs.js b/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000..de3df47 --- /dev/null +++ b/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,354 @@ +var fs = require('fs') +var polyfills = require('./polyfills.js') +var legacy = require('./legacy-streams.js') +var clone = require('./clone.js') + +var util = require('util') + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} + +function noop () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } + +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + retry() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } + + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) + + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + retry() + } + + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + require('assert').equal(fs[gracefulQueue].length, 0) + }) + } +} + +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} + +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} + +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$readFile(path, options, cb) + + function go$readFile (path, options, cb) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + var args = [path] + if (typeof options !== 'function') { + args.push(options) + } else { + cb = options + } + args.push(go$readdir$cb) + + return go$readdir(args) + + function go$readdir$cb (err, files) { + if (files && files.sort) + files.sort() + + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [args]]) + + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + } + } + + function go$readdir (args) { + return fs$readdir.apply(fs, args) + } + + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } + + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } + + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) + + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } + + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } + + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } + + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb]]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + retry() + } + }) + } + } + + return fs +} + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) +} + +function retry () { + var elem = fs[gracefulQueue].shift() + if (elem) { + debug('RETRY', elem[0].name, elem[1]) + elem[0].apply(null, elem[1]) + } +} diff --git a/node_modules/graceful-fs/legacy-streams.js b/node_modules/graceful-fs/legacy-streams.js new file mode 100644 index 0000000..d617b50 --- /dev/null +++ b/node_modules/graceful-fs/legacy-streams.js @@ -0,0 +1,118 @@ +var Stream = require('stream').Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; + } + + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} diff --git a/node_modules/graceful-fs/package.json b/node_modules/graceful-fs/package.json new file mode 100644 index 0000000..1041d31 --- /dev/null +++ b/node_modules/graceful-fs/package.json @@ -0,0 +1,84 @@ +{ + "_args": [ + [ + "graceful-fs@4.2.4", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "graceful-fs@4.2.4", + "_id": "graceful-fs@4.2.4", + "_inBundle": false, + "_integrity": "sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw==", + "_location": "/graceful-fs", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "graceful-fs@4.2.4", + "name": "graceful-fs", + "escapedName": "graceful-fs", + "rawSpec": "4.2.4", + "saveSpec": null, + "fetchSpec": "4.2.4" + }, + "_requiredBy": [ + "/fs-extra", + "/jsonfile" + ], + "_resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.4.tgz", + "_spec": "4.2.4", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "bugs": { + "url": "https://github.com/isaacs/node-graceful-fs/issues" + }, + "dependencies": {}, + "description": "A drop-in replacement for fs, making various improvements.", + "devDependencies": { + "import-fresh": "^2.0.0", + "mkdirp": "^0.5.0", + "rimraf": "^2.2.8", + "tap": "^12.7.0" + }, + "directories": { + "test": "test" + }, + "files": [ + "fs.js", + "graceful-fs.js", + "legacy-streams.js", + "polyfills.js", + "clone.js" + ], + "homepage": "https://github.com/isaacs/node-graceful-fs#readme", + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "ISC", + "main": "graceful-fs.js", + "name": "graceful-fs", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/node-graceful-fs.git" + }, + "scripts": { + "postpublish": "git push origin --follow-tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "node test.js | tap -" + }, + "version": "4.2.4" +} diff --git a/node_modules/graceful-fs/polyfills.js b/node_modules/graceful-fs/polyfills.js new file mode 100644 index 0000000..a5808d2 --- /dev/null +++ b/node_modules/graceful-fs/polyfills.js @@ -0,0 +1,342 @@ +var constants = require('constants') + +var origCwd = process.cwd +var cwd = null + +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} + +var chdir = process.chdir +process.chdir = function(d) { + cwd = null + chdir.call(process, d) +} + +module.exports = patch + +function patch (fs) { + // (re-)implement some things that are known busted or missing. + + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } + + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } + + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) + + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) + + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) + + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) + + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } + + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + }})(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + + // This ensures `util.promisify` works as it does for native `fs.read`. + read.__proto__ = fs$read + return read + })(fs.read) + + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } + + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } + + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; + } + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } +} diff --git a/node_modules/inflight/LICENSE b/node_modules/inflight/LICENSE new file mode 100644 index 0000000..05eeeb8 --- /dev/null +++ b/node_modules/inflight/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +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/inflight/README.md b/node_modules/inflight/README.md new file mode 100644 index 0000000..6dc8929 --- /dev/null +++ b/node_modules/inflight/README.md @@ -0,0 +1,37 @@ +# inflight + +Add callbacks to requests in flight to avoid async duplication + +## USAGE + +```javascript +var inflight = require('inflight') + +// some request that does some stuff +function req(key, callback) { + // key is any random string. like a url or filename or whatever. + // + // will return either a falsey value, indicating that the + // request for this key is already in flight, or a new callback + // which when called will call all callbacks passed to inflightk + // with the same key + callback = inflight(key, callback) + + // If we got a falsey value back, then there's already a req going + if (!callback) return + + // this is where you'd fetch the url or whatever + // callback is also once()-ified, so it can safely be assigned + // to multiple events etc. First call wins. + setTimeout(function() { + callback(null, key) + }, 100) +} + +// only assigns a single setTimeout +// when it dings, all cbs get called +req('foo', cb1) +req('foo', cb2) +req('foo', cb3) +req('foo', cb4) +``` diff --git a/node_modules/inflight/inflight.js b/node_modules/inflight/inflight.js new file mode 100644 index 0000000..48202b3 --- /dev/null +++ b/node_modules/inflight/inflight.js @@ -0,0 +1,54 @@ +var wrappy = require('wrappy') +var reqs = Object.create(null) +var once = require('once') + +module.exports = wrappy(inflight) + +function inflight (key, cb) { + if (reqs[key]) { + reqs[key].push(cb) + return null + } else { + reqs[key] = [cb] + return makeres(key) + } +} + +function makeres (key) { + return once(function RES () { + var cbs = reqs[key] + var len = cbs.length + var args = slice(arguments) + + // XXX It's somewhat ambiguous whether a new callback added in this + // pass should be queued for later execution if something in the + // list of callbacks throws, or if it should just be discarded. + // However, it's such an edge case that it hardly matters, and either + // choice is likely as surprising as the other. + // As it happens, we do go ahead and schedule it for later execution. + try { + for (var i = 0; i < len; i++) { + cbs[i].apply(null, args) + } + } finally { + if (cbs.length > len) { + // added more in the interim. + // de-zalgo, just in case, but don't call again. + cbs.splice(0, len) + process.nextTick(function () { + RES.apply(null, args) + }) + } else { + delete reqs[key] + } + } + }) +} + +function slice (args) { + var length = args.length + var array = [] + + for (var i = 0; i < length; i++) array[i] = args[i] + return array +} diff --git a/node_modules/inflight/package.json b/node_modules/inflight/package.json new file mode 100644 index 0000000..ae21101 --- /dev/null +++ b/node_modules/inflight/package.json @@ -0,0 +1,62 @@ +{ + "_args": [ + [ + "inflight@1.0.6", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "inflight@1.0.6", + "_id": "inflight@1.0.6", + "_inBundle": false, + "_integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", + "_location": "/inflight", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "inflight@1.0.6", + "name": "inflight", + "escapedName": "inflight", + "rawSpec": "1.0.6", + "saveSpec": null, + "fetchSpec": "1.0.6" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "_spec": "1.0.6", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/inflight/issues" + }, + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + }, + "description": "Add callbacks to requests in flight to avoid async duplication", + "devDependencies": { + "tap": "^7.1.2" + }, + "files": [ + "inflight.js" + ], + "homepage": "https://github.com/isaacs/inflight", + "license": "ISC", + "main": "inflight.js", + "name": "inflight", + "repository": { + "type": "git", + "url": "git+https://github.com/npm/inflight.git" + }, + "scripts": { + "test": "tap test.js --100" + }, + "version": "1.0.6" +} diff --git a/node_modules/inherits/LICENSE b/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +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/inherits/README.md b/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/node_modules/inherits/inherits.js b/node_modules/inherits/inherits.js new file mode 100644 index 0000000..f71f2d9 --- /dev/null +++ b/node_modules/inherits/inherits.js @@ -0,0 +1,9 @@ +try { + var util = require('util'); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = require('./inherits_browser.js'); +} diff --git a/node_modules/inherits/inherits_browser.js b/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..86bbb3d --- /dev/null +++ b/node_modules/inherits/inherits_browser.js @@ -0,0 +1,27 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (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) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} diff --git a/node_modules/inherits/package.json b/node_modules/inherits/package.json new file mode 100644 index 0000000..42d4cd0 --- /dev/null +++ b/node_modules/inherits/package.json @@ -0,0 +1,67 @@ +{ + "_args": [ + [ + "inherits@2.0.4", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "inherits@2.0.4", + "_id": "inherits@2.0.4", + "_inBundle": false, + "_integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "_location": "/inherits", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "inherits@2.0.4", + "name": "inherits", + "escapedName": "inherits", + "rawSpec": "2.0.4", + "saveSpec": null, + "fetchSpec": "2.0.4" + }, + "_requiredBy": [ + "/glob", + "/readable-stream", + "/string-to-stream" + ], + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "_spec": "2.0.4", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "browser": "./inherits_browser.js", + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "devDependencies": { + "tap": "^14.2.4" + }, + "files": [ + "inherits.js", + "inherits_browser.js" + ], + "homepage": "https://github.com/isaacs/inherits#readme", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "license": "ISC", + "main": "./inherits.js", + "name": "inherits", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "scripts": { + "test": "tap" + }, + "version": "2.0.4" +} diff --git a/node_modules/isarray/.npmignore b/node_modules/isarray/.npmignore new file mode 100644 index 0000000..3c3629e --- /dev/null +++ b/node_modules/isarray/.npmignore @@ -0,0 +1 @@ +node_modules diff --git a/node_modules/isarray/.travis.yml b/node_modules/isarray/.travis.yml new file mode 100644 index 0000000..cc4dba2 --- /dev/null +++ b/node_modules/isarray/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.8" + - "0.10" diff --git a/node_modules/isarray/Makefile b/node_modules/isarray/Makefile new file mode 100644 index 0000000..787d56e --- /dev/null +++ b/node_modules/isarray/Makefile @@ -0,0 +1,6 @@ + +test: + @node_modules/.bin/tape test.js + +.PHONY: test + diff --git a/node_modules/isarray/README.md b/node_modules/isarray/README.md new file mode 100644 index 0000000..16d2c59 --- /dev/null +++ b/node_modules/isarray/README.md @@ -0,0 +1,60 @@ + +# isarray + +`Array#isArray` for older browsers. + +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray) +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray) + +[![browser support](https://ci.testling.com/juliangruber/isarray.png) +](https://ci.testling.com/juliangruber/isarray) + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.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/isarray/component.json b/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/node_modules/isarray/index.js b/node_modules/isarray/index.js new file mode 100644 index 0000000..a57f634 --- /dev/null +++ b/node_modules/isarray/index.js @@ -0,0 +1,5 @@ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; diff --git a/node_modules/isarray/package.json b/node_modules/isarray/package.json new file mode 100644 index 0000000..8d47569 --- /dev/null +++ b/node_modules/isarray/package.json @@ -0,0 +1,77 @@ +{ + "_args": [ + [ + "isarray@1.0.0", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "isarray@1.0.0", + "_id": "isarray@1.0.0", + "_inBundle": false, + "_integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", + "_location": "/isarray", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "isarray@1.0.0", + "name": "isarray", + "escapedName": "isarray", + "rawSpec": "1.0.0", + "saveSpec": null, + "fetchSpec": "1.0.0" + }, + "_requiredBy": [ + "/readable-stream" + ], + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "_spec": "1.0.0", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "dependencies": {}, + "description": "Array#isArray for older browsers", + "devDependencies": { + "tape": "~2.13.4" + }, + "homepage": "https://github.com/juliangruber/isarray", + "keywords": [ + "browser", + "isarray", + "array" + ], + "license": "MIT", + "main": "index.js", + "name": "isarray", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "scripts": { + "test": "tape test.js" + }, + "testling": { + "files": "test.js", + "browsers": [ + "ie/8..latest", + "firefox/17..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", + "android-browser/4.2..latest" + ] + }, + "version": "1.0.0" +} diff --git a/node_modules/isarray/test.js b/node_modules/isarray/test.js new file mode 100644 index 0000000..e0c3444 --- /dev/null +++ b/node_modules/isarray/test.js @@ -0,0 +1,20 @@ +var isArray = require('./'); +var test = require('tape'); + +test('is array', function(t){ + t.ok(isArray([])); + t.notOk(isArray({})); + t.notOk(isArray(null)); + t.notOk(isArray(false)); + + var obj = {}; + obj[0] = true; + t.notOk(isArray(obj)); + + var arr = []; + arr.foo = 'bar'; + t.ok(isArray(arr)); + + t.end(); +}); + diff --git a/node_modules/jsonfile/.npmignore b/node_modules/jsonfile/.npmignore new file mode 100644 index 0000000..cefaa67 --- /dev/null +++ b/node_modules/jsonfile/.npmignore @@ -0,0 +1,2 @@ +test/ +.travis.yml \ No newline at end of file diff --git a/node_modules/jsonfile/CHANGELOG.md b/node_modules/jsonfile/CHANGELOG.md new file mode 100644 index 0000000..66fcbb4 --- /dev/null +++ b/node_modules/jsonfile/CHANGELOG.md @@ -0,0 +1,126 @@ +2.4.0 / 2016-09-15 +------------------ +### Changed +- added optional support for `graceful-fs` [#62] + +2.3.1 / 2016-05-13 +------------------ +- fix to support BOM. [#45][#45] + +2.3.0 / 2016-04-16 +------------------ +- add `throws` to `readFile()`. See [#39][#39] +- add support for any arbitrary `fs` module. Useful with [mock-fs](https://www.npmjs.com/package/mock-fs) + +2.2.3 / 2015-10-14 +------------------ +- include file name in parse error. See: https://github.com/jprichardson/node-jsonfile/pull/34 + +2.2.2 / 2015-09-16 +------------------ +- split out tests into separate files +- fixed `throws` when set to `true` in `readFileSync()`. See: https://github.com/jprichardson/node-jsonfile/pull/33 + +2.2.1 / 2015-06-25 +------------------ +- fixed regression when passing in string as encoding for options in `writeFile()` and `writeFileSync()`. See: https://github.com/jprichardson/node-jsonfile/issues/28 + +2.2.0 / 2015-06-25 +------------------ +- added `options.spaces` to `writeFile()` and `writeFileSync()` + +2.1.2 / 2015-06-22 +------------------ +- fixed if passed `readFileSync(file, 'utf8')`. See: https://github.com/jprichardson/node-jsonfile/issues/25 + +2.1.1 / 2015-06-19 +------------------ +- fixed regressions if `null` is passed for options. See: https://github.com/jprichardson/node-jsonfile/issues/24 + +2.1.0 / 2015-06-19 +------------------ +- cleanup: JavaScript Standard Style, rename files, dropped terst for assert +- methods now support JSON revivers/replacers + +2.0.1 / 2015-05-24 +------------------ +- update license attribute https://github.com/jprichardson/node-jsonfile/pull/21 + +2.0.0 / 2014-07-28 +------------------ +* added `\n` to end of file on write. [#14](https://github.com/jprichardson/node-jsonfile/pull/14) +* added `options.throws` to `readFileSync()` +* dropped support for Node v0.8 + +1.2.0 / 2014-06-29 +------------------ +* removed semicolons +* bugfix: passed `options` to `fs.readFile` and `fs.readFileSync`. This technically changes behavior, but +changes it according to docs. [#12][#12] + +1.1.1 / 2013-11-11 +------------------ +* fixed catching of callback bug (ffissore / #5) + +1.1.0 / 2013-10-11 +------------------ +* added `options` param to methods, (seanodell / #4) + +1.0.1 / 2013-09-05 +------------------ +* removed `homepage` field from package.json to remove NPM warning + +1.0.0 / 2013-06-28 +------------------ +* added `.npmignore`, #1 +* changed spacing default from `4` to `2` to follow Node conventions + +0.0.1 / 2012-09-10 +------------------ +* Initial release. + +[#45]: https://github.com/jprichardson/node-jsonfile/issues/45 "Reading of UTF8-encoded (w/ BOM) files fails" +[#44]: https://github.com/jprichardson/node-jsonfile/issues/44 "Extra characters in written file" +[#43]: https://github.com/jprichardson/node-jsonfile/issues/43 "Prettyfy json when written to file" +[#42]: https://github.com/jprichardson/node-jsonfile/pull/42 "Moved fs.readFileSync within the try/catch" +[#41]: https://github.com/jprichardson/node-jsonfile/issues/41 "Linux: Hidden file not working" +[#40]: https://github.com/jprichardson/node-jsonfile/issues/40 "autocreate folder doesnt work from Path-value" +[#39]: https://github.com/jprichardson/node-jsonfile/pull/39 "Add `throws` option for readFile (async)" +[#38]: https://github.com/jprichardson/node-jsonfile/pull/38 "Update README.md writeFile[Sync] signature" +[#37]: https://github.com/jprichardson/node-jsonfile/pull/37 "support append file" +[#36]: https://github.com/jprichardson/node-jsonfile/pull/36 "Add typescript definition file." +[#35]: https://github.com/jprichardson/node-jsonfile/pull/35 "Add typescript definition file." +[#34]: https://github.com/jprichardson/node-jsonfile/pull/34 "readFile JSON parse error includes filename" +[#33]: https://github.com/jprichardson/node-jsonfile/pull/33 "fix throw->throws typo in readFileSync()" +[#32]: https://github.com/jprichardson/node-jsonfile/issues/32 "readFile & readFileSync can possible have strip-comments as an option?" +[#31]: https://github.com/jprichardson/node-jsonfile/pull/31 "[Modify] Support string include is unicode escape string" +[#30]: https://github.com/jprichardson/node-jsonfile/issues/30 "How to use Jsonfile package in Meteor.js App?" +[#29]: https://github.com/jprichardson/node-jsonfile/issues/29 "writefile callback if no error?" +[#28]: https://github.com/jprichardson/node-jsonfile/issues/28 "writeFile options argument broken " +[#27]: https://github.com/jprichardson/node-jsonfile/pull/27 "Use svg instead of png to get better image quality" +[#26]: https://github.com/jprichardson/node-jsonfile/issues/26 "Breaking change to fs-extra" +[#25]: https://github.com/jprichardson/node-jsonfile/issues/25 "support string encoding param for read methods" +[#24]: https://github.com/jprichardson/node-jsonfile/issues/24 "readFile: Passing in null options with a callback throws an error" +[#23]: https://github.com/jprichardson/node-jsonfile/pull/23 "Add appendFile and appendFileSync" +[#22]: https://github.com/jprichardson/node-jsonfile/issues/22 "Default value for spaces in readme.md is outdated" +[#21]: https://github.com/jprichardson/node-jsonfile/pull/21 "Update license attribute" +[#20]: https://github.com/jprichardson/node-jsonfile/issues/20 "Add simple caching functionallity" +[#19]: https://github.com/jprichardson/node-jsonfile/pull/19 "Add appendFileSync method" +[#18]: https://github.com/jprichardson/node-jsonfile/issues/18 "Add updateFile and updateFileSync methods" +[#17]: https://github.com/jprichardson/node-jsonfile/issues/17 "seem read & write sync has sequentially problem" +[#16]: https://github.com/jprichardson/node-jsonfile/pull/16 "export spaces defaulted to null" +[#15]: https://github.com/jprichardson/node-jsonfile/issues/15 "`jsonfile.spaces` should default to `null`" +[#14]: https://github.com/jprichardson/node-jsonfile/pull/14 "Add EOL at EOF" +[#13]: https://github.com/jprichardson/node-jsonfile/issues/13 "Add a final newline" +[#12]: https://github.com/jprichardson/node-jsonfile/issues/12 "readFile doesn't accept options" +[#11]: https://github.com/jprichardson/node-jsonfile/pull/11 "Added try,catch to readFileSync" +[#10]: https://github.com/jprichardson/node-jsonfile/issues/10 "No output or error from writeFile" +[#9]: https://github.com/jprichardson/node-jsonfile/pull/9 "Change 'js' to 'jf' in example." +[#8]: https://github.com/jprichardson/node-jsonfile/pull/8 "Updated forgotten module.exports to me." +[#7]: https://github.com/jprichardson/node-jsonfile/pull/7 "Add file name in error message" +[#6]: https://github.com/jprichardson/node-jsonfile/pull/6 "Use graceful-fs when possible" +[#5]: https://github.com/jprichardson/node-jsonfile/pull/5 "Jsonfile doesn't behave nicely when used inside a test suite." +[#4]: https://github.com/jprichardson/node-jsonfile/pull/4 "Added options parameter to writeFile and writeFileSync" +[#3]: https://github.com/jprichardson/node-jsonfile/issues/3 "test2" +[#2]: https://github.com/jprichardson/node-jsonfile/issues/2 "homepage field must be a string url. Deleted." +[#1]: https://github.com/jprichardson/node-jsonfile/pull/1 "adding an `.npmignore` file" diff --git a/node_modules/jsonfile/LICENSE b/node_modules/jsonfile/LICENSE new file mode 100644 index 0000000..cb7e807 --- /dev/null +++ b/node_modules/jsonfile/LICENSE @@ -0,0 +1,15 @@ +(The MIT License) + +Copyright (c) 2012-2015, JP Richardson + +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/jsonfile/README.md b/node_modules/jsonfile/README.md new file mode 100644 index 0000000..54bca05 --- /dev/null +++ b/node_modules/jsonfile/README.md @@ -0,0 +1,162 @@ +Node.js - jsonfile +================ + +Easily read/write JSON files. + +[![npm Package](https://img.shields.io/npm/v/jsonfile.svg?style=flat-square)](https://www.npmjs.org/package/jsonfile) +[![build status](https://secure.travis-ci.org/jprichardson/node-jsonfile.svg)](http://travis-ci.org/jprichardson/node-jsonfile) +[![windows Build status](https://img.shields.io/appveyor/ci/jprichardson/node-jsonfile/master.svg?label=windows%20build)](https://ci.appveyor.com/project/jprichardson/node-jsonfile/branch/master) + +Standard JavaScript + +Why? +---- + +Writing `JSON.stringify()` and then `fs.writeFile()` and `JSON.parse()` with `fs.readFile()` enclosed in `try/catch` blocks became annoying. + + + +Installation +------------ + + npm install --save jsonfile + + + +API +--- + +### readFile(filename, [options], callback) + +`options` (`object`, default `undefined`): Pass in any `fs.readFile` options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). + - `throws` (`boolean`, default: `true`). If `JSON.parse` throws an error, pass this error to the callback. + If `false`, returns `null` for the object. + + +```js +var jsonfile = require('jsonfile') +var file = '/tmp/data.json' +jsonfile.readFile(file, function(err, obj) { + console.dir(obj) +}) +``` + + +### readFileSync(filename, [options]) + +`options` (`object`, default `undefined`): Pass in any `fs.readFileSync` options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse). +- `throws` (`boolean`, default: `true`). If `JSON.parse` throws an error, throw the error. +If `false`, returns `null` for the object. + +```js +var jsonfile = require('jsonfile') +var file = '/tmp/data.json' + +console.dir(jsonfile.readFileSync(file)) +``` + + +### writeFile(filename, obj, [options], callback) + +`options`: Pass in any `fs.writeFile` options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`. + + +```js +var jsonfile = require('jsonfile') + +var file = '/tmp/data.json' +var obj = {name: 'JP'} + +jsonfile.writeFile(file, obj, function (err) { + console.error(err) +}) +``` + +**formatting with spaces:** + +```js +var jsonfile = require('jsonfile') + +var file = '/tmp/data.json' +var obj = {name: 'JP'} + +jsonfile.writeFile(file, obj, {spaces: 2}, function(err) { + console.error(err) +}) +``` + + +### writeFileSync(filename, obj, [options]) + +`options`: Pass in any `fs.writeFileSync` options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`. + +```js +var jsonfile = require('jsonfile') + +var file = '/tmp/data.json' +var obj = {name: 'JP'} + +jsonfile.writeFileSync(file, obj) +``` + +**formatting with spaces:** + +```js +var jsonfile = require('jsonfile') + +var file = '/tmp/data.json' +var obj = {name: 'JP'} + +jsonfile.writeFileSync(file, obj, {spaces: 2}) +``` + + + +### spaces + +Global configuration to set spaces to indent JSON files. + +**default:** `null` + +```js +var jsonfile = require('jsonfile') + +jsonfile.spaces = 4 + +var file = '/tmp/data.json' +var obj = {name: 'JP'} + +// json file has four space indenting now +jsonfile.writeFile(file, obj, function (err) { + console.error(err) +}) +``` + +Note, it's bound to `this.spaces`. So, if you do this: + +```js +var myObj = {} +myObj.writeJsonSync = jsonfile.writeFileSync +// => this.spaces = null +``` + +Could do the following: + +```js +var jsonfile = require('jsonfile') +jsonfile.spaces = 4 +jsonfile.writeFileSync(file, obj) // will have 4 spaces indentation + +var myCrazyObj = {spaces: 32} +myCrazyObj.writeJsonSync = jsonfile.writeFileSync +myCrazyObj.writeJsonSync(file, obj) // will have 32 space indentation +myCrazyObj.writeJsonSync(file, obj, {spaces: 2}) // will have only 2 +``` + + +License +------- + +(MIT License) + +Copyright 2012-2016, JP Richardson diff --git a/node_modules/jsonfile/appveyor.yml b/node_modules/jsonfile/appveyor.yml new file mode 100644 index 0000000..872af18 --- /dev/null +++ b/node_modules/jsonfile/appveyor.yml @@ -0,0 +1,28 @@ +# Test against this version of Node.js +environment: + matrix: + # node.js + - nodejs_version: "0.10" + - nodejs_version: "0.12" + - nodejs_version: "4" + - nodejs_version: "5" + - nodejs_version: "6" + +# Install scripts. (runs after repo cloning) +install: + # Get the latest stable version of Node.js or io.js + - ps: Install-Product node $env:nodejs_version + # install modules + - npm config set loglevel warn + - npm install --silent + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - node --version + - npm --version + # run tests + - npm test + +# Don't actually build. +build: off diff --git a/node_modules/jsonfile/index.js b/node_modules/jsonfile/index.js new file mode 100644 index 0000000..7111e15 --- /dev/null +++ b/node_modules/jsonfile/index.js @@ -0,0 +1,133 @@ +var _fs +try { + _fs = require('graceful-fs') +} catch (_) { + _fs = require('fs') +} + +function readFile (file, options, callback) { + if (callback == null) { + callback = options + options = {} + } + + if (typeof options === 'string') { + options = {encoding: options} + } + + options = options || {} + var fs = options.fs || _fs + + var shouldThrow = true + // DO NOT USE 'passParsingErrors' THE NAME WILL CHANGE!!!, use 'throws' instead + if ('passParsingErrors' in options) { + shouldThrow = options.passParsingErrors + } else if ('throws' in options) { + shouldThrow = options.throws + } + + fs.readFile(file, options, function (err, data) { + if (err) return callback(err) + + data = stripBom(data) + + var obj + try { + obj = JSON.parse(data, options ? options.reviver : null) + } catch (err2) { + if (shouldThrow) { + err2.message = file + ': ' + err2.message + return callback(err2) + } else { + return callback(null, null) + } + } + + callback(null, obj) + }) +} + +function readFileSync (file, options) { + options = options || {} + if (typeof options === 'string') { + options = {encoding: options} + } + + var fs = options.fs || _fs + + var shouldThrow = true + // DO NOT USE 'passParsingErrors' THE NAME WILL CHANGE!!!, use 'throws' instead + if ('passParsingErrors' in options) { + shouldThrow = options.passParsingErrors + } else if ('throws' in options) { + shouldThrow = options.throws + } + + var content = fs.readFileSync(file, options) + content = stripBom(content) + + try { + return JSON.parse(content, options.reviver) + } catch (err) { + if (shouldThrow) { + err.message = file + ': ' + err.message + throw err + } else { + return null + } + } +} + +function writeFile (file, obj, options, callback) { + if (callback == null) { + callback = options + options = {} + } + options = options || {} + var fs = options.fs || _fs + + var spaces = typeof options === 'object' && options !== null + ? 'spaces' in options + ? options.spaces : this.spaces + : this.spaces + + var str = '' + try { + str = JSON.stringify(obj, options ? options.replacer : null, spaces) + '\n' + } catch (err) { + if (callback) return callback(err, null) + } + + fs.writeFile(file, str, options, callback) +} + +function writeFileSync (file, obj, options) { + options = options || {} + var fs = options.fs || _fs + + var spaces = typeof options === 'object' && options !== null + ? 'spaces' in options + ? options.spaces : this.spaces + : this.spaces + + var str = JSON.stringify(obj, options.replacer, spaces) + '\n' + // not sure if fs.writeFileSync returns anything, but just in case + return fs.writeFileSync(file, str, options) +} + +function stripBom (content) { + // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified + if (Buffer.isBuffer(content)) content = content.toString('utf8') + content = content.replace(/^\uFEFF/, '') + return content +} + +var jsonfile = { + spaces: null, + readFile: readFile, + readFileSync: readFileSync, + writeFile: writeFile, + writeFileSync: writeFileSync +} + +module.exports = jsonfile diff --git a/node_modules/jsonfile/package.json b/node_modules/jsonfile/package.json new file mode 100644 index 0000000..003be43 --- /dev/null +++ b/node_modules/jsonfile/package.json @@ -0,0 +1,73 @@ +{ + "_args": [ + [ + "jsonfile@2.4.0", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "jsonfile@2.4.0", + "_id": "jsonfile@2.4.0", + "_inBundle": false, + "_integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=", + "_location": "/jsonfile", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "jsonfile@2.4.0", + "name": "jsonfile", + "escapedName": "jsonfile", + "rawSpec": "2.4.0", + "saveSpec": null, + "fetchSpec": "2.4.0" + }, + "_requiredBy": [ + "/fs-extra" + ], + "_resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz", + "_spec": "2.4.0", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "JP Richardson", + "email": "jprichardson@gmail.com" + }, + "bugs": { + "url": "https://github.com/jprichardson/node-jsonfile/issues" + }, + "dependencies": { + "graceful-fs": "^4.1.6" + }, + "description": "Easily read/write JSON files.", + "devDependencies": { + "mocha": "2.x", + "mock-fs": "^3.8.0", + "rimraf": "^2.4.0", + "standard": "^6.0.8" + }, + "homepage": "https://github.com/jprichardson/node-jsonfile#readme", + "keywords": [ + "read", + "write", + "file", + "json", + "fs", + "fs-extra" + ], + "license": "MIT", + "main": "index.js", + "name": "jsonfile", + "optionalDependencies": { + "graceful-fs": "^4.1.6" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/jprichardson/node-jsonfile.git" + }, + "scripts": { + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "mocha" + }, + "version": "2.4.0" +} diff --git a/node_modules/minimatch/LICENSE b/node_modules/minimatch/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/minimatch/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/minimatch/README.md b/node_modules/minimatch/README.md new file mode 100644 index 0000000..ad72b81 --- /dev/null +++ b/node_modules/minimatch/README.md @@ -0,0 +1,209 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. diff --git a/node_modules/minimatch/minimatch.js b/node_modules/minimatch/minimatch.js new file mode 100644 index 0000000..5b5f8cf --- /dev/null +++ b/node_modules/minimatch/minimatch.js @@ -0,0 +1,923 @@ +module.exports = minimatch +minimatch.Minimatch = Minimatch + +var path = { sep: '/' } +try { + path = require('path') +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} +var expand = require('brace-expansion') + +var plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +var qmark = '[^/]' + +// * => any number of characters +var star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// characters that need to be escaped in RegExp. +var reSpecials = charSet('().*{}+?[]^$\\!') + +// "abc" -> { a:true, b:true, c:true } +function charSet (s) { + return s.split('').reduce(function (set, c) { + set[c] = true + return set + }, {}) +} + +// normalizes slashes. +var slashSplit = /\/+/ + +minimatch.filter = filter +function filter (pattern, options) { + options = options || {} + return function (p, i, list) { + return minimatch(p, pattern, options) + } +} + +function ext (a, b) { + a = a || {} + b = b || {} + var t = {} + Object.keys(b).forEach(function (k) { + t[k] = b[k] + }) + Object.keys(a).forEach(function (k) { + t[k] = a[k] + }) + return t +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch + + var orig = minimatch + + var m = function minimatch (p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)) + } + + m.Minimatch = function Minimatch (pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)) + } + + return m +} + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch + return minimatch.defaults(def).Minimatch +} + +function minimatch (p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + // "" only matches "" + if (pattern.trim() === '') return p === '' + + return new Minimatch(pattern, options).match(p) +} + +function Minimatch (pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options) + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required') + } + + if (!options) options = {} + pattern = pattern.trim() + + // windows support: need to use /, not \ + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/') + } + + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + + // make the set of regexps etc. + this.make() +} + +Minimatch.prototype.debug = function () {} + +Minimatch.prototype.make = make +function make () { + // don't do it more than once. + if (this._made) return + + var pattern = this.pattern + var options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + var set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = console.error + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(function (s) { + return s.split(slashSplit) + }) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map(function (s, si, set) { + return s.map(this.parse, this) + }, this) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(function (s) { + return s.indexOf(false) === -1 + }) + + this.debug(this.pattern, set) + + this.set = set +} + +Minimatch.prototype.parseNegate = parseNegate +function parseNegate () { + var pattern = this.pattern + var negate = false + var options = this.options + var negateOffset = 0 + + if (options.nonegate) return + + for (var i = 0, l = pattern.length + ; i < l && pattern.charAt(i) === '!' + ; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate +} + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options) +} + +Minimatch.prototype.braceExpand = braceExpand + +function braceExpand (pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options + } else { + options = {} + } + } + + pattern = typeof pattern === 'undefined' + ? this.pattern : pattern + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern') + } + + if (options.nobrace || + !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +Minimatch.prototype.parse = parse +var SUBPARSE = {} +function parse (pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long') + } + + var options = this.options + + // shortcuts + if (!options.noglobstar && pattern === '**') return GLOBSTAR + if (pattern === '') return '' + + var re = '' + var hasMagic = !!options.nocase + var escaping = false + // ? => one single character + var patternListStack = [] + var negativeLists = [] + var stateChar + var inClass = false + var reClassStart = -1 + var classStart = -1 + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + var self = this + + function clearStateChar () { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + self.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (var i = 0, len = pattern.length, c + ; (i < len) && (c = pattern.charAt(i)) + ; i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping && reSpecials[c]) { + re += '\\' + c + escaping = false + continue + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false + + case '\\': + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + self.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } + + clearStateChar() + hasMagic = true + var pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|' + escaping = false + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + escaping = false + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + cs + ']') + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' + hasMagic = hasMagic || sp[1] + inClass = false + continue + } + } + + // finish up the class. + hasMagic = true + inClass = false + re += c + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (escaping) { + // no need + escaping = false + } else if (reSpecials[c] + && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + var t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + var addPatternStart = false + switch (re.charAt(0)) { + case '.': + case '[': + case '(': addPatternStart = true + } + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n] + + var nlBefore = re.slice(0, nl.reStart) + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + var nlAfter = re.slice(nl.reEnd) + + nlLast += nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + var openParensBefore = nlBefore.split('(').length - 1 + var cleanAfter = nlAfter + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + var dollar = '' + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$' + } + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast + re = newRe + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + var flags = options.nocase ? 'i' : '' + try { + var regExp = new RegExp('^' + re + '$', flags) + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + + regExp._glob = pattern + regExp._src = re + + return regExp +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe() +} + +Minimatch.prototype.makeRe = makeRe +function makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + var set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + var options = this.options + + var twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + var flags = options.nocase ? 'i' : '' + + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return (p === GLOBSTAR) ? twoStar + : (typeof p === 'string') ? regExpEscape(p) + : p._src + }).join('\\\/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) { + this.regexp = false + } + return this.regexp +} + +minimatch.match = function (list, pattern, options) { + options = options || {} + var mm = new Minimatch(pattern, options) + list = list.filter(function (f) { + return mm.match(f) + }) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +Minimatch.prototype.match = match +function match (f, partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + var options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + var filename + var i + for (i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i] + var file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + var hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate +} + +// set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase() + } else { + hit = f === p + } + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') + return emptyFileEnd + } + + // should be unreachable. + throw new Error('wtf?') +} + +// replace stuff like \* with * +function globUnescape (s) { + return s.replace(/\\(.)/g, '$1') +} + +function regExpEscape (s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +} diff --git a/node_modules/minimatch/package.json b/node_modules/minimatch/package.json new file mode 100644 index 0000000..47a776d --- /dev/null +++ b/node_modules/minimatch/package.json @@ -0,0 +1,67 @@ +{ + "_args": [ + [ + "minimatch@3.0.4", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "minimatch@3.0.4", + "_id": "minimatch@3.0.4", + "_inBundle": false, + "_integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "_location": "/minimatch", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "minimatch@3.0.4", + "name": "minimatch", + "escapedName": "minimatch", + "rawSpec": "3.0.4", + "saveSpec": null, + "fetchSpec": "3.0.4" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", + "_spec": "3.0.4", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me" + }, + "bugs": { + "url": "https://github.com/isaacs/minimatch/issues" + }, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "description": "a glob matcher in javascript", + "devDependencies": { + "tap": "^10.3.2" + }, + "engines": { + "node": "*" + }, + "files": [ + "minimatch.js" + ], + "homepage": "https://github.com/isaacs/minimatch#readme", + "license": "ISC", + "main": "minimatch.js", + "name": "minimatch", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap test/*.js --cov" + }, + "version": "3.0.4" +} diff --git a/node_modules/node-latex/.prettierrc b/node_modules/node-latex/.prettierrc new file mode 100644 index 0000000..49955e2 --- /dev/null +++ b/node_modules/node-latex/.prettierrc @@ -0,0 +1,5 @@ +{ + "semi": false, + "singleQuote": true, + "trailingComma": "none" +} diff --git a/node_modules/node-latex/index.d.ts b/node_modules/node-latex/index.d.ts new file mode 100644 index 0000000..75abd3c --- /dev/null +++ b/node_modules/node-latex/index.d.ts @@ -0,0 +1,58 @@ +import { Readable, Transform } from 'stream' + +/** + * node-latex options + */ +export interface LatexOptions { + /** + * The absolute path (or an array of absolute paths) to the directory which + * contains the assets necessary for the doc. + */ + inputs?: string | string[] + + /** + * The absolute path (or an array of absolute paths) to the directory which + * contains the fonts necessary for the doc (you will most likely want to use + * this option if you're working with fontspec). + */ + fonts?: string | string[] + + /** + * The command to run for your document (pdflatex, xetex, etc). pdflatex is the + * default. + */ + cmd?: string + + /** + * Arguments passed to cmd. Defaults to ['-halt-on-error']. + */ + args?: string[] + + /** + * The number of times to run options.cmd. Some documents require multiple + * passes. Only works when doc is a String. Defaults to 1. + */ + passes?: number + + /** + * The path to the file where you want to save the contents of the error log + * to. + */ + errorLogs?: string +} + +/** + * Compiles latex to pdf document + * + * @param doc + * The (La)TeX document you want to use. + * + * @param options + * The compiler options + */ +declare function latex( + doc: Readable | string, + options?: LatexOptions +): Transform + +export default latex diff --git a/node_modules/node-latex/index.js b/node_modules/node-latex/index.js new file mode 100644 index 0000000..1b1830f --- /dev/null +++ b/node_modules/node-latex/index.js @@ -0,0 +1,204 @@ +'use strict' + +const strToStream = require('string-to-stream') +const spawn = require('child_process').spawn +const through = require('through2') +const fse = require('fs-extra') +const temp = require('temp').track() +const path = require('path') +const fs = require('fs') + +/** + * Generates a PDF stream from a LaTeX document. + * + * @param {String} src - The LaTeX document. + * @param {Object} options - Optional compilation specifications. + * + * @return {DestroyableTransform} + */ +function latex(src, options) { + const outputStream = through() + + /** + * Emits the given error to the returned output stream. + */ + const handleErrors = (err) => { + outputStream.emit('error', err) + outputStream.destroy() + } + + /** + * Emits errors from logs to output stream, and also gives full log to user if requested. + */ + const printErrors = (tempPath, userLogPath) => { + const errorLogPath = path.join(tempPath, 'texput.log') + + fs.stat(errorLogPath, (err, stats) => { + if (err || !stats.isFile()) { + outputStream.emit('error', new Error('No error log file.')) + return + } + + const errorLogStream = fs.createReadStream(errorLogPath) + + if (userLogPath) { + const userLogStream = fs.createWriteStream(path.resolve(userLogPath)) + errorLogStream.pipe(userLogStream) + } + + const errors = [] + + errorLogStream.on('data', (data) => { + const lines = data.toString().split('\n') + + lines.forEach((line, i) => { + if (line.startsWith('! Undefined control sequence.')) { + errors.push(lines[i - 1]) + errors.push(lines[i]) + errors.push(lines[i + 1]) + } else if (line.startsWith('!')) { + errors.push(line) + } + }) + }) + + errorLogStream.on('end', () => { + const errMessage = `LaTeX Syntax Error\n${errors.join('\n')}` + const error = new Error(errMessage) + + outputStream.emit('error', error) + }) + }) + } + + temp.mkdir('node-latex', (err, tempPath) => { + if (err) { + handleErrors(err) + } + + let inputStream + + if (!src) { + handleErrors(new Error('Error: No TeX document provided.')) + } + + if (typeof src === 'string') { + inputStream = strToStream(src) + } else if (src.pipe) { + inputStream = src + } else { + handleErrors(new Error('Error: Invalid TeX document.')) + } + + options = options || {} + + function resolvePaths(paths) { + if (Array.isArray(paths)) { + return paths.map(pth => path.resolve(pth)) + } + return path.resolve(paths) + } + + // The path(s) to your TEXINPUTS. + const inputs = options.inputs ? resolvePaths(options.inputs) : tempPath + + // The path(s) to your font inputs for fontspec. + const fonts = options.fonts ? resolvePaths(options.fonts) : tempPath + + // The binary command to run (`pdflatex`, `xetex`, etc). + const cmd = options.cmd || 'pdflatex' + + // The number of times to run LaTeX. + const passes = options.passes || 1 + + // The path to where the user wants to save the error log file to. + const userLogPath = options.errorLogs + + // The current amount of times LaTeX has run so far. + let completedPasses = 0 + + if (passes > 1 && typeof src !== 'string') { + const msg = 'Error: You can\'t process a stream twice. Pass a string to use multiple passes.' + handleErrors(new Error(msg)) + + return + } + + /** + * Combines all paths into a single PATH to be added to process.env. + */ + const joinPaths = inputs => + (Array.isArray(inputs) ? inputs.join(path.delimiter) : inputs) + + path.delimiter + + const args = options.args || [ + '-halt-on-error' + ] + args.push('-jobname=texput') + + const opts = { + cwd: tempPath, + env: Object.assign({}, process.env, { + TEXINPUTS: joinPaths(inputs), + TTFONTS: joinPaths(fonts), + OPENTYPEFONTS: joinPaths(fonts) + }) + } + + /** + * Runs a LaTeX child process on the document stream + * and then decides whether it needs to do it again. + */ + const runLatex = (inputStream) => { + const tex = spawn(cmd, args, opts) + + inputStream.pipe(tex.stdin) + + // Prevent Node from crashing on compilation error. + tex.stdin.on('error', handleErrors) + + tex.on('error', () => { + handleErrors(new Error(`Error: Unable to run ${cmd} command.`)) + }) + + tex.stdout.on('data', (data) => { }); + + tex.stderr.on('data', (data) => { }); + + tex.on('close', (code) => { }); + + tex.on('exit', (code) => { + if (code !== 0) { + printErrors(tempPath, userLogPath) + return + } + + completedPasses++ + + // Schedule another run if necessary. + completedPasses >= passes + ? returnDocument() + : runLatex(strToStream(src)) + }) + } + + /** + * Returns the PDF stream after the final run. + */ + const returnDocument = () => { + const pdfPath = path.join(tempPath, 'texput.pdf') + const pdfStream = fs.createReadStream(pdfPath) + + pdfStream.pipe(outputStream) + pdfStream.on('close', () => fse.removeSync(tempPath)) + pdfStream.on('error', handleErrors) + } + + // Start the first run. + runLatex(inputStream) + }) + + return outputStream +} + +module.exports = latex diff --git a/node_modules/node-latex/license b/node_modules/node-latex/license new file mode 100644 index 0000000..e4615f9 --- /dev/null +++ b/node_modules/node-latex/license @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Saad Quadri + +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/node-latex/package.json b/node_modules/node-latex/package.json new file mode 100644 index 0000000..e093249 --- /dev/null +++ b/node_modules/node-latex/package.json @@ -0,0 +1,70 @@ +{ + "_args": [ + [ + "node-latex@3.0.0", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "node-latex@3.0.0", + "_id": "node-latex@3.0.0", + "_inBundle": false, + "_integrity": "sha512-GrcJDu38/kSauDe6/V9j1wEHqwaUJyHJUb7xeGdvhQ0sofV1LecgyORRk7XEzyUFpV0jUCp1w0twvlb2T4CnqA==", + "_location": "/node-latex", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "node-latex@3.0.0", + "name": "node-latex", + "escapedName": "node-latex", + "rawSpec": "3.0.0", + "saveSpec": null, + "fetchSpec": "3.0.0" + }, + "_requiredBy": [ + "#DEV:/" + ], + "_resolved": "https://registry.npmjs.org/node-latex/-/node-latex-3.0.0.tgz", + "_spec": "3.0.0", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Saad Quadri" + }, + "bugs": { + "url": "https://github.com/saadq/node-latex/issues" + }, + "dependencies": { + "@types/node": "^11.12.0", + "fs-extra": "^2.0.0", + "string-to-stream": "^1.1.0", + "temp": "^0.8.3", + "through2": "^2.0.3" + }, + "description": "A small wrapper for LaTeX.", + "devDependencies": { + "blyss": "^2.0.0", + "snazzy": "^6.0.0" + }, + "homepage": "https://github.com/saadq/node-latex#readme", + "keywords": [ + "latex", + "pdflatex", + "xetex", + "pdf" + ], + "license": "MIT", + "main": "index.js", + "name": "node-latex", + "repository": { + "type": "git", + "url": "git+https://github.com/saadq/node-latex.git" + }, + "scripts": { + "fix": "blyss --fix", + "lint": "blyss | snazzy", + "test": "npm run --silent lint" + }, + "types": "./index.d.ts", + "version": "3.0.0" +} diff --git a/node_modules/node-latex/readme.md b/node_modules/node-latex/readme.md new file mode 100644 index 0000000..70f3ee6 --- /dev/null +++ b/node_modules/node-latex/readme.md @@ -0,0 +1,50 @@ +# node-latex +A small wrapper for generating PDFs with LaTeX in Node. + +## Requirements + +LaTeX must be installed on your machine. You can download it [here](https://www.latex-project.org/get/). + +## Install + +``` +npm install node-latex +``` + +## Usage + +```js +const latex = require('node-latex') +const fs = require('fs') + +const input = fs.createReadStream('input.tex') +const output = fs.createWriteStream('output.pdf') +const pdf = latex(input) + +pdf.pipe(output) +pdf.on('error', err => console.error(err)) +pdf.on('finish', () => console.log('PDF generated!')) +``` + +View more examples [here](https://github.com/saadq/node-latex/tree/master/examples). + +## API + +### latex(doc[, options]) + +**doc** \[ReadableStream|String\] *Required* - The (La)TeX document you want to use. + +**options.inputs** \[String|Array\] - The path (or an array of paths) to the directory which contains the assets necessary for the doc. + +**options.fonts** \[String|Array\] - The path (or an array of paths) to the directory which contains the fonts necessary for the doc (you will most likely want to use this option if you're working with `fontspec`). + +**options.cmd** \[String\] - The command to run for your document (`pdflatex`, `xetex`, etc). `pdflatex` is the default. + +**options.args** \[Array\] - Arguments passed to `cmd`. Defaults to `['-halt-on-error']`. + +**options.passes** \[Number\] - The number of times to run `options.cmd`. Some documents require multiple passes. Only works when `doc` is a String. Defaults to `1`. + +**options.errorLogs** \[String] - The path to the file where you want to save the contents of the error log to. + +## License +MIT diff --git a/node_modules/once/LICENSE b/node_modules/once/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/once/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/once/README.md b/node_modules/once/README.md new file mode 100644 index 0000000..1f1ffca --- /dev/null +++ b/node_modules/once/README.md @@ -0,0 +1,79 @@ +# once + +Only call a function once. + +## usage + +```javascript +var once = require('once') + +function load (file, cb) { + cb = once(cb) + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Or add to the Function.prototype in a responsible way: + +```javascript +// only has to be done once +require('once').proto() + +function load (file, cb) { + cb = cb.once() + loader.load('file') + loader.once('load', cb) + loader.once('error', cb) +} +``` + +Ironically, the prototype feature makes this module twice as +complicated as necessary. + +To check whether you function has been called, use `fn.called`. Once the +function is called for the first time the return value of the original +function is saved in `fn.value` and subsequent calls will continue to +return this value. + +```javascript +var once = require('once') + +function load (cb) { + cb = once(cb) + var stream = createStream() + stream.once('data', cb) + stream.once('end', function () { + if (!cb.called) cb(new Error('not found')) + }) +} +``` + +## `once.strict(func)` + +Throw an error if the function is called twice. + +Some functions are expected to be called only once. Using `once` for them would +potentially hide logical errors. + +In the example below, the `greet` function has to call the callback only once: + +```javascript +function greet (name, cb) { + // return is missing from the if statement + // when no name is passed, the callback is called twice + if (!name) cb('Hello anonymous') + cb('Hello ' + name) +} + +function log (msg) { + console.log(msg) +} + +// this will print 'Hello anonymous' but the logical error will be missed +greet(null, once(msg)) + +// once.strict will print 'Hello anonymous' and throw an error when the callback will be called the second time +greet(null, once.strict(msg)) +``` diff --git a/node_modules/once/once.js b/node_modules/once/once.js new file mode 100644 index 0000000..2354067 --- /dev/null +++ b/node_modules/once/once.js @@ -0,0 +1,42 @@ +var wrappy = require('wrappy') +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} diff --git a/node_modules/once/package.json b/node_modules/once/package.json new file mode 100644 index 0000000..2217357 --- /dev/null +++ b/node_modules/once/package.json @@ -0,0 +1,71 @@ +{ + "_args": [ + [ + "once@1.4.0", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "once@1.4.0", + "_id": "once@1.4.0", + "_inBundle": false, + "_integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", + "_location": "/once", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "once@1.4.0", + "name": "once", + "escapedName": "once", + "rawSpec": "1.4.0", + "saveSpec": null, + "fetchSpec": "1.4.0" + }, + "_requiredBy": [ + "/glob", + "/inflight" + ], + "_resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "_spec": "1.4.0", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/once/issues" + }, + "dependencies": { + "wrappy": "1" + }, + "description": "Run a function exactly one time", + "devDependencies": { + "tap": "^7.0.1" + }, + "directories": { + "test": "test" + }, + "files": [ + "once.js" + ], + "homepage": "https://github.com/isaacs/once#readme", + "keywords": [ + "once", + "function", + "one", + "single" + ], + "license": "ISC", + "main": "once.js", + "name": "once", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/once.git" + }, + "scripts": { + "test": "tap test/*.js" + }, + "version": "1.4.0" +} diff --git a/node_modules/path-is-absolute/index.js b/node_modules/path-is-absolute/index.js new file mode 100644 index 0000000..22aa6c3 --- /dev/null +++ b/node_modules/path-is-absolute/index.js @@ -0,0 +1,20 @@ +'use strict'; + +function posix(path) { + return path.charAt(0) === '/'; +} + +function win32(path) { + // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; + var result = splitDeviceRe.exec(path); + var device = result[1] || ''; + var isUnc = Boolean(device && device.charAt(1) !== ':'); + + // UNC paths are always absolute + return Boolean(result[2] || isUnc); +} + +module.exports = process.platform === 'win32' ? win32 : posix; +module.exports.posix = posix; +module.exports.win32 = win32; diff --git a/node_modules/path-is-absolute/license b/node_modules/path-is-absolute/license new file mode 100644 index 0000000..654d0bf --- /dev/null +++ b/node_modules/path-is-absolute/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/path-is-absolute/package.json b/node_modules/path-is-absolute/package.json new file mode 100644 index 0000000..74aff0a --- /dev/null +++ b/node_modules/path-is-absolute/package.json @@ -0,0 +1,79 @@ +{ + "_args": [ + [ + "path-is-absolute@1.0.1", + "C:\\Users\\karin\\Documents\\TP_project\\documents" + ] + ], + "_development": true, + "_from": "path-is-absolute@1.0.1", + "_id": "path-is-absolute@1.0.1", + "_inBundle": false, + "_integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", + "_location": "/path-is-absolute", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "path-is-absolute@1.0.1", + "name": "path-is-absolute", + "escapedName": "path-is-absolute", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/glob" + ], + "_resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "_spec": "1.0.1", + "_where": "C:\\Users\\karin\\Documents\\TP_project\\documents", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/path-is-absolute/issues" + }, + "description": "Node.js 0.12 path.isAbsolute() ponyfill", + "devDependencies": { + "xo": "^0.16.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/sindresorhus/path-is-absolute#readme", + "keywords": [ + "path", + "paths", + "file", + "dir", + "absolute", + "isabsolute", + "is-absolute", + "built-in", + "util", + "utils", + "core", + "ponyfill", + "polyfill", + "shim", + "is", + "detect", + "check" + ], + "license": "MIT", + "name": "path-is-absolute", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/path-is-absolute.git" + }, + "scripts": { + "test": "xo && node test.js" + }, + "version": "1.0.1" +} diff --git a/node_modules/path-is-absolute/readme.md b/node_modules/path-is-absolute/readme.md new file mode 100644 index 0000000..8dbdf5f --- /dev/null +++ b/node_modules/path-is-absolute/readme.md @@ -0,0 +1,59 @@ +# path-is-absolute [![Build Status](https://travis-ci.org/sindresorhus/path-is-absolute.svg?branch=master)](https://travis-ci.org/sindresorhus/path-is-absolute) + +> Node.js 0.12 [`path.isAbsolute()`](http://nodejs.org/api/path.html#path_path_isabsolute_path) [ponyfill](https://ponyfill.com) + + +## Install + +``` +$ npm install --save path-is-absolute +``` + + +## Usage + +```js +const pathIsAbsolute = require('path-is-absolute'); + +// Running on Linux +pathIsAbsolute('/home/foo'); +//=> true +pathIsAbsolute('C:/Users/foo'); +//=> false + +// Running on Windows +pathIsAbsolute('C:/Users/foo'); +//=> true +pathIsAbsolute('/home/foo'); +//=> false + +// Running on any OS +pathIsAbsolute.posix('/home/foo'); +//=> true +pathIsAbsolute.posix('C:/Users/foo'); +//=> false +pathIsAbsolute.win32('C:/Users/foo'); +//=> true +pathIsAbsolute.win32('/home/foo'); +//=> false +``` + + +## API + +See the [`path.isAbsolute()` docs](http://nodejs.org/api/path.html#path_path_isabsolute_path). + +### pathIsAbsolute(path) + +### pathIsAbsolute.posix(path) + +POSIX specific version. + +### pathIsAbsolute.win32(path) + +Windows specific version. + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/prettier/LICENSE b/node_modules/prettier/LICENSE new file mode 100644 index 0000000..5767e34 --- /dev/null +++ b/node_modules/prettier/LICENSE @@ -0,0 +1,7 @@ +Copyright © James Long and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/prettier/README.md b/node_modules/prettier/README.md new file mode 100644 index 0000000..76f2e04 --- /dev/null +++ b/node_modules/prettier/README.md @@ -0,0 +1,111 @@ +![Prettier Banner](https://raw.githubusercontent.com/prettier/prettier-logo/master/images/prettier-banner-light.png) + +

Opinionated Code Formatter

+ +

+ + JavaScript + · TypeScript + · Flow + · JSX + · JSON + +
+ + CSS + · SCSS + · Less + +
+ + HTML + · Vue + · Angular + +
+ + GraphQL + · Markdown + · YAML + +
+ + + Your favorite language? + + +

+ +

+ + Github Actions Build Status + + Github Actions Build Status + + Github Actions Build Status + + Codecov Coverage Status + + Blazing Fast +
+ + npm version + + weekly downloads from npm + + code style: prettier + + Chat on Gitter + + Follow Prettier on Twitter +

+ +## Intro + +Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary. + +### Input + + +```js +foo(reallyLongArg(), omgSoManyParameters(), IShouldRefactorThis(), isThereSeriouslyAnotherOne()); +``` + +### Output + +```js +foo( + reallyLongArg(), + omgSoManyParameters(), + IShouldRefactorThis(), + isThereSeriouslyAnotherOne() +); +``` + +Prettier can be run [in your editor](http://prettier.io/docs/en/editors.html) on-save, in a [pre-commit hook](https://prettier.io/docs/en/precommit.html), or in [CI environments](https://prettier.io/docs/en/cli.html#list-different) to ensure your codebase has a consistent style without devs ever having to post a nit-picky comment on a code review ever again! + +--- + +**[Documentation](https://prettier.io/docs/en/)** + + +[Install](https://prettier.io/docs/en/install.html) · +[Options](https://prettier.io/docs/en/options.html) · +[CLI](https://prettier.io/docs/en/cli.html) · +[API](https://prettier.io/docs/en/api.html) + +**[Playground](https://prettier.io/playground/)** + +--- + +## Badge + +Show the world you're using _Prettier_ → [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) + +```md +[![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg?style=flat-square)](https://github.com/prettier/prettier) +``` + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md). diff --git a/node_modules/prettier/bin-prettier.js b/node_modules/prettier/bin-prettier.js new file mode 100644 index 0000000..2fe4edf --- /dev/null +++ b/node_modules/prettier/bin-prettier.js @@ -0,0 +1,16523 @@ +#!/usr/bin/env node +'use strict'; + +var path = require('path'); +var fs$2 = require('fs'); +var readline = require('readline'); +var os = require('os'); +var tty = require('tty'); +var util$2 = require('util'); +var stream$4 = require('stream'); +var events = require('events'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var path__default = /*#__PURE__*/_interopDefaultLegacy(path); +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$2); +var readline__default = /*#__PURE__*/_interopDefaultLegacy(readline); +var os__default = /*#__PURE__*/_interopDefaultLegacy(os); +var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty); +var util__default = /*#__PURE__*/_interopDefaultLegacy(util$2); +var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream$4); +var events__default = /*#__PURE__*/_interopDefaultLegacy(events); + +var semverCompare = function cmp(a, b) { + var pa = a.split('.'); + var pb = b.split('.'); + + for (var i = 0; i < 3; i++) { + var na = Number(pa[i]); + var nb = Number(pb[i]); + if (na > nb) return 1; + if (nb > na) return -1; + if (!isNaN(na) && isNaN(nb)) return 1; + if (isNaN(na) && !isNaN(nb)) return -1; + } + + return 0; +}; + +var pleaseUpgradeNode = function pleaseUpgradeNode(pkg, opts) { + var opts = opts || {}; + var requiredVersion = pkg.engines.node.replace('>=', ''); + var currentVersion = process.version.replace('v', ''); + + if (semverCompare(currentVersion, requiredVersion) === -1) { + if (opts.message) { + console.error(opts.message(requiredVersion)); + } else { + console.error(pkg.name + ' requires at least version ' + requiredVersion + ' of Node, please upgrade'); + } + + if (opts.hasOwnProperty('exitCode')) { + process.exit(opts.exitCode); + } else { + process.exit(1); + } + } +}; + +var name = "prettier"; +var version = "2.1.2"; +var description = "Prettier is an opinionated code formatter"; +var bin = "./bin/prettier.js"; +var repository = "prettier/prettier"; +var homepage = "https://prettier.io"; +var author = "James Long"; +var license = "MIT"; +var main = "./index.js"; +var browser = "./standalone.js"; +var unpkg = "./standalone.js"; +var engines = { + node: ">=10.13.0" +}; +var files = [ + "index.js", + "standalone.js", + "src", + "bin" +]; +var dependencies = { + "@angular/compiler": "10.0.12", + "@babel/code-frame": "7.10.4", + "@babel/parser": "7.11.2", + "@glimmer/syntax": "0.59.0", + "@iarna/toml": "2.2.5", + "@typescript-eslint/typescript-estree": "3.10.0", + "angular-estree-parser": "2.2.0", + "angular-html-parser": "1.7.1", + camelcase: "6.0.0", + chalk: "4.1.0", + "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", + "cjk-regex": "2.0.0", + cosmiconfig: "7.0.0", + dashify: "2.0.0", + diff: "4.0.2", + editorconfig: "0.15.3", + "editorconfig-to-prettier": "0.1.1", + "escape-string-regexp": "4.0.0", + esutils: "2.0.3", + "fast-glob": "3.2.4", + "fast-json-stable-stringify": "2.1.0", + "find-parent-dir": "0.3.0", + "flow-parser": "0.132.0", + "get-stream": "6.0.0", + globby: "11.0.1", + graphql: "15.3.0", + "html-element-attributes": "2.2.1", + "html-styles": "1.0.0", + "html-tag-names": "1.1.5", + "html-void-elements": "1.0.5", + ignore: "4.0.6", + "jest-docblock": "26.0.0", + json5: "2.1.3", + leven: "3.1.0", + "lines-and-columns": "1.1.6", + "linguist-languages": "7.10.0", + lodash: "4.17.20", + mem: "6.1.0", + minimatch: "3.0.4", + minimist: "1.2.5", + "n-readlines": "1.0.0", + outdent: "0.7.1", + "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee", + "please-upgrade-node": "3.2.0", + "postcss-less": "3.1.4", + "postcss-media-query-parser": "0.2.3", + "postcss-scss": "2.1.1", + "postcss-selector-parser": "2.2.3", + "postcss-values-parser": "2.0.1", + "regexp-util": "1.2.2", + "remark-footnotes": "2.0.0", + "remark-math": "1.0.6", + "remark-parse": "8.0.3", + resolve: "1.17.0", + semver: "7.3.2", + "string-width": "4.2.0", + typescript: "4.0.2", + "unicode-regex": "3.0.0", + unified: "9.2.0", + vnopts: "1.0.2", + "yaml-unist-parser": "1.3.1" +}; +var devDependencies = { + "@babel/core": "7.11.4", + "@babel/preset-env": "7.11.0", + "@babel/types": "7.11.0", + "@glimmer/reference": "0.59.0", + "@rollup/plugin-alias": "3.1.1", + "@rollup/plugin-babel": "5.2.0", + "@rollup/plugin-commonjs": "14.0.0", + "@rollup/plugin-json": "4.1.0", + "@rollup/plugin-node-resolve": "9.0.0", + "@rollup/plugin-replace": "2.3.3", + "@types/estree": "0.0.45", + "@types/node": "14.6.0", + "@typescript-eslint/types": "3.10.0", + "babel-loader": "8.1.0", + benchmark: "2.1.4", + "builtin-modules": "3.1.0", + "cross-env": "7.0.2", + cspell: "4.1.0", + eslint: "7.7.0", + "eslint-config-prettier": "6.11.0", + "eslint-formatter-friendly": "7.0.0", + "eslint-plugin-import": "2.22.0", + "eslint-plugin-jest": "23.20.0", + "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules", + "eslint-plugin-react": "7.20.6", + "eslint-plugin-unicorn": "21.0.0", + execa: "4.0.3", + jest: "26.4.2", + "jest-snapshot-serializer-ansi": "1.0.0", + "jest-snapshot-serializer-raw": "1.1.0", + "jest-watch-typeahead": "0.6.0", + "npm-run-all": "4.1.5", + prettier: "2.1.1", + rimraf: "3.0.2", + rollup: "2.26.5", + "rollup-plugin-node-globals": "1.4.0", + "rollup-plugin-terser": "7.0.0", + shelljs: "0.8.4", + "snapshot-diff": "0.8.1", + "strip-ansi": "6.0.0", + "synchronous-promise": "2.0.13", + tempy: "0.6.0", + "terser-webpack-plugin": "4.1.0", + webpack: "4.44.1" +}; +var scripts = { + prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1", + "prepare-release": "yarn && yarn build && yarn test:dist", + test: "jest", + "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest", + "test:dist": "cross-env NODE_ENV=production jest", + "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest", + "test:integration": "jest tests_integration", + "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + lint: "run-p lint:*", + "lint:typecheck": "tsc", + "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly", + "lint:changelog": "node ./scripts/lint-changelog.js", + "lint:prettier": "prettier . \"!test*\" --check", + "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"", + "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"", + "lint:deps": "node ./scripts/check-deps.js", + fix: "run-s fix:eslint fix:prettier", + "fix:eslint": "yarn lint:eslint --fix", + "fix:prettier": "yarn lint:prettier --write", + build: "node ./scripts/build/build.js", + "build-docs": "node ./scripts/build-docs.js" +}; +var _package = { + name: name, + version: version, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + browser: browser, + unpkg: unpkg, + engines: engines, + files: files, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts +}; + +var _package$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name, + version: version, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + browser: browser, + unpkg: unpkg, + engines: engines, + files: files, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts, + 'default': _package +}); + +var fastJsonStableStringify = function (data, opts) { + if (!opts) opts = {}; + if (typeof opts === 'function') opts = { + cmp: opts + }; + var cycles = typeof opts.cycles === 'boolean' ? opts.cycles : false; + + var cmp = opts.cmp && function (f) { + return function (node) { + return function (a, b) { + var aobj = { + key: a, + value: node[a] + }; + var bobj = { + key: b, + value: node[b] + }; + return f(aobj, bobj); + }; + }; + }(opts.cmp); + + var seen = []; + return function stringify(node) { + if (node && node.toJSON && typeof node.toJSON === 'function') { + node = node.toJSON(); + } + + if (node === undefined) return; + if (typeof node == 'number') return isFinite(node) ? '' + node : 'null'; + if (typeof node !== 'object') return JSON.stringify(node); + var i, out; + + if (Array.isArray(node)) { + out = '['; + + for (i = 0; i < node.length; i++) { + if (i) out += ','; + out += stringify(node[i]) || 'null'; + } + + return out + ']'; + } + + if (node === null) return 'null'; + + if (seen.indexOf(node) !== -1) { + if (cycles) return JSON.stringify('__cycle__'); + throw new TypeError('Converting circular structure to JSON'); + } + + var seenIndex = seen.push(node) - 1; + var keys = Object.keys(node).sort(cmp && cmp(node)); + out = ''; + + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + var value = stringify(node[key]); + if (!value) continue; + if (out) out += ','; + out += JSON.stringify(key) + ':' + value; + } + + seen.splice(seenIndex, 1); + return '{' + out + '}'; + }(data); +}; + +var src = require("./index"); + +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 && /[\p{Lu}]/u.test(character)) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && /[\p{Ll}]/u.test(character)) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = character.toLocaleLowerCase() === character && character.toLocaleUpperCase() !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = character.toLocaleUpperCase() === character && character.toLocaleLowerCase() !== 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).toLocaleUpperCase() + 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.toLocaleUpperCase() : input.toLocaleLowerCase(); + } + + const hasUpperCase = input !== input.toLocaleLowerCase(); + + if (hasUpperCase) { + input = preserveCamelCase(input); + } + + input = input.replace(/^[_.\- ]+/, '').toLocaleLowerCase().replace(/[_.\- ]+([\p{Alpha}\p{N}_]|$)/gu, (_, p1) => p1.toLocaleUpperCase()).replace(/\d+([\p{Alpha}\p{N}_]|$)/gu, m => m.toLocaleUpperCase()); + return postProcess(input); +}; + +var camelcase = camelCase; // TODO: Remove this for the next major release + +var _default = camelCase; +camelcase.default = _default; + +/*! + * dashify + * + * Copyright (c) 2015-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var dashify = (str, options) => { + if (typeof str !== 'string') throw new TypeError('expected a string'); + return str.trim().replace(/([a-z])([A-Z])/g, '$1-$2').replace(/\W/g, m => /[À-ž]/.test(m) ? m : '-').replace(/^-+|-+$/g, '').replace(/-{2,}/g, m => options && options.condense ? '-' : m).toLowerCase(); +}; + +function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; +} + +function getCjsExportFromNamespace (n) { + return n && n['default'] || n; +} + +function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); +} + +var colorName = { + "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] +}; + +/* MIT license */ + +/* eslint-disable no-mixed-operators */ +// 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(colorName)) { + reverseKeywords[colorName[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'] + } +}; +var conversions = 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(colorName)) { + const value = colorName[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 colorName[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]; +}; + +/* + 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; +} + +var route = 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; +}; + +const convert$1 = {}; +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$1[fromModel] = {}; + Object.defineProperty(convert$1[fromModel], 'channels', { + value: conversions[fromModel].channels + }); + Object.defineProperty(convert$1[fromModel], 'labels', { + value: conversions[fromModel].labels + }); + const routes = route(fromModel); + const routeModels = Object.keys(routes); + routeModels.forEach(toModel => { + const fn = routes[toModel]; + convert$1[fromModel][toModel] = wrapRounded(fn); + convert$1[fromModel][toModel].raw = wrapRaw(fn); + }); +}); +var colorConvert = convert$1; + +var ansiStyles = createCommonjsModule(function (module) { + + 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$1; + + const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { + if (colorConvert$1 === undefined) { + colorConvert$1 = colorConvert; + } + + const offset = isBackground ? 10 : 0; + const styles = {}; + + for (const [sourceSpace, suite] of Object.entries(colorConvert$1)) { + 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 + }); +}); + +var hasFlag = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; + +const { + env +} = process; +let forceColor; + +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never')) { + forceColor = 0; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { + forceColor = 1; +} + +if ('FORCE_COLOR' in env) { + if (env.FORCE_COLOR === 'true') { + forceColor = 1; + } else if (env.FORCE_COLOR === 'false') { + forceColor = 0; + } else { + forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); + } +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(haveStream, streamIsTTY) { + if (forceColor === 0) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor === undefined) { + return 0; + } + + const min = forceColor || 0; + + if (env.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os__default['default'].release().split('.'); + + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if ('GITHUB_ACTIONS' in env) { + return 1; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream, stream && stream.isTTY); + return translateLevel(level); +} + +var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: translateLevel(supportsColor(true, tty__default['default'].isatty(1))), + stderr: translateLevel(supportsColor(true, tty__default['default'].isatty(2))) +}; + +const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +var util = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +}; + +const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; +const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); + +function unescape(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; + + if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } + + return ESCAPES.get(c) || c; +} + +function parseArguments(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + const number = Number(chunk); + + if (!Number.isNaN(number)) { + results.push(number); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } + + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } + + return current; +} + +var templates = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; // eslint-disable-next-line max-params + + temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); + styles.push({ + inverse, + styles: parseStyle(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } + + return chunks.join(''); +}; + +const { + stdout: stdoutColor, + stderr: stderrColor +} = supportsColor_1; +const { + stringReplaceAll: stringReplaceAll$1, + stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 +} = util; +const { + isArray +} = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping + +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; +const styles = Object.create(null); + +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } // Detect level if not set manually + + + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; + +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } + +} + +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; + + chalk.template.Instance = ChalkClass; + return chalk.template; +}; + +function Chalk(options) { + return chalkFactory(options); +} + +for (const [styleName, style] of Object.entries(ansiStyles)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, { + value: builder + }); + return builder; + } + + }; +} + +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', { + value: builder + }); + return builder; + } + +}; +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + +for (const model of usedModels) { + styles[model] = { + get() { + const { + level + } = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + + }; +} + +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const { + level + } = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + + }; +} + +const proto = Object.defineProperties(() => {}, Object.assign({}, styles, { + level: { + enumerable: true, + + get() { + return this._generator.level; + }, + + set(level) { + this._generator.level = level; + } + + } +})); + +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent + }; +}; + +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + + + return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' ')); + }; // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + + + Object.setPrototypeOf(builder, proto); + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + return builder; +}; + +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } + + let styler = self._styler; + + if (styler === undefined) { + return string; + } + + const { + openAll, + closeAll + } = styler; + + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll$1(string, styler.close, styler.open); + styler = styler.parent; + } + } // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + + + const lfIndex = string.indexOf('\n'); + + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; +}; + +let template; + +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; + + if (!isArray(firstString) || !isArray(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } + + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + + for (let i = 1; i < firstString.length; i++) { + parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i])); + } + + if (template === undefined) { + template = templates; + } + + return template(chalk, parts.join('')); +}; + +Object.defineProperties(Chalk.prototype, styles); +const chalk = Chalk(); // eslint-disable-line new-cap + +chalk.supportsColor = stdoutColor; +chalk.stderr = Chalk({ + level: stderrColor ? stderrColor.level : 0 +}); // eslint-disable-line new-cap + +chalk.stderr.supportsColor = stderrColor; +var source = chalk; + +/** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ +function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + + return result; +} + +var fromPairs_1 = fromPairs; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray$1 = Array.isArray; +var isArray_1 = isArray$1; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +var _freeGlobal = freeGlobal; + +/** Detect free variable `self`. */ + +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +/** Used as a reference to the global object. */ + +var root = _freeGlobal || freeSelf || Function('return this')(); +var _root = root; + +/** Built-in value references. */ + +var Symbol$1 = _root.Symbol; +var _Symbol = Symbol$1; + +/** Used for built-in method references. */ + +var objectProto = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty = objectProto.hasOwnProperty; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + +var nativeObjectToString = objectProto.toString; +/** Built-in value references. */ + +var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + + return result; +} + +var _getRawTag = getRawTag; + +/** Used for built-in method references. */ +var objectProto$1 = Object.prototype; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + +var nativeObjectToString$1 = objectProto$1.toString; +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + +function objectToString(value) { + return nativeObjectToString$1.call(value); +} + +var _objectToString = objectToString; + +/** `Object#toString` result references. */ + +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; +/** Built-in value references. */ + +var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + + return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value); +} + +var _baseGetTag = baseGetTag; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +var isObjectLike_1 = isObjectLike; + +/** `Object#toString` result references. */ + +var symbolTag = '[object Symbol]'; +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + +function isSymbol(value) { + return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag; +} + +var isSymbol_1 = isSymbol; + +/** Used to match property names within property paths. */ + +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + +function isKey(value, object) { + if (isArray_1(value)) { + return false; + } + + var type = typeof value; + + if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { + return true; + } + + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); +} + +var _isKey = isKey; + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +var isObject_1 = isObject; + +/** `Object#toString` result references. */ + +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + +function isFunction(value) { + if (!isObject_1(value)) { + return false; + } // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + + + var tag = _baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +var isFunction_1 = isFunction; + +/** Used to detect overreaching core-js shims. */ + +var coreJsData = _root['__core-js_shared__']; +var _coreJsData = coreJsData; + +/** Used to detect methods masquerading as native. */ + +var maskSrcKey = function () { + var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); + return uid ? 'Symbol(src)_1.' + uid : ''; +}(); +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + + +function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func; +} + +var _isMasked = isMasked; + +/** Used for built-in method references. */ +var funcProto = Function.prototype; +/** Used to resolve the decompiled source of functions. */ + +var funcToString = funcProto.toString; +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + + try { + return func + ''; + } catch (e) {} + } + + return ''; +} + +var _toSource = toSource; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; +/** Used to detect host constructors (Safari). */ + +var reIsHostCtor = /^\[object .+?Constructor\]$/; +/** Used for built-in method references. */ + +var funcProto$1 = Function.prototype, + objectProto$2 = Object.prototype; +/** Used to resolve the decompiled source of functions. */ + +var funcToString$1 = funcProto$1.toString; +/** Used to check objects for own properties. */ + +var hasOwnProperty$1 = objectProto$2.hasOwnProperty; +/** Used to detect if a method is native. */ + +var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + +function baseIsNative(value) { + if (!isObject_1(value) || _isMasked(value)) { + return false; + } + + var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; + return pattern.test(_toSource(value)); +} + +var _baseIsNative = baseIsNative; + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +var _getValue = getValue; + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + +function getNative(object, key) { + var value = _getValue(object, key); + return _baseIsNative(value) ? value : undefined; +} + +var _getNative = getNative; + +/* Built-in method references that are verified to be native. */ + +var nativeCreate = _getNative(Object, 'create'); +var _nativeCreate = nativeCreate; + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + +function hashClear() { + this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; + this.size = 0; +} + +var _hashClear = hashClear; + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +var _hashDelete = hashDelete; + +/** Used to stand-in for `undefined` hash values. */ + +var HASH_UNDEFINED = '__lodash_hash_undefined__'; +/** Used for built-in method references. */ + +var objectProto$3 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$2 = objectProto$3.hasOwnProperty; +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + +function hashGet(key) { + var data = this.__data__; + + if (_nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + + return hasOwnProperty$2.call(data, key) ? data[key] : undefined; +} + +var _hashGet = hashGet; + +/** Used for built-in method references. */ + +var objectProto$4 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$3 = objectProto$4.hasOwnProperty; +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +function hashHas(key) { + var data = this.__data__; + return _nativeCreate ? data[key] !== undefined : hasOwnProperty$3.call(data, key); +} + +var _hashHas = hashHas; + +/** Used to stand-in for `undefined` hash values. */ + +var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value; + return this; +} + +var _hashSet = hashSet; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + this.clear(); + + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} // Add methods to `Hash`. + + +Hash.prototype.clear = _hashClear; +Hash.prototype['delete'] = _hashDelete; +Hash.prototype.get = _hashGet; +Hash.prototype.has = _hashHas; +Hash.prototype.set = _hashSet; +var _Hash = Hash; + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +var _listCacheClear = listCacheClear; + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || value !== value && other !== other; +} + +var eq_1 = eq; + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + +function assocIndexOf(array, key) { + var length = array.length; + + while (length--) { + if (eq_1(array[length][0], key)) { + return length; + } + } + + return -1; +} + +var _assocIndexOf = assocIndexOf; + +/** Used for built-in method references. */ + +var arrayProto = Array.prototype; +/** Built-in value references. */ + +var splice = arrayProto.splice; +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + +function listCacheDelete(key) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + if (index < 0) { + return false; + } + + var lastIndex = data.length - 1; + + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + + --this.size; + return true; +} + +var _listCacheDelete = listCacheDelete; + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + +function listCacheGet(key) { + var data = this.__data__, + index = _assocIndexOf(data, key); + return index < 0 ? undefined : data[index][1]; +} + +var _listCacheGet = listCacheGet; + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +function listCacheHas(key) { + return _assocIndexOf(this.__data__, key) > -1; +} + +var _listCacheHas = listCacheHas; + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + +function listCacheSet(key, value) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + + return this; +} + +var _listCacheSet = listCacheSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + this.clear(); + + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} // Add methods to `ListCache`. + + +ListCache.prototype.clear = _listCacheClear; +ListCache.prototype['delete'] = _listCacheDelete; +ListCache.prototype.get = _listCacheGet; +ListCache.prototype.has = _listCacheHas; +ListCache.prototype.set = _listCacheSet; +var _ListCache = ListCache; + +/* Built-in method references that are verified to be native. */ + +var Map$1 = _getNative(_root, 'Map'); +var _Map = Map$1; + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new _Hash(), + 'map': new (_Map || _ListCache)(), + 'string': new _Hash() + }; +} + +var _mapCacheClear = mapCacheClear; + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null; +} + +var _isKeyable = isKeyable; + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + +function getMapData(map, key) { + var data = map.__data__; + return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; +} + +var _getMapData = getMapData; + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + +function mapCacheDelete(key) { + var result = _getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +var _mapCacheDelete = mapCacheDelete; + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + +function mapCacheGet(key) { + return _getMapData(this, key).get(key); +} + +var _mapCacheGet = mapCacheGet; + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +function mapCacheHas(key) { + return _getMapData(this, key).has(key); +} + +var _mapCacheHas = mapCacheHas; + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + +function mapCacheSet(key, value) { + var data = _getMapData(this, key), + size = data.size; + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +var _mapCacheSet = mapCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + this.clear(); + + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} // Add methods to `MapCache`. + + +MapCache.prototype.clear = _mapCacheClear; +MapCache.prototype['delete'] = _mapCacheDelete; +MapCache.prototype.get = _mapCacheGet; +MapCache.prototype.has = _mapCacheHas; +MapCache.prototype.set = _mapCacheSet; +var _MapCache = MapCache; + +/** Error message constants. */ + +var FUNC_ERROR_TEXT = 'Expected a function'; +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + +function memoize(func, resolver) { + if (typeof func != 'function' || resolver != null && typeof resolver != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + + var memoized = function () { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + + memoized.cache = new (memoize.Cache || _MapCache)(); + return memoized; +} // Expose `MapCache`. + + +memoize.Cache = _MapCache; +var memoize_1 = memoize; + +/** Used as the maximum memoize cache size. */ + +var MAX_MEMOIZE_SIZE = 500; +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + +function memoizeCapped(func) { + var result = memoize_1(func, function (key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + + return key; + }); + var cache = result.cache; + return result; +} + +var _memoizeCapped = memoizeCapped; + +/** Used to match property names within property paths. */ + +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; +/** Used to match backslashes in property paths. */ + +var reEscapeChar = /\\(\\)?/g; +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + +var stringToPath = _memoizeCapped(function (string) { + var result = []; + + if (string.charCodeAt(0) === 46 + /* . */ + ) { + result.push(''); + } + + string.replace(rePropName, function (match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match); + }); + return result; +}); +var _stringToPath = stringToPath; + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + + return result; +} + +var _arrayMap = arrayMap; + +/** Used as references for various `Number` constants. */ + +var INFINITY = 1 / 0; +/** Used to convert symbols to primitives and strings. */ + +var symbolProto = _Symbol ? _Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + + if (isArray_1(value)) { + // Recursively convert values (susceptible to call stack limits). + return _arrayMap(value, baseToString) + ''; + } + + if (isSymbol_1(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + + var result = value + ''; + return result == '0' && 1 / value == -INFINITY ? '-0' : result; +} + +var _baseToString = baseToString; + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + +function toString(value) { + return value == null ? '' : _baseToString(value); +} + +var toString_1 = toString; + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + +function castPath(value, object) { + if (isArray_1(value)) { + return value; + } + + return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); +} + +var _castPath = castPath; + +/** Used as references for various `Number` constants. */ + +var INFINITY$1 = 1 / 0; +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + +function toKey(value) { + if (typeof value == 'string' || isSymbol_1(value)) { + return value; + } + + var result = value + ''; + return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result; +} + +var _toKey = toKey; + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + +function baseGet(object, path) { + path = _castPath(path, object); + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[_toKey(path[index++])]; + } + + return index && index == length ? object : undefined; +} + +var _baseGet = baseGet; + +var defineProperty = function () { + try { + var func = _getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}(); + +var _defineProperty = defineProperty; + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + +function baseAssignValue(object, key, value) { + if (key == '__proto__' && _defineProperty) { + _defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +var _baseAssignValue = baseAssignValue; + +/** Used for built-in method references. */ + +var objectProto$5 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$4 = objectProto$5.hasOwnProperty; +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ + +function assignValue(object, key, value) { + var objValue = object[key]; + + if (!(hasOwnProperty$4.call(object, key) && eq_1(objValue, value)) || value === undefined && !(key in object)) { + _baseAssignValue(object, key, value); + } +} + +var _assignValue = assignValue; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; +/** Used to detect unsigned integer values. */ + +var reIsUint = /^(?:0|[1-9]\d*)$/; +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length; +} + +var _isIndex = isIndex; + +/** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ + +function baseSet(object, path, value, customizer) { + if (!isObject_1(object)) { + return object; + } + + path = _castPath(path, object); + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = _toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + + if (newValue === undefined) { + newValue = isObject_1(objValue) ? objValue : _isIndex(path[index + 1]) ? [] : {}; + } + } + + _assignValue(nested, key, newValue); + nested = nested[key]; + } + + return object; +} + +var _baseSet = baseSet; + +/** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ + +function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = _baseGet(object, path); + + if (predicate(value, path)) { + _baseSet(result, _castPath(path, object), value); + } + } + + return result; +} + +var _basePickBy = basePickBy; + +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} + +var _baseHasIn = baseHasIn; + +/** `Object#toString` result references. */ + +var argsTag = '[object Arguments]'; +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + +function baseIsArguments(value) { + return isObjectLike_1(value) && _baseGetTag(value) == argsTag; +} + +var _baseIsArguments = baseIsArguments; + +/** Used for built-in method references. */ + +var objectProto$6 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$5 = objectProto$6.hasOwnProperty; +/** Built-in value references. */ + +var propertyIsEnumerable = objectProto$6.propertyIsEnumerable; +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + +var isArguments = _baseIsArguments(function () { + return arguments; +}()) ? _baseIsArguments : function (value) { + return isObjectLike_1(value) && hasOwnProperty$5.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); +}; +var isArguments_1 = isArguments; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$1 = 9007199254740991; +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + +function isLength(value) { + return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$1; +} + +var isLength_1 = isLength; + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + +function hasPath(object, path, hasFunc) { + path = _castPath(path, object); + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = _toKey(path[index]); + + if (!(result = object != null && hasFunc(object, key))) { + break; + } + + object = object[key]; + } + + if (result || ++index != length) { + return result; + } + + length = object == null ? 0 : object.length; + return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); +} + +var _hasPath = hasPath; + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + +function hasIn(object, path) { + return object != null && _hasPath(object, path, _baseHasIn); +} + +var hasIn_1 = hasIn; + +/** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + +function basePick(object, paths) { + return _basePickBy(object, paths, function (value, path) { + return hasIn_1(object, path); + }); +} + +var _basePick = basePick; + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + + return array; +} + +var _arrayPush = arrayPush; + +/** Built-in value references. */ + +var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + +function isFlattenable(value) { + return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +var _isFlattenable = isFlattenable; + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + predicate || (predicate = _isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + _arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + + return result; +} + +var _baseFlatten = baseFlatten; + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + +function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? _baseFlatten(array, 1) : []; +} + +var flatten_1 = flatten; + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: + return func.call(thisArg); + + case 1: + return func.call(thisArg, args[0]); + + case 2: + return func.call(thisArg, args[0], args[1]); + + case 3: + return func.call(thisArg, args[0], args[1], args[2]); + } + + return func.apply(thisArg, args); +} + +var _apply = apply; + +/* Built-in method references for those with the same name as other `lodash` methods. */ + +var nativeMax = Math.max; +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ + +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? func.length - 1 : start, 0); + return function () { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + + index = -1; + var otherArgs = Array(start + 1); + + while (++index < start) { + otherArgs[index] = args[index]; + } + + otherArgs[start] = transform(array); + return _apply(func, this, otherArgs); + }; +} + +var _overRest = overRest; + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function () { + return value; + }; +} + +var constant_1 = constant; + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +var identity_1 = identity; + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + +var baseSetToString = !_defineProperty ? identity_1 : function (func, string) { + return _defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant_1(string), + 'writable': true + }); +}; +var _baseSetToString = baseSetToString; + +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; +/* Built-in method references for those with the same name as other `lodash` methods. */ + +var nativeNow = Date.now; +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ + +function shortOut(func) { + var count = 0, + lastCalled = 0; + return function () { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + lastCalled = stamp; + + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + + return func.apply(undefined, arguments); + }; +} + +var _shortOut = shortOut; + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + +var setToString = _shortOut(_baseSetToString); +var _setToString = setToString; + +/** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ + +function flatRest(func) { + return _setToString(_overRest(func, undefined, flatten_1), func + ''); +} + +var _flatRest = flatRest; + +/** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ + +var pick = _flatRest(function (object, paths) { + return object == null ? {} : _basePick(object, paths); +}); +var pick_1 = pick; + +/** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ +function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + + return accumulator; +} + +var _arrayAggregator = arrayAggregator; + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function (object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + + return object; + }; +} + +var _createBaseFor = createBaseFor; + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + +var baseFor = _createBaseFor(); +var _baseFor = baseFor; + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + + return result; +} + +var _baseTimes = baseTimes; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +var stubFalse_1 = stubFalse; + +var isBuffer_1 = createCommonjsModule(function (module, exports) { + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + /** Detect free variable `module`. */ + + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + /** Detect the popular CommonJS extension `module.exports`. */ + + var moduleExports = freeModule && freeModule.exports === freeExports; + /** Built-in value references. */ + + var Buffer = moduleExports ? _root.Buffer : undefined; + /* Built-in method references for those with the same name as other `lodash` methods. */ + + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + + var isBuffer = nativeIsBuffer || stubFalse_1; + module.exports = isBuffer; +}); + +/** `Object#toString` result references. */ + +var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag$1 = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; +/** Used to identify `toStringTag` values of typed arrays. */ + +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + +function baseIsTypedArray(value) { + return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; +} + +var _baseIsTypedArray = baseIsTypedArray; + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function (value) { + return func(value); + }; +} + +var _baseUnary = baseUnary; + +var _nodeUtil = createCommonjsModule(function (module, exports) { + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + /** Detect free variable `module`. */ + + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + /** Detect the popular CommonJS extension `module.exports`. */ + + var moduleExports = freeModule && freeModule.exports === freeExports; + /** Detect free variable `process` from Node.js. */ + + var freeProcess = moduleExports && _freeGlobal.process; + /** Used to access faster Node.js helpers. */ + + var nodeUtil = function () { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } // Legacy `process.binding('util')` for Node.js < 10. + + + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }(); + + module.exports = nodeUtil; +}); + +/* Node.js helper references. */ + +var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + +var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; +var isTypedArray_1 = isTypedArray; + +/** Used for built-in method references. */ + +var objectProto$7 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$6 = objectProto$7.hasOwnProperty; +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + +function arrayLikeKeys(value, inherited) { + var isArr = isArray_1(value), + isArg = !isArr && isArguments_1(value), + isBuff = !isArr && !isArg && isBuffer_1(value), + isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? _baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$6.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. + isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays. + isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties. + _isIndex(key, length)))) { + result.push(key); + } + } + + return result; +} + +var _arrayLikeKeys = arrayLikeKeys; + +/** Used for built-in method references. */ +var objectProto$8 = Object.prototype; +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8; + return value === proto; +} + +var _isPrototype = isPrototype; + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function (arg) { + return func(transform(arg)); + }; +} + +var _overArg = overArg; + +/* Built-in method references for those with the same name as other `lodash` methods. */ + +var nativeKeys = _overArg(Object.keys, Object); +var _nativeKeys = nativeKeys; + +/** Used for built-in method references. */ + +var objectProto$9 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$7 = objectProto$9.hasOwnProperty; +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + +function baseKeys(object) { + if (!_isPrototype(object)) { + return _nativeKeys(object); + } + + var result = []; + + for (var key in Object(object)) { + if (hasOwnProperty$7.call(object, key) && key != 'constructor') { + result.push(key); + } + } + + return result; +} + +var _baseKeys = baseKeys; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + +function isArrayLike(value) { + return value != null && isLength_1(value.length) && !isFunction_1(value); +} + +var isArrayLike_1 = isArrayLike; + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + +function keys(object) { + return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); +} + +var keys_1 = keys; + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + +function baseForOwn(object, iteratee) { + return object && _baseFor(object, iteratee, keys_1); +} + +var _baseForOwn = baseForOwn; + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + +function createBaseEach(eachFunc, fromRight) { + return function (collection, iteratee) { + if (collection == null) { + return collection; + } + + if (!isArrayLike_1(collection)) { + return eachFunc(collection, iteratee); + } + + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while (fromRight ? index-- : ++index < length) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + + return collection; + }; +} + +var _createBaseEach = createBaseEach; + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + +var baseEach = _createBaseEach(_baseForOwn); +var _baseEach = baseEach; + +/** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + +function baseAggregator(collection, setter, iteratee, accumulator) { + _baseEach(collection, function (value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; +} + +var _baseAggregator = baseAggregator; + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + +function stackClear() { + this.__data__ = new _ListCache(); + this.size = 0; +} + +var _stackClear = stackClear; + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + this.size = data.size; + return result; +} + +var _stackDelete = stackDelete; + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +var _stackGet = stackGet; + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +var _stackHas = stackHas; + +/** Used as the size to enable large array optimizations. */ + +var LARGE_ARRAY_SIZE = 200; +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + +function stackSet(key, value) { + var data = this.__data__; + + if (data instanceof _ListCache) { + var pairs = data.__data__; + + if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + + data = this.__data__ = new _MapCache(pairs); + } + + data.set(key, value); + this.size = data.size; + return this; +} + +var _stackSet = stackSet; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + +function Stack(entries) { + var data = this.__data__ = new _ListCache(entries); + this.size = data.size; +} // Add methods to `Stack`. + + +Stack.prototype.clear = _stackClear; +Stack.prototype['delete'] = _stackDelete; +Stack.prototype.get = _stackGet; +Stack.prototype.has = _stackHas; +Stack.prototype.set = _stackSet; +var _Stack = Stack; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + + return this; +} + +var _setCacheAdd = setCacheAdd; + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +var _setCacheHas = setCacheHas; + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + this.__data__ = new _MapCache(); + + while (++index < length) { + this.add(values[index]); + } +} // Add methods to `SetCache`. + + +SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; +SetCache.prototype.has = _setCacheHas; +var _SetCache = SetCache; + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + + return false; +} + +var _arraySome = arraySome; + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +var _cacheHas = cacheHas; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } // Check that cyclic values are equal. + + + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + + var index = -1, + result = true, + seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined; + stack.set(array, other); + stack.set(other, array); // Ignore non-index properties. + + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); + } + + if (compared !== undefined) { + if (compared) { + continue; + } + + result = false; + break; + } // Recursively compare arrays (susceptible to call stack limits). + + + if (seen) { + if (!_arraySome(other, function (othValue, othIndex) { + if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + result = false; + break; + } + } + + stack['delete'](array); + stack['delete'](other); + return result; +} + +var _equalArrays = equalArrays; + +/** Built-in value references. */ + +var Uint8Array = _root.Uint8Array; +var _Uint8Array = Uint8Array; + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + map.forEach(function (value, key) { + result[++index] = [key, value]; + }); + return result; +} + +var _mapToArray = mapToArray; + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + set.forEach(function (value) { + result[++index] = value; + }); + return result; +} + +var _setToArray = setToArray; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; +/** `Object#toString` result references. */ + +var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + mapTag$1 = '[object Map]', + numberTag$1 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$1 = '[object Set]', + stringTag$1 = '[object String]', + symbolTag$1 = '[object Symbol]'; +var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$1 = '[object DataView]'; +/** Used to convert symbols to primitives and strings. */ + +var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, + symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag$1: + if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { + return false; + } + + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$1: + if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { + return false; + } + + return true; + + case boolTag$1: + case dateTag$1: + case numberTag$1: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq_1(+object, +other); + + case errorTag$1: + return object.name == other.name && object.message == other.message; + + case regexpTag$1: + case stringTag$1: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == other + ''; + + case mapTag$1: + var convert = _mapToArray; + + case setTag$1: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = _setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } // Assume cyclic values are equal. + + + var stacked = stack.get(object); + + if (stacked) { + return stacked == other; + } + + bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). + + stack.set(object, other); + var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$1: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + + } + + return false; +} + +var _equalByTag = equalByTag; + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); +} + +var _baseGetAllKeys = baseGetAllKeys; + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + + return result; +} + +var _arrayFilter = arrayFilter; + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +var stubArray_1 = stubArray; + +/** Used for built-in method references. */ + +var objectProto$a = Object.prototype; +/** Built-in value references. */ + +var propertyIsEnumerable$1 = objectProto$a.propertyIsEnumerable; +/* Built-in method references for those with the same name as other `lodash` methods. */ + +var nativeGetSymbols = Object.getOwnPropertySymbols; +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + +var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) { + if (object == null) { + return []; + } + + object = Object(object); + return _arrayFilter(nativeGetSymbols(object), function (symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); +}; +var _getSymbols = getSymbols; + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + +function getAllKeys(object) { + return _baseGetAllKeys(object, keys_1, _getSymbols); +} + +var _getAllKeys = getAllKeys; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$2 = 1; +/** Used for built-in method references. */ + +var objectProto$b = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$8 = objectProto$b.hasOwnProperty; +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = _getAllKeys(object), + objLength = objProps.length, + othProps = _getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + + var index = objLength; + + while (index--) { + var key = objProps[index]; + + if (!(isPartial ? key in other : hasOwnProperty$8.call(other, key))) { + return false; + } + } // Check that cyclic values are equal. + + + var objStacked = stack.get(object); + var othStacked = stack.get(other); + + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + + var result = true; + stack.set(object, other); + stack.set(other, object); + var skipCtor = isPartial; + + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); + } // Recursively compare objects (susceptible to call stack limits). + + + if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { + result = false; + break; + } + + skipCtor || (skipCtor = key == 'constructor'); + } + + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. + + if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + + stack['delete'](object); + stack['delete'](other); + return result; +} + +var _equalObjects = equalObjects; + +/* Built-in method references that are verified to be native. */ + +var DataView = _getNative(_root, 'DataView'); +var _DataView = DataView; + +/* Built-in method references that are verified to be native. */ + +var Promise$1 = _getNative(_root, 'Promise'); +var _Promise = Promise$1; + +/* Built-in method references that are verified to be native. */ + +var Set$1 = _getNative(_root, 'Set'); +var _Set = Set$1; + +/* Built-in method references that are verified to be native. */ + +var WeakMap$1 = _getNative(_root, 'WeakMap'); +var _WeakMap = WeakMap$1; + +/** `Object#toString` result references. */ + +var mapTag$2 = '[object Map]', + objectTag$1 = '[object Object]', + promiseTag = '[object Promise]', + setTag$2 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; +var dataViewTag$2 = '[object DataView]'; +/** Used to detect maps, sets, and weakmaps. */ + +var dataViewCtorString = _toSource(_DataView), + mapCtorString = _toSource(_Map), + promiseCtorString = _toSource(_Promise), + setCtorString = _toSource(_Set), + weakMapCtorString = _toSource(_WeakMap); +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + +var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + +if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) { + getTag = function (value) { + var result = _baseGetTag(value), + Ctor = result == objectTag$1 ? value.constructor : undefined, + ctorString = Ctor ? _toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag$2; + + case mapCtorString: + return mapTag$2; + + case promiseCtorString: + return promiseTag; + + case setCtorString: + return setTag$2; + + case weakMapCtorString: + return weakMapTag$1; + } + } + + return result; + }; +} + +var _getTag = getTag; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$3 = 1; +/** `Object#toString` result references. */ + +var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + objectTag$2 = '[object Object]'; +/** Used for built-in method references. */ + +var objectProto$c = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$9 = objectProto$c.hasOwnProperty; +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray_1(object), + othIsArr = isArray_1(other), + objTag = objIsArr ? arrayTag$1 : _getTag(object), + othTag = othIsArr ? arrayTag$1 : _getTag(other); + objTag = objTag == argsTag$2 ? objectTag$2 : objTag; + othTag = othTag == argsTag$2 ? objectTag$2 : othTag; + var objIsObj = objTag == objectTag$2, + othIsObj = othTag == objectTag$2, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer_1(object)) { + if (!isBuffer_1(other)) { + return false; + } + + objIsArr = true; + objIsObj = false; + } + + if (isSameTag && !objIsObj) { + stack || (stack = new _Stack()); + return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + stack || (stack = new _Stack()); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + + if (!isSameTag) { + return false; + } + + stack || (stack = new _Stack()); + return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +var _baseIsEqualDeep = baseIsEqualDeep; + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + + if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) { + return value !== value && other !== other; + } + + return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +var _baseIsEqual = baseIsEqual; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + + object = Object(object); + + while (index--) { + var data = matchData[index]; + + if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { + return false; + } + } + + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new _Stack(); + + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + + if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) { + return false; + } + } + } + + return true; +} + +var _baseIsMatch = baseIsMatch; + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + +function isStrictComparable(value) { + return value === value && !isObject_1(value); +} + +var _isStrictComparable = isStrictComparable; + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + +function getMatchData(object) { + var result = keys_1(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + result[length] = [key, value, _isStrictComparable(value)]; + } + + return result; +} + +var _getMatchData = getMatchData; + +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function (object) { + if (object == null) { + return false; + } + + return object[key] === srcValue && (srcValue !== undefined || key in Object(object)); + }; +} + +var _matchesStrictComparable = matchesStrictComparable; + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + +function baseMatches(source) { + var matchData = _getMatchData(source); + + if (matchData.length == 1 && matchData[0][2]) { + return _matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + + return function (object) { + return object === source || _baseIsMatch(object, source, matchData); + }; +} + +var _baseMatches = baseMatches; + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + +function get(object, path, defaultValue) { + var result = object == null ? undefined : _baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +var get_1 = get; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + +function baseMatchesProperty(path, srcValue) { + if (_isKey(path) && _isStrictComparable(srcValue)) { + return _matchesStrictComparable(_toKey(path), srcValue); + } + + return function (object) { + var objValue = get_1(object, path); + return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; +} + +var _baseMatchesProperty = baseMatchesProperty; + +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function (object) { + return object == null ? undefined : object[key]; + }; +} + +var _baseProperty = baseProperty; + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + +function basePropertyDeep(path) { + return function (object) { + return _baseGet(object, path); + }; +} + +var _basePropertyDeep = basePropertyDeep; + +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + +function property(path) { + return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); +} + +var property_1 = property; + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + + if (value == null) { + return identity_1; + } + + if (typeof value == 'object') { + return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); + } + + return property_1(value); +} + +var _baseIteratee = baseIteratee; + +/** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + +function createAggregator(setter, initializer) { + return function (collection, iteratee) { + var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator, + accumulator = initializer ? initializer() : {}; + return func(collection, setter, _baseIteratee(iteratee), accumulator); + }; +} + +var _createAggregator = createAggregator; + +/** Used for built-in method references. */ + +var objectProto$d = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$a = objectProto$d.hasOwnProperty; +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + +var groupBy = _createAggregator(function (result, value, key) { + if (hasOwnProperty$a.call(result, key)) { + result[key].push(value); + } else { + _baseAssignValue(result, key, [value]); + } +}); +var groupBy_1 = groupBy; + +/** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + +var partition = _createAggregator(function (result, value, key) { + result[key ? 0 : 1].push(value); +}, function () { + return [[], []]; +}); +var partition_1 = partition; + +var thirdParty = require("./third-party"); + +var prettierInternal = src.__internal; + +var minimist = function (args, opts) { + if (!opts) opts = {}; + var flags = { + bools: {}, + strings: {}, + unknownFn: null + }; + + if (typeof opts['unknown'] === 'function') { + flags.unknownFn = opts['unknown']; + } + + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) { + flags.allBools = true; + } else { + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + }); + } + + var aliases = {}; + Object.keys(opts.alias || {}).forEach(function (key) { + aliases[key] = [].concat(opts.alias[key]); + aliases[key].forEach(function (x) { + aliases[x] = [key].concat(aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + [].concat(opts.string).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + + if (aliases[key]) { + flags.strings[aliases[key]] = true; + } + }); + var defaults = opts['default'] || {}; + var argv = { + _: [] + }; + Object.keys(flags.bools).forEach(function (key) { + setArg(key, defaults[key] === undefined ? false : defaults[key]); + }); + var notFlags = []; + + if (args.indexOf('--') !== -1) { + notFlags = args.slice(args.indexOf('--') + 1); + args = args.slice(0, args.indexOf('--')); + } + + function argDefined(key, arg) { + return flags.allBools && /^--[^=]+$/.test(arg) || flags.strings[key] || flags.bools[key] || aliases[key]; + } + + function setArg(key, val, arg) { + if (arg && flags.unknownFn && !argDefined(key, arg)) { + if (flags.unknownFn(arg) === false) return; + } + + var value = !flags.strings[key] && isNumber(val) ? Number(val) : val; + setKey(argv, key.split('.'), value); + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), value); + }); + } + + function setKey(obj, keys, value) { + var o = obj; + + for (var i = 0; i < keys.length - 1; i++) { + var key = keys[i]; + if (key === '__proto__') return; + if (o[key] === undefined) o[key] = {}; + if (o[key] === Object.prototype || o[key] === Number.prototype || o[key] === String.prototype) o[key] = {}; + if (o[key] === Array.prototype) o[key] = []; + o = o[key]; + } + + var key = keys[keys.length - 1]; + if (key === '__proto__') return; + if (o === Object.prototype || o === Number.prototype || o === String.prototype) o = {}; + if (o === Array.prototype) o = []; + + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') { + o[key] = value; + } else if (Array.isArray(o[key])) { + o[key].push(value); + } else { + o[key] = [o[key], value]; + } + } + + function aliasIsBoolean(key) { + return aliases[key].some(function (x) { + return flags.bools[x]; + }); + } + + for (var i = 0; i < args.length; i++) { + var arg = args[i]; + + if (/^--.+=/.test(arg)) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/); + var key = m[1]; + var value = m[2]; + + if (flags.bools[key]) { + value = value !== 'false'; + } + + setArg(key, value, arg); + } else if (/^--no-.+/.test(arg)) { + var key = arg.match(/^--no-(.+)/)[1]; + setArg(key, false, arg); + } else if (/^--.+/.test(arg)) { + var key = arg.match(/^--(.+)/)[1]; + var next = args[i + 1]; + + if (next !== undefined && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, next, arg); + i++; + } else if (/^(true|false)$/.test(next)) { + setArg(key, next === 'true', arg); + i++; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } else if (/^-[^-]+/.test(arg)) { + var letters = arg.slice(1, -1).split(''); + var broken = false; + + for (var j = 0; j < letters.length; j++) { + var next = arg.slice(j + 2); + + if (next === '-') { + setArg(letters[j], next, arg); + continue; + } + + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) { + setArg(letters[j], next.split('=')[1], arg); + broken = true; + break; + } + + if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) { + setArg(letters[j], next, arg); + broken = true; + break; + } + + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], arg.slice(j + 2), arg); + broken = true; + break; + } else { + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg); + } + } + + var key = arg.slice(-1)[0]; + + if (!broken && key !== '-') { + if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)) { + setArg(key, args[i + 1], arg); + i++; + } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) { + setArg(key, args[i + 1] === 'true', arg); + i++; + } else { + setArg(key, flags.strings[key] ? '' : true, arg); + } + } + } else { + if (!flags.unknownFn || flags.unknownFn(arg) !== false) { + argv._.push(flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)); + } + + if (opts.stopEarly) { + argv._.push.apply(argv._, args.slice(i + 1)); + + break; + } + } + } + + Object.keys(defaults).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) { + setKey(argv, key.split('.'), defaults[key]); + (aliases[key] || []).forEach(function (x) { + setKey(argv, x.split('.'), defaults[key]); + }); + } + }); + + if (opts['--']) { + argv['--'] = new Array(); + notFlags.forEach(function (key) { + argv['--'].push(key); + }); + } else { + notFlags.forEach(function (key) { + argv._.push(key); + }); + } + + return argv; +}; + +function hasKey(obj, keys) { + var o = obj; + keys.slice(0, -1).forEach(function (key) { + o = o[key] || {}; + }); + var key = keys[keys.length - 1]; + return key in o; +} + +function isNumber(x) { + if (typeof x === 'number') return true; + if (/^0x[0-9a-f]+$/i.test(x)) return true; + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +const PLACEHOLDER = null; +/** + * unspecified boolean flag without default value is parsed as `undefined` instead of `false` + */ + +var minimist_1 = function (args, options) { + const boolean = options.boolean || []; + const defaults = options.default || {}; + const booleanWithoutDefault = boolean.filter(key => !(key in defaults)); + const newDefaults = Object.assign({}, defaults, fromPairs_1(booleanWithoutDefault.map(key => [key, PLACEHOLDER]))); + const parsed = minimist(args, Object.assign({}, options, { + default: newDefaults + })); + return fromPairs_1(Object.entries(parsed).filter(([, value]) => value !== PLACEHOLDER)); +}; + +var array = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.splitWhen = exports.flatten = void 0; + + function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); + } + + exports.flatten = flatten; + + function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } else { + result[groupIndex].push(item); + } + } + + return result; + } + + exports.splitWhen = splitWhen; +}); + +var errno = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isEnoentCodeError = void 0; + + function isEnoentCodeError(error) { + return error.code === 'ENOENT'; + } + + exports.isEnoentCodeError = isEnoentCodeError; +}); + +var fs = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.createDirentFromStats = void 0; + + class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } + + } + + function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); + } + + exports.createDirentFromStats = createDirentFromStats; +}); + +var path_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0; + const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ + + const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; + /** + * Designed to work only with simple paths: `dir\\file`. + */ + + function unixify(filepath) { + return filepath.replace(/\\/g, '/'); + } + + exports.unixify = unixify; + + function makeAbsolute(cwd, filepath) { + return path__default['default'].resolve(cwd, filepath); + } + + exports.makeAbsolute = makeAbsolute; + + function escape(pattern) { + return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); + } + + exports.escape = escape; + + function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + + return entry; + } + + exports.removeLeadingDotSegment = removeLeadingDotSegment; +}); + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ +var isExtglob = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + + while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; + +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var chars = { + '{': '}', + '(': ')', + '[': ']' +}; +var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; +var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; + +var isGlob = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var regex = strictRegex; + var match; // optionally relax regex + + if (options && options.strict === false) { + regex = relaxedRegex; + } + + while (match = regex.exec(str)) { + if (match[2]) return true; + var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + + var open = match[1]; + var close = open ? chars[open] : null; + + if (open && close) { + var n = str.indexOf(close, idx); + + if (n !== -1) { + idx = n + 1; + } + } + + str = str.slice(idx); + } + + return false; +}; + +var pathPosixDirname = path__default['default'].posix.dirname; +var isWin32 = os__default['default'].platform() === 'win32'; +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\/]*.*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ + +var globParent = function globParent(str, opts) { + var options = Object.assign({ + flipBackslashes: true + }, opts); // flip windows path separators + + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } // special case for strings ending in enclosure containing path separator + + + if (enclosure.test(str)) { + str += slash; + } // preserves full path in case of trailing path separator + + + str += 'a'; // remove path parts that are globby + + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); // remove escape chars and return result + + + return str.replace(escaped, '$1'); +}; + +var utils = createCommonjsModule(function (module, exports) { + + exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + + return false; + }; + /** + * Find a node of the given type + */ + + + exports.find = (node, type) => node.nodes.find(node => node.type === type); + /** + * Find a node of the given type + */ + + + exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return (Number(max) - Number(min)) / Number(step) >= limit; + }; + /** + * Escape the given node with '\\' before node.value + */ + + + exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if (type && node.type === type || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } + }; + /** + * Returns true if the given brace node should be enclosed in literal braces + */ + + + exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + + if (node.commas >> 0 + node.ranges >> 0 === 0) { + node.invalid = true; + return true; + } + + return false; + }; + /** + * Returns true if a brace node is invalid. + */ + + + exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + + if (block.commas >> 0 + block.ranges >> 0 === 0) { + block.invalid = true; + return true; + } + + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + + return false; + }; + /** + * Returns true if a node is an open or close node + */ + + + exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + + return node.open === true || node.close === true; + }; + /** + * Reduce an array of text nodes. + */ + + + exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; + }, []); + /** + * Flatten an array + */ + + + exports.flatten = (...args) => { + const result = []; + + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); + } + + return result; + }; + + flat(args); + return result; + }; +}); + +var stringify = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils.isOpenOrClose(node)) { + return '\\' + node.value; + } + + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + + return output; + }; + + return stringify(ast); +}; + +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +var isNumber$1 = function (num) { + if (typeof num === 'number') { + return num - num === 0; + } + + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + + return false; +}; + +const toRegexRange = (min, max, options) => { + if (isNumber$1(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber$1(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = Object.assign({ + relaxZeros: true + }, options); + + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + + if (opts.capture) { + return `(${result})`; + } + + if (opts.wrap === false) { + return result; + } + + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { + min, + max, + a, + b + }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && positives.length + negatives.length > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false) || []; + let onlyPositive = filterPatterns(pos, neg, '', false) || []; + let intersected = filterPatterns(neg, pos, '-?', true) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare); + return stops; +} +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { + pattern: start, + count: [], + digits: 0 + }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { + pattern, + count: [count], + digits + }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { + string + } = ele; // only push if _both_ are negative... + + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } // or _both_ are positive + + + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + + return result; +} +/** + * Zip strings + */ + + +function zip(a, b) { + let arr = []; + + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + + return arr; +} + +function compare(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - integer % Math.pow(10, zeros); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${b - a === 1 ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + + case 1: + return relax ? '0?' : '0'; + + case 2: + return relax ? '0{0,2}' : '00'; + + default: + { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} +/** + * Cache + */ + + +toRegexRange.cache = {}; + +toRegexRange.clearCache = () => toRegexRange.cache = {}; +/** + * Expose `toRegexRange` + */ + + +var toRegexRange_1 = toRegexRange; + +const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || typeof value === 'string' && value !== ''; +}; + +const isNumber$2 = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + + while (value[++index] === '0'); + + return index > 0; +}; + +const stringify$1 = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'); + } + + if (toNumber === false) { + return String(input); + } + + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + + if (negative) { + input = input.slice(1); + maxLength--; + } + + while (input.length < maxLength) input = '0' + input; + + return negative ? '-' + input : input; +}; + +const toSequence = (parts, options) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange_1(a, b, Object.assign({ + wrap: false + }, options)); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + + return toRegexRange_1(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } // fix negative zero + + + if (a === 0) a = 0; + if (b === 0) b = 0; + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify$1(start, end, options) === false; + let format = options.transform || transform(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { + negatives: [], + positives: [] + }; + + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({ + wrap: false + }, options)); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if (!isNumber$2(start) && start.length > 1 || !isNumber$2(end) && end.length > 1) { + return invalidRange(start, end, options); + } + + let format = options.transform || (val => String.fromCharCode(val)); + + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { + wrap: false, + options + }); + } + + return range; +}; + +const fill = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill(start, end, 1, { + transform: step + }); + } + + if (isObject$1(step)) { + return fill(start, end, 0, step); + } + + let opts = Object.assign({}, options); + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber$2(step)) { + if (step != null && !isObject$1(step)) return invalidStep(step, opts); + return fill(start, end, 1, step); + } + + if (isNumber$2(start) && isNumber$2(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +var fillRange = fill; + +const compile = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? prefix + node.value : '('; + } + + if (node.type === 'close') { + return invalid ? prefix + node.value : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils.reduce(node.nodes); + let range = fillRange(...args, Object.assign({}, options, { + wrap: false, + toRegex: true + })); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + + return output; + }; + + return walk(ast); +}; + +var compile_1 = compile; + +const append = (queue = '', stash = '', enclose = false) => { + let result = []; + queue = [].concat(queue); + stash = [].concat(stash); + if (!stash.length) return queue; + + if (!queue.length) { + return enclose ? utils.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + } + } + } + + return utils.flatten(result); +}; + +const expand = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils.reduce(node.nodes); + + if (utils.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fillRange(...args, options); + + if (range.length === 0) { + range = stringify(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils.flatten(walk(ast)); +}; + +var expand_1 = expand; + +var constants = { + MAX_LENGTH: 1024 * 64, + // Digits + CHAR_0: '0', + + /* 0 */ + CHAR_9: '9', + + /* 9 */ + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', + + /* A */ + CHAR_LOWERCASE_A: 'a', + + /* a */ + CHAR_UPPERCASE_Z: 'Z', + + /* Z */ + CHAR_LOWERCASE_Z: 'z', + + /* z */ + CHAR_LEFT_PARENTHESES: '(', + + /* ( */ + CHAR_RIGHT_PARENTHESES: ')', + + /* ) */ + CHAR_ASTERISK: '*', + + /* * */ + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', + + /* & */ + CHAR_AT: '@', + + /* @ */ + CHAR_BACKSLASH: '\\', + + /* \ */ + CHAR_BACKTICK: '`', + + /* ` */ + CHAR_CARRIAGE_RETURN: '\r', + + /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', + + /* ^ */ + CHAR_COLON: ':', + + /* : */ + CHAR_COMMA: ',', + + /* , */ + CHAR_DOLLAR: '$', + + /* . */ + CHAR_DOT: '.', + + /* . */ + CHAR_DOUBLE_QUOTE: '"', + + /* " */ + CHAR_EQUAL: '=', + + /* = */ + CHAR_EXCLAMATION_MARK: '!', + + /* ! */ + CHAR_FORM_FEED: '\f', + + /* \f */ + CHAR_FORWARD_SLASH: '/', + + /* / */ + CHAR_HASH: '#', + + /* # */ + CHAR_HYPHEN_MINUS: '-', + + /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', + + /* < */ + CHAR_LEFT_CURLY_BRACE: '{', + + /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', + + /* [ */ + CHAR_LINE_FEED: '\n', + + /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', + + /* \u00A0 */ + CHAR_PERCENT: '%', + + /* % */ + CHAR_PLUS: '+', + + /* + */ + CHAR_QUESTION_MARK: '?', + + /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', + + /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', + + /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', + + /* ] */ + CHAR_SEMICOLON: ';', + + /* ; */ + CHAR_SINGLE_QUOTE: '\'', + + /* ' */ + CHAR_SPACE: ' ', + + /* */ + CHAR_TAB: '\t', + + /* \t */ + CHAR_UNDERSCORE: '_', + + /* _ */ + CHAR_VERTICAL_LINE: '|', + + /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' + /* \uFEFF */ + +}; + +/** + * Constants + */ + + +const { + MAX_LENGTH, + CHAR_BACKSLASH, + + /* \ */ + CHAR_BACKTICK, + + /* ` */ + CHAR_COMMA, + + /* , */ + CHAR_DOT, + + /* . */ + CHAR_LEFT_PARENTHESES, + + /* ( */ + CHAR_RIGHT_PARENTHESES, + + /* ) */ + CHAR_LEFT_CURLY_BRACE, + + /* { */ + CHAR_RIGHT_CURLY_BRACE, + + /* } */ + CHAR_LEFT_SQUARE_BRACKET, + + /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, + + /* ] */ + CHAR_DOUBLE_QUOTE, + + /* " */ + CHAR_SINGLE_QUOTE, + + /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = constants; +/** + * parse + */ + +const parse = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH; + + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { + type: 'root', + input, + nodes: [] + }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + /** + * Helpers + */ + + const advance = () => input[index++]; + + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ + type: 'bos' + }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + /** + * Escaped chars + */ + + + if (value === CHAR_BACKSLASH) { + push({ + type: 'text', + value: (options.keepEscaping ? value : '') + advance() + }); + continue; + } + /** + * Right square bracket (literal): ']' + */ + + + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ + type: 'text', + value: '\\' + value + }); + continue; + } + /** + * Left square bracket: '[' + */ + + + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Parentheses + */ + + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ + type: 'paren', + nodes: [] + }); + stack.push(block); + push({ + type: 'text', + value + }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ + type: 'text', + value + }); + continue; + } + + block = stack.pop(); + push({ + type: 'text', + value + }); + block = stack[stack.length - 1]; + continue; + } + /** + * Quotes: '|"|` + */ + + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Left curly brace: '{' + */ + + + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + block = push(brace); + stack.push(block); + push({ + type: 'open', + value + }); + continue; + } + /** + * Right curly brace: '}' + */ + + + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ + type: 'text', + value + }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + push({ + type, + value + }); + depth--; + block = stack[stack.length - 1]; + continue; + } + /** + * Comma: ',' + */ + + + if (value === CHAR_COMMA && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { + type: 'text', + value: stringify(block) + }]; + } + + push({ + type: 'comma', + value + }); + block.commas++; + continue; + } + /** + * Dot: '.' + */ + + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ + type: 'text', + value + }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ + type: 'dot', + value + }); + continue; + } + /** + * Text + */ + + + push({ + type: 'text', + value + }); + } // Mark imbalanced braces and brackets as invalid + + + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); // get the location of the block on parent.nodes (block's siblings) + + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes + + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ + type: 'eos' + }); + return ast; +}; + +var parse_1 = parse; + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces.create(pattern, options); + + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + + return output; +}; +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + + +braces.parse = (input, options = {}) => parse_1(input, options); +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + + +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify(braces.parse(input, options), options); + } + + return stringify(input, options); +}; +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + + +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + return compile_1(input, options); +}; +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + + +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + let result = expand_1(input, options); // filter out empty strings if specified + + if (options.noempty === true) { + result = result.filter(Boolean); + } // filter out duplicates if specified + + + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + + +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); +}; +/** + * Expose "braces" + */ + + +var braces_1 = braces; + +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, { + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}); +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; +var constants$1 = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + // Digits + CHAR_0: 48, + + /* 0 */ + CHAR_9: 57, + + /* 9 */ + // Alphabet chars. + CHAR_UPPERCASE_A: 65, + + /* A */ + CHAR_LOWERCASE_A: 97, + + /* a */ + CHAR_UPPERCASE_Z: 90, + + /* Z */ + CHAR_LOWERCASE_Z: 122, + + /* z */ + CHAR_LEFT_PARENTHESES: 40, + + /* ( */ + CHAR_RIGHT_PARENTHESES: 41, + + /* ) */ + CHAR_ASTERISK: 42, + + /* * */ + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, + + /* & */ + CHAR_AT: 64, + + /* @ */ + CHAR_BACKWARD_SLASH: 92, + + /* \ */ + CHAR_CARRIAGE_RETURN: 13, + + /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, + + /* ^ */ + CHAR_COLON: 58, + + /* : */ + CHAR_COMMA: 44, + + /* , */ + CHAR_DOT: 46, + + /* . */ + CHAR_DOUBLE_QUOTE: 34, + + /* " */ + CHAR_EQUAL: 61, + + /* = */ + CHAR_EXCLAMATION_MARK: 33, + + /* ! */ + CHAR_FORM_FEED: 12, + + /* \f */ + CHAR_FORWARD_SLASH: 47, + + /* / */ + CHAR_GRAVE_ACCENT: 96, + + /* ` */ + CHAR_HASH: 35, + + /* # */ + CHAR_HYPHEN_MINUS: 45, + + /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, + + /* < */ + CHAR_LEFT_CURLY_BRACE: 123, + + /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, + + /* [ */ + CHAR_LINE_FEED: 10, + + /* \n */ + CHAR_NO_BREAK_SPACE: 160, + + /* \u00A0 */ + CHAR_PERCENT: 37, + + /* % */ + CHAR_PLUS: 43, + + /* + */ + CHAR_QUESTION_MARK: 63, + + /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, + + /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, + + /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, + + /* ] */ + CHAR_SEMICOLON: 59, + + /* ; */ + CHAR_SINGLE_QUOTE: 39, + + /* ' */ + CHAR_SPACE: 32, + + /* */ + CHAR_TAB: 9, + + /* \t */ + CHAR_UNDERSCORE: 95, + + /* _ */ + CHAR_VERTICAL_LINE: 124, + + /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, + + /* \uFEFF */ + SEP: path__default['default'].sep, + + /** + * Create EXTGLOB_CHARS + */ + extglobChars(chars) { + return { + '!': { + type: 'negate', + open: '(?:(?!(?:', + close: `))${chars.STAR})` + }, + '?': { + type: 'qmark', + open: '(?:', + close: ')?' + }, + '+': { + type: 'plus', + open: '(?:', + close: ')+' + }, + '*': { + type: 'star', + open: '(?:', + close: ')*' + }, + '@': { + type: 'at', + open: '(?:', + close: ')' + } + }; + }, + + /** + * Create GLOB_CHARS + */ + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } + +}; + +var utils$1 = createCommonjsModule(function (module, exports) { + + const win32 = process.platform === 'win32'; + const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = constants$1; + + exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + + exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); + + exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); + + exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); + + exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + + exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); + }; + + exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + + if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) { + return true; + } + + return false; + }; + + exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + + return win32 === true || path__default['default'].sep === '\\'; + }; + + exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; + }; + + exports.removePrefix = (input, state = {}) => { + let output = input; + + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + + return output; + }; + + exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + let output = `${prepend}(?:${input})${append}`; + + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + + return output; + }; +}); + +const { + CHAR_ASTERISK, + + /* * */ + CHAR_AT, + + /* @ */ + CHAR_BACKWARD_SLASH, + + /* \ */ + CHAR_COMMA: CHAR_COMMA$1, + + /* , */ + CHAR_DOT: CHAR_DOT$1, + + /* . */ + CHAR_EXCLAMATION_MARK, + + /* ! */ + CHAR_FORWARD_SLASH, + + /* / */ + CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, + + /* { */ + CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, + + /* ( */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, + + /* [ */ + CHAR_PLUS, + + /* + */ + CHAR_QUESTION_MARK, + + /* ? */ + CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, + + /* } */ + CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, + + /* ) */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 + /* ] */ + +} = constants$1; + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), and `negated` (true if the path starts with `!`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + + +const scan = (input, options) => { + const opts = options || {}; + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { + value: '', + depth: 0, + isGlob: false + }; + + const eos = () => index >= length; + + const peek = () => str.charCodeAt(index + 1); + + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE$1) { + braceEscaped = true; + } + + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE$1) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE$1) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { + value: '', + depth: 0, + isGlob: false + }; + if (finished === true) continue; + + if (prev === CHAR_DOT$1 && index === start + 1) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES$1) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + continue; + } + + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET$1) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES$1) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES$1) { + finished = true; + break; + } + } + + continue; + } + + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils$1.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$1.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + + if (!isPathSeparator(code)) { + tokens.push(token); + } + + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + + if (idx !== 0 || value !== '') { + parts.push(value); + } + + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +var scan_1 = scan; + +/** + * Constants + */ + + +const { + MAX_LENGTH: MAX_LENGTH$1, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants$1; +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils$1.escapeRegex(v)).join('..'); + } + + return value; +}; +/** + * Create the message for a syntax error + */ + + +const syntaxError = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + + +const parse$1 = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + const opts = Object.assign({}, options); + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + let len = input.length; + + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { + type: 'bos', + value: '', + output: opts.prepend || '' + }; + const tokens = [bos]; + const capture = opts.capture ? '' : '?:'; + const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix + + const PLATFORM_CHARS = constants$1.globChars(win32); + const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS); + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } // minimatch options support + + + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + input = utils$1.removePrefix(input, state); + len = input.length; + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + + const peek = state.peek = (n = 1) => input[state.index + n]; + + const advance = state.advance = () => input[++state.index]; + + const remaining = () => input.slice(state.index + 1); + + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = Object.assign({}, EXTGLOB_CHARS[value], { + conditions: 1, + inner: '' + }); + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + increment('parens'); + push({ + type, + value, + output: state.output ? '' : ONE_CHAR + }); + push({ + type: 'paren', + extglob: true, + value: advance(), + output + }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.prev.type === 'bos' && eos()) { + state.negatedExtglob = true; + } + } + + push({ + type: 'paren', + extglob: true, + value, + output + }); + decrement('parens'); + }; + /** + * Fast paths + */ + + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + + return star; + } + + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : m ? '\\' : ''; + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils$1.wrapOutput(output, state, options); + return state; + } + /** + * Tokenize input until we reach end-of-string + */ + + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + /** + * Escaped characters + */ + + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ + type: 'text', + value + }); + continue; + } // collapse slashes to reduce potential for exploits + + + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance() || ''; + } else { + value += advance() || ''; + } + + if (state.brackets === 0) { + push({ + type: 'text', + value + }); + continue; + } + } + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE$1[rest]; + + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + + continue; + } + } + } + } + + if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ + value + }); + continue; + } + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + + if (state.quotes === 1 && value !== '"') { + value = utils$1.escapeRegex(value); + prev.value += value; + append({ + value + }); + continue; + } + /** + * Double quotes + */ + + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + + if (opts.keepQuotes === true) { + push({ + type: 'text', + value + }); + } + + continue; + } + /** + * Parentheses + */ + + + if (value === '(') { + increment('parens'); + push({ + type: 'paren', + value + }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ + type: 'paren', + value, + output: state.parens ? ')' : '\\)' + }); + decrement('parens'); + continue; + } + /** + * Square brackets + */ + + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ + type: 'bracket', + value + }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) { + push({ + type: 'text', + value, + output: `\\${value}` + }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError('opening', '[')); + } + + push({ + type: 'text', + value, + output: `\\${value}` + }); + continue; + } + + decrement('brackets'); + const prevValue = prev.value.slice(1); + + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ + value + }); // when literal brackets are explicitly disabled + // assume we should match with a regex character class + + if (opts.literalBrackets === false || utils$1.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$1.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } // when the user specifies nothing, try to match both + + + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + /** + * Braces + */ + + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ + type: 'text', + value, + output: value + }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + + if (arr[i].type === 'brace') { + break; + } + + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + + for (const t of toks) { + state.output += t.output || t.value; + } + } + + push({ + type: 'brace', + value, + output + }); + decrement('braces'); + braces.pop(); + continue; + } + /** + * Pipes + */ + + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Commas + */ + + + if (value === ',') { + let output = value; + const brace = braces[braces.length - 1]; + + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ + type: 'comma', + value, + output + }); + continue; + } + /** + * Slashes + */ + + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + + continue; + } + + push({ + type: 'slash', + value, + output: SLASH_LITERAL + }); + continue; + } + /** + * Dots + */ + + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ + type: 'text', + value, + output: DOT_LITERAL + }); + continue; + } + + push({ + type: 'dot', + value, + output: DOT_LITERAL + }); + continue; + } + /** + * Question marks + */ + + + if (value === '?') { + const isGroup = prev && prev.value === '('; + + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils$1.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) { + output = `\\${value}`; + } + + push({ + type: 'text', + value, + output + }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ + type: 'qmark', + value, + output: QMARK_NO_DOT + }); + continue; + } + + push({ + type: 'qmark', + value, + output: QMARK + }); + continue; + } + /** + * Exclamation + */ + + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + /** + * Plus + */ + + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if (prev && prev.value === '(' || opts.regex === false) { + push({ + type: 'plus', + value, + output: PLUS_LITERAL + }); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) { + push({ + type: 'plus', + value + }); + continue; + } + + push({ + type: 'plus', + value: PLUS_LITERAL + }); + continue; + } + /** + * Plain text + */ + + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ + type: 'at', + extglob: true, + value, + output: '' + }); + continue; + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Plain text + */ + + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Stars + */ + + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) { + push({ + type: 'star', + value, + output: '' + }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ + type: 'star', + value, + output: '' + }); + continue; + } // strip consecutive `/**/` + + + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + + if (after && after !== '/') { + break; + } + + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + state.output += prior.output + prev.output; + state.globstar = true; + consume(value + advance()); + push({ + type: 'slash', + value: '/', + output: '' + }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ + type: 'slash', + value: '/', + output: '' + }); + continue; + } // remove single star from output + + + state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar + + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; // reset output with globstar + + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { + type: 'star', + value, + output: star + }; + + if (opts.bash === true) { + token.output = '.*?'; + + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ']')); + state.output = utils$1.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', ')')); + state.output = utils$1.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError('closing', '}')); + state.output = utils$1.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ + type: 'maybe_slash', + value: '', + output: `${SLASH_LITERAL}?` + }); + } // rebuild the output if we had to backtrack at any point + + + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + + +parse$1.fastpaths = (input, options) => { + const opts = Object.assign({}, options); + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1; + const len = input.length; + + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils$1.isWindows(options); // create constants based on platform, for windows or posix + + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants$1.globChars(win32); + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { + negated: false, + prefix: '' + }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: + { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + const source = create(match[1]); + if (!source) return; + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils$1.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$1 = parse$1; + +const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val); +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + + +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + + return false; + }; + + return arrayMatcher; + } + + const isState = isObject$2(glob) && glob.tokens && glob.input; + + if (glob === '' || typeof glob !== 'string' && !isState) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils$1.isWindows(options); + const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + + if (opts.ignore) { + const ignoreOpts = Object.assign({}, options, { + ignore: null, + onMatch: null, + onResult: null + }); + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { + isMatch, + match, + output + } = picomatch.test(input, regex, options, { + glob, + posix + }); + const result = { + glob, + state, + regex, + posix, + input, + output, + match, + isMatch + }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + + +picomatch.test = (input, regex, options, { + glob, + posix +} = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { + isMatch: false, + output: '' + }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils$1.toPosixSlashes : null); + let match = input === glob; + let output = match && format ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { + isMatch: Boolean(match), + match, + output + }; +}; +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + + +picomatch.matchBase = (input, glob, options, posix = utils$1.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path__default['default'].basename(input)); +}; +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + + +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse_1$1(pattern, Object.assign({}, options, { + fastpaths: false + })); +}; +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + + +picomatch.scan = (input, options) => scan_1(input, options); +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + + +picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return parsed.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + let source = `${prepend}(?:${parsed.output})${append}`; + + if (parsed && parsed.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch.toRegex(source, options); + + if (returnState === true) { + regex.state = parsed; + } + + return regex; +}; + +picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + const opts = options || {}; + let parsed = { + negated: false, + fastpaths: true + }; + let prefix = ''; + let output; + + if (input.startsWith('./')) { + input = input.slice(2); + prefix = parsed.prefix = './'; + } + + if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + output = parse_1$1.fastpaths(input, options); + } + + if (output === undefined) { + parsed = parse_1$1(input, options); + parsed.prefix = prefix + (parsed.prefix || ''); + } else { + parsed.output = output; + } + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + + +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; +/** + * Picomatch constants. + * @return {Object} + */ + + +picomatch.constants = constants$1; +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch; + +var picomatch$1 = picomatch_1; + +const isEmptyString = val => typeof val === 'string' && (val === '' || val === './'); +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} list List of strings to match. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} options See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + + +const micromatch = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; + + let onResult = state => { + items.add(state.output); + + if (options && options.onResult) { + options.onResult(state); + } + }; + + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, { + onResult + }), true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; + + for (let item of list) { + let matched = isMatch(item, true); + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; + + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } + + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); + + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } + + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } + } + + return matches; +}; +/** + * Backwards compatibility + */ + + +micromatch.match = micromatch; +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch.matcher = (pattern, options) => picomatch$1(pattern, options); +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str); +/** + * Backwards compatibility + */ + + +micromatch.any = micromatch.isMatch; +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; + + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + + let matches = micromatch(list, patterns, Object.assign({}, options, { + onResult + })); + + for (let item of items) { + if (!matches.includes(item)) { + result.add(item); + } + } + + return [...result]; +}; +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public + */ + + +micromatch.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`); + } + + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch.contains(str, p, options)); + } + + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) { + return true; + } + } + + return micromatch.isMatch(str, pattern, Object.assign({}, options, { + contains: true + })); +}; +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + + +micromatch.matchKeys = (obj, patterns, options) => { + if (!utils$1.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + + let keys = micromatch(Object.keys(obj), patterns, options); + let res = {}; + + for (let key of keys) res[key] = obj[key]; + + return res; +}; +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +micromatch.some = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$1(String(pattern), options); + + if (items.some(item => isMatch(item))) { + return true; + } + } + + return false; +}; +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +micromatch.every = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$1(String(pattern), options); + + if (!items.every(item => isMatch(item))) { + return false; + } + } + + return true; +}; +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +micromatch.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`); + } + + return [].concat(patterns).every(p => picomatch$1(p, options)(str)); +}; +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + + +micromatch.capture = (glob, input, options) => { + let posix = utils$1.isWindows(options); + let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, { + capture: true + })); + let match = regex.exec(posix ? utils$1.toPosixSlashes(input) : input); + + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); + } +}; +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + + +micromatch.makeRe = (...args) => picomatch$1.makeRe(...args); +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + + +micromatch.scan = (...args) => picomatch$1.scan(...args); +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ + + +micromatch.parse = (patterns, options) => { + let res = []; + + for (let pattern of [].concat(patterns || [])) { + for (let str of braces_1(String(pattern), options)) { + res.push(picomatch$1.parse(str, options)); + } + } + + return res; +}; +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + + +micromatch.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + + if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) { + return [pattern]; + } + + return braces_1(pattern, options); +}; +/** + * Expand braces + */ + + +micromatch.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch.braces(pattern, Object.assign({}, options, { + expand: true + })); +}; +/** + * Expose micromatch + */ + + +var micromatch_1 = micromatch; + +var pattern = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; + const GLOBSTAR = '**'; + const ESCAPE_SYMBOL = '\\'; + const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; + const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; + const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/; + const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/; + const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; + + function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); + } + + exports.isStaticPattern = isStaticPattern; + + function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + + + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + + if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { + return true; + } + + return false; + } + + exports.isDynamicPattern = isDynamicPattern; + + function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; + } + + exports.convertToPositivePattern = convertToPositivePattern; + + function convertToNegativePattern(pattern) { + return '!' + pattern; + } + + exports.convertToNegativePattern = convertToNegativePattern; + + function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; + } + + exports.isNegativePattern = isNegativePattern; + + function isPositivePattern(pattern) { + return !isNegativePattern(pattern); + } + + exports.isPositivePattern = isPositivePattern; + + function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); + } + + exports.getNegativePatterns = getNegativePatterns; + + function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); + } + + exports.getPositivePatterns = getPositivePatterns; + + function getBaseDirectory(pattern) { + return globParent(pattern, { + flipBackslashes: false + }); + } + + exports.getBaseDirectory = getBaseDirectory; + + function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); + } + + exports.hasGlobStar = hasGlobStar; + + function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); + } + + exports.endsWithSlashGlobStar = endsWithSlashGlobStar; + + function isAffectDepthOfReadingPattern(pattern) { + const basename = path__default['default'].basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); + } + + exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; + + function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); + } + + exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; + + function expandBraceExpansion(pattern) { + return micromatch_1.braces(pattern, { + expand: true, + nodupes: true + }); + } + + exports.expandBraceExpansion = expandBraceExpansion; + + function getPatternParts(pattern, options) { + let { + parts + } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), { + parts: true + })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + + + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + + return parts; + } + + exports.getPatternParts = getPatternParts; + + function makeRe(pattern, options) { + return micromatch_1.makeRe(pattern, options); + } + + exports.makeRe = makeRe; + + function convertPatternsToRe(patterns, options) { + return patterns.map(pattern => makeRe(pattern, options)); + } + + exports.convertPatternsToRe = convertPatternsToRe; + + function matchAny(entry, patternsRe) { + return patternsRe.some(patternRe => patternRe.test(entry)); + } + + exports.matchAny = matchAny; +}); + +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2020 Teambition + * Licensed under the MIT license. + */ + + +const PassThrough = stream__default['default'].PassThrough; +const slice = Array.prototype.slice; +var merge2_1 = merge2; + +function merge2() { + const streamsQueue = []; + const args = slice.call(arguments); + let merging = false; + let options = args[args.length - 1]; + + if (options && !Array.isArray(options) && options.pipe == null) { + args.pop(); + } else { + options = {}; + } + + const doEnd = options.end !== false; + const doPipeError = options.pipeError === true; + + if (options.objectMode == null) { + options.objectMode = true; + } + + if (options.highWaterMark == null) { + options.highWaterMark = 64 * 1024; + } + + const mergedStream = PassThrough(options); + + function addStream() { + for (let i = 0, len = arguments.length; i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)); + } + + mergeStream(); + return this; + } + + function mergeStream() { + if (merging) { + return; + } + + merging = true; + let streams = streamsQueue.shift(); + + if (!streams) { + process.nextTick(endStream); + return; + } + + if (!Array.isArray(streams)) { + streams = [streams]; + } + + let pipesCount = streams.length + 1; + + function next() { + if (--pipesCount > 0) { + return; + } + + merging = false; + mergeStream(); + } + + function pipe(stream) { + function onend() { + stream.removeListener('merge2UnpipeEnd', onend); + stream.removeListener('end', onend); + + if (doPipeError) { + stream.removeListener('error', onerror); + } + + next(); + } + + function onerror(err) { + mergedStream.emit('error', err); + } // skip ended stream + + + if (stream._readableState.endEmitted) { + return next(); + } + + stream.on('merge2UnpipeEnd', onend); + stream.on('end', onend); + + if (doPipeError) { + stream.on('error', onerror); + } + + stream.pipe(mergedStream, { + end: false + }); // compatible for old stream + + stream.resume(); + } + + for (let i = 0; i < streams.length; i++) { + pipe(streams[i]); + } + + next(); + } + + function endStream() { + merging = false; // emit 'queueDrain' when all streams merged. + + mergedStream.emit('queueDrain'); + + if (doEnd) { + mergedStream.end(); + } + } + + mergedStream.setMaxListeners(0); + mergedStream.add = addStream; + mergedStream.on('unpipe', function (stream) { + stream.emit('merge2UnpipeEnd'); + }); + + if (args.length) { + addStream.apply(null, args); + } + + return mergedStream; +} // check and pause streams for pipe. + + +function pauseStreams(streams, options) { + if (!Array.isArray(streams)) { + // Backwards-compat with old-style streams + if (!streams._readableState && streams.pipe) { + streams = streams.pipe(PassThrough(options)); + } + + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error('Only readable stream can be merged.'); + } + + streams.pause(); + } else { + for (let i = 0, len = streams.length; i < len; i++) { + streams[i] = pauseStreams(streams[i], options); + } + } + + return streams; +} + +var stream = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.merge = void 0; + + function merge(streams) { + const mergedStream = merge2_1(streams); + streams.forEach(stream => { + stream.once('error', error => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; + } + + exports.merge = merge; + + function propagateCloseEventToSources(streams) { + streams.forEach(stream => stream.emit('close')); + } +}); + +var string = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isEmpty = exports.isString = void 0; + + function isString(input) { + return typeof input === 'string'; + } + + exports.isString = isString; + + function isEmpty(input) { + return input === ''; + } + + exports.isEmpty = isEmpty; +}); + +var utils$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; + exports.array = array; + exports.errno = errno; + exports.fs = fs; + exports.path = path_1; + exports.pattern = pattern; + exports.stream = stream; + exports.string = string; +}); + +var tasks = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; + + function generate(patterns, settings) { + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); + const staticPatterns = positivePatterns.filter(pattern => utils$2.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter(pattern => utils$2.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, + /* dynamic */ + false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, + /* dynamic */ + true); + return staticTasks.concat(dynamicTasks); + } + + exports.generate = generate; + + function convertPatternsToTasks(positive, negative, dynamic) { + const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks. + // In this case, the global task covers the rest. + + if ('.' in positivePatternsGroup) { + const task = convertPatternGroupToTask('.', positive, negative, dynamic); + return [task]; + } + + return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic); + } + + exports.convertPatternsToTasks = convertPatternsToTasks; + + function getPositivePatterns(patterns) { + return utils$2.pattern.getPositivePatterns(patterns); + } + + exports.getPositivePatterns = getPositivePatterns; + + function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils$2.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils$2.pattern.convertToPositivePattern); + return positive; + } + + exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; + + function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils$2.pattern.getBaseDirectory(pattern); + + if (base in collection) { + collection[base].push(pattern); + } else { + collection[base] = [pattern]; + } + + return collection; + }, group); + } + + exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; + + function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map(base => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); + } + + exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; + + function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils$2.pattern.convertToNegativePattern)) + }; + } + + exports.convertPatternGroupToTask = convertPatternGroupToTask; +}); + +var async = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function read(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + return callFailureCallback(callback, lstatError); + } + + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return callSuccessCallback(callback, lstat); + } + + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + return callFailureCallback(callback, statError); + } + + return callSuccessCallback(callback, lstat); + } + + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + + callSuccessCallback(callback, stat); + }); + }); + } + + exports.read = read; + + function callFailureCallback(callback, error) { + callback(error); + } + + function callSuccessCallback(callback, result) { + callback(null, result); + } +}); + +var sync = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + + try { + const stat = settings.fs.statSync(path); + + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + + return stat; + } catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + + throw error; + } + } + + exports.read = read; +}); + +var fs_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + stat: fs__default['default'].stat, + lstatSync: fs__default['default'].lstatSync, + statSync: fs__default['default'].statSync + }; + + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + + exports.createFileSystemAdapter = createFileSystemAdapter; +}); + +var settings = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs_1.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + + _getValue(option, value) { + return option === undefined ? value : option; + } + + } + + exports.default = Settings; +}); + +var out = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Settings = settings.default; + + function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return async.read(path, getSettings(), optionsOrSettingsOrCallback); + } + + async.read(path, getSettings(optionsOrSettingsOrCallback), callback); + } + + exports.stat = stat; + + function statSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync.read(path, settings); + } + + exports.statSync = statSync; + + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings.default) { + return settingsOrOptions; + } + + return new settings.default(settingsOrOptions); + } +}); + +var runParallel_1 = runParallel; + +function runParallel(tasks, cb) { + var results, pending, keys; + var isSync = true; + + if (Array.isArray(tasks)) { + results = []; + pending = tasks.length; + } else { + keys = Object.keys(tasks); + results = {}; + pending = keys.length; + } + + function done(err) { + function end() { + if (cb) cb(err, results); + cb = null; + } + + if (isSync) process.nextTick(end);else end(); + } + + function each(i, err, result) { + results[i] = result; + + if (--pending === 0 || err) { + done(err); + } + } + + if (!pending) { + // empty + done(null); + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { + each(key, err, result); + }); + }); + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { + each(i, err, result); + }); + }); + } + + isSync = false; +} + +var constants$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); + const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); + const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); + const SUPPORTED_MAJOR_VERSION = 10; + const SUPPORTED_MINOR_VERSION = 10; + const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; + const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; + /** + * IS `true` for Node.js 10.10 and greater. + */ + + exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; +}); + +var fs$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } + + } + + function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); + } + + exports.createDirentFromStats = createDirentFromStats; +}); + +var utils$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.fs = fs$1; +}); + +var async$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function read(directory, settings, callback) { + if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings, callback); + } + + return readdir(directory, settings, callback); + } + + exports.read = read; + + function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { + withFileTypes: true + }, (readdirError, dirents) => { + if (readdirError !== null) { + return callFailureCallback(callback, readdirError); + } + + const entries = dirents.map(dirent => ({ + dirent, + name: dirent.name, + path: `${directory}${settings.pathSegmentSeparator}${dirent.name}` + })); + + if (!settings.followSymbolicLinks) { + return callSuccessCallback(callback, entries); + } + + const tasks = entries.map(entry => makeRplTaskEntry(entry, settings)); + runParallel_1(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + return callFailureCallback(callback, rplError); + } + + callSuccessCallback(callback, rplEntries); + }); + }); + } + + exports.readdirWithFileTypes = readdirWithFileTypes; + + function makeRplTaskEntry(entry, settings) { + return done => { + if (!entry.dirent.isSymbolicLink()) { + return done(null, entry); + } + + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + return done(statError); + } + + return done(null, entry); + } + + entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats); + return done(null, entry); + }); + }; + } + + function readdir(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + return callFailureCallback(callback, readdirError); + } + + const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`); + const tasks = filepaths.map(filepath => { + return done => out.stat(filepath, settings.fsStatSettings, done); + }); + runParallel_1(tasks, (rplError, results) => { + if (rplError !== null) { + return callFailureCallback(callback, rplError); + } + + const entries = []; + names.forEach((name, index) => { + const stats = results[index]; + const entry = { + name, + path: filepaths[index], + dirent: utils$3.fs.createDirentFromStats(name, stats) + }; + + if (settings.stats) { + entry.stats = stats; + } + + entries.push(entry); + }); + callSuccessCallback(callback, entries); + }); + }); + } + + exports.readdir = readdir; + + function callFailureCallback(callback, error) { + callback(error); + } + + function callSuccessCallback(callback, result) { + callback(null, result); + } +}); + +var sync$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function read(directory, settings) { + if (!settings.stats && constants$2.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + + return readdir(directory, settings); + } + + exports.read = read; + + function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { + withFileTypes: true + }); + return dirents.map(dirent => { + const entry = { + dirent, + name: dirent.name, + path: `${directory}${settings.pathSegmentSeparator}${dirent.name}` + }; + + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils$3.fs.createDirentFromStats(entry.name, stats); + } catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + + return entry; + }); + } + + exports.readdirWithFileTypes = readdirWithFileTypes; + + function readdir(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map(name => { + const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`; + const stats = out.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils$3.fs.createDirentFromStats(name, stats) + }; + + if (settings.stats) { + entry.stats = stats; + } + + return entry; + }); + } + + exports.readdir = readdir; +}); + +var fs_1$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + stat: fs__default['default'].stat, + lstatSync: fs__default['default'].lstatSync, + statSync: fs__default['default'].statSync, + readdir: fs__default['default'].readdir, + readdirSync: fs__default['default'].readdirSync + }; + + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + + exports.createFileSystemAdapter = createFileSystemAdapter; +}); + +var settings$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs_1$1.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new out.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + + _getValue(option, value) { + return option === undefined ? value : option; + } + + } + + exports.default = Settings; +}); + +var out$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Settings = settings$1.default; + + function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return async$1.read(path, getSettings(), optionsOrSettingsOrCallback); + } + + async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback); + } + + exports.scandir = scandir; + + function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync$1.read(path, settings); + } + + exports.scandirSync = scandirSync; + + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings$1.default) { + return settingsOrOptions; + } + + return new settings$1.default(settingsOrOptions); + } +}); + +function reusify(Constructor) { + var head = new Constructor(); + var tail = head; + + function get() { + var current = head; + + if (current.next) { + head = current.next; + } else { + head = new Constructor(); + tail = head; + } + + current.next = null; + return current; + } + + function release(obj) { + tail.next = obj; + tail = obj; + } + + return { + get: get, + release: release + }; +} + +var reusify_1 = reusify; + +function fastqueue(context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker; + worker = context; + context = null; + } + + var cache = reusify_1(Task); + var queueHead = null; + var queueTail = null; + var _running = 0; + var self = { + push: push, + drain: noop, + saturated: noop, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop, + kill: kill, + killAndDrain: killAndDrain + }; + return self; + + function running() { + return _running; + } + + function pause() { + self.paused = true; + } + + function length() { + var current = queueHead; + var counter = 0; + + while (current) { + current = current.next; + counter++; + } + + return counter; + } + + function getQueue() { + var current = queueHead; + var tasks = []; + + while (current) { + tasks.push(current.value); + current = current.next; + } + + return tasks; + } + + function resume() { + if (!self.paused) return; + self.paused = false; + + for (var i = 0; i < self.concurrency; i++) { + _running++; + release(); + } + } + + function idle() { + return _running === 0 && self.length() === 0; + } + + function push(value, done) { + var current = cache.get(); + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop; + + if (_running === self.concurrency || self.paused) { + if (queueTail) { + queueTail.next = current; + queueTail = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function unshift(value, done) { + var current = cache.get(); + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop; + + if (_running === self.concurrency || self.paused) { + if (queueHead) { + current.next = queueHead; + queueHead = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function release(holder) { + if (holder) { + cache.release(holder); + } + + var next = queueHead; + + if (next) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null; + } + + queueHead = next.next; + next.next = null; + worker.call(context, next.value, next.worked); + + if (queueTail === null) { + self.empty(); + } + } else { + _running--; + } + } else if (--_running === 0) { + self.drain(); + } + } + + function kill() { + queueHead = null; + queueTail = null; + self.drain = noop; + } + + function killAndDrain() { + queueHead = null; + queueTail = null; + self.drain(); + self.drain = noop; + } +} + +function noop() {} + +function Task() { + this.value = null; + this.callback = noop; + this.next = null; + this.release = noop; + this.context = null; + var self = this; + + this.worked = function worked(err, result) { + var callback = self.callback; + self.value = null; + self.callback = noop; + callback.call(self.context, err, result); + self.release(self); + }; +} + +var queue = fastqueue; + +var common = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + + return !settings.errorFilter(error); + } + + exports.isFatalError = isFatalError; + + function isAppliedFilter(filter, value) { + return filter === null || filter(value); + } + + exports.isAppliedFilter = isAppliedFilter; + + function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[\\/]/).join(separator); + } + + exports.replacePathSegmentSeparator = replacePathSegmentSeparator; + + function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + + return a + separator + b; + } + + exports.joinPathSegments = joinPathSegments; +}); + +var reader = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } + + } + + exports.default = Reader; +}); + +var async$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class AsyncReader extends reader.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = out$1.scandir; + this._emitter = new events__default['default'].EventEmitter(); + this._queue = queue(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + + this._isDestroyed = true; + + this._queue.killAndDrain(); + } + + onEntry(callback) { + this._emitter.on('entry', callback); + } + + onError(callback) { + this._emitter.once('error', callback); + } + + onEnd(callback) { + this._emitter.once('end', callback); + } + + _pushToQueue(directory, base) { + const queueItem = { + directory, + base + }; + + this._queue.push(queueItem, error => { + if (error !== null) { + this._handleError(error); + } + }); + } + + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + return done(error, undefined); + } + + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + + done(null, undefined); + }); + } + + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + + this._isFatalError = true; + this._isDestroyed = true; + + this._emitter.emit('error', error); + } + + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + + const fullpath = entry.path; + + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, entry.path); + } + } + + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } + + } + + exports.default = AsyncReader; +}); + +var async$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async$2.default(this._root, this._settings); + this._storage = new Set(); + } + + read(callback) { + this._reader.onError(error => { + callFailureCallback(callback, error); + }); + + this._reader.onEntry(entry => { + this._storage.add(entry); + }); + + this._reader.onEnd(() => { + callSuccessCallback(callback, [...this._storage]); + }); + + this._reader.read(); + } + + } + + exports.default = AsyncProvider; + + function callFailureCallback(callback, error) { + callback(error); + } + + function callSuccessCallback(callback, entries) { + callback(null, entries); + } +}); + +var stream$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async$2.default(this._root, this._settings); + this._stream = new stream__default['default'].Readable({ + objectMode: true, + read: () => {}, + destroy: this._reader.destroy.bind(this._reader) + }); + } + + read() { + this._reader.onError(error => { + this._stream.emit('error', error); + }); + + this._reader.onEntry(entry => { + this._stream.push(entry); + }); + + this._reader.onEnd(() => { + this._stream.push(null); + }); + + this._reader.read(); + + return this._stream; + } + + } + + exports.default = StreamProvider; +}); + +var sync$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class SyncReader extends reader.default { + constructor() { + super(...arguments); + this._scandir = out$1.scandirSync; + this._storage = new Set(); + this._queue = new Set(); + } + + read() { + this._pushToQueue(this._root, this._settings.basePath); + + this._handleQueue(); + + return [...this._storage]; + } + + _pushToQueue(directory, base) { + this._queue.add({ + directory, + base + }); + } + + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + + for (const entry of entries) { + this._handleEntry(entry, base); + } + } catch (error) { + this._handleError(error); + } + } + + _handleError(error) { + if (!common.isFatalError(this._settings, error)) { + return; + } + + throw error; + } + + _handleEntry(entry, base) { + const fullpath = entry.path; + + if (base !== undefined) { + entry.path = common.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + + if (common.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + + if (entry.dirent.isDirectory() && common.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, entry.path); + } + } + + _pushToStorage(entry) { + this._storage.add(entry); + } + + } + + exports.default = SyncReader; +}); + +var sync$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync$2.default(this._root, this._settings); + } + + read() { + return this._reader.read(); + } + + } + + exports.default = SyncProvider; +}); + +var settings$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Infinity); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep); + this.fsScandirSettings = new out$1.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + + _getValue(option, value) { + return option === undefined ? value : option; + } + + } + + exports.default = Settings; +}); + +var out$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Settings = settings$2.default; + + function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return new async$3.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + } + + new async$3.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); + } + + exports.walk = walk; + + function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync$3.default(directory, settings); + return provider.read(); + } + + exports.walkSync = walkSync; + + function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream$1.default(directory, settings); + return provider.read(); + } + + exports.walkStream = walkStream; + + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings$2.default) { + return settingsOrOptions; + } + + return new settings$2.default(settingsOrOptions); + } +}); + +var reader$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new out.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + + _getFullEntryPath(filepath) { + return path__default['default'].resolve(this._settings.cwd, filepath); + } + + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils$2.fs.createDirentFromStats(pattern, stats) + }; + + if (this._settings.stats) { + entry.stats = stats; + } + + return entry; + } + + _isFatalError(error) { + return !utils$2.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } + + } + + exports.default = Reader; +}); + +var stream$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ReaderStream extends reader$1.default { + constructor() { + super(...arguments); + this._walkStream = out$2.walkStream; + this._stat = out.stat; + } + + dynamic(root, options) { + return this._walkStream(root, options); + } + + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream__default['default'].PassThrough({ + objectMode: true + }); + + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options).then(entry => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + + if (index === filepaths.length - 1) { + stream.end(); + } + + done(); + }).catch(done); + }; + + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + + return stream; + } + + _getEntry(filepath, pattern, options) { + return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => { + if (options.errorFilter(error)) { + return null; + } + + throw error; + }); + } + + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } + + } + + exports.default = ReaderStream; +}); + +var matcher = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + + this._fillStorage(); + } + + _fillStorage() { + /** + * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). + * So, before expand patterns with brace expansion into separated patterns. + */ + const patterns = utils$2.pattern.expandPatternsWithBraceExpansion(this._patterns); + + for (const pattern of patterns) { + const segments = this._getPatternSegments(pattern); + + const sections = this._splitSegmentsIntoSections(segments); + + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + + _getPatternSegments(pattern) { + const parts = utils$2.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map(part => { + const dynamic = utils$2.pattern.isDynamicPattern(part, this._settings); + + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + + return { + dynamic: true, + pattern: part, + patternRe: utils$2.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + + _splitSegmentsIntoSections(segments) { + return utils$2.array.splitWhen(segments, segment => segment.dynamic && utils$2.pattern.hasGlobStar(segment.pattern)); + } + + } + + exports.default = Matcher; +}); + +var partial = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class PartialMatcher extends matcher.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + + const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels); + + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + + if (!pattern.complete && levels > section.length) { + return true; + } + + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + + if (!segment.dynamic && segment.pattern === part) { + return true; + } + + return false; + }); + + if (match) { + return true; + } + } + + return false; + } + + } + + exports.default = PartialMatcher; +}); + +var deep = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + + const negativeRe = this._getNegativePatternsRe(negative); + + return entry => this._filter(basePath, entry, matcher, negativeRe); + } + + _getMatcher(patterns) { + return new partial.default(patterns, this._settings, this._micromatchOptions); + } + + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils$2.pattern.isAffectDepthOfReadingPattern); + return utils$2.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + + const filepath = utils$2.path.removeLeadingDotSegment(entry.path); + + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + + if (basePath === '') { + return entryPathDepth; + } + + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils$2.pattern.matchAny(entryPath, patternsRe); + } + + } + + exports.default = DeepFilter; +}); + +var entry = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + + getFilter(positive, negative) { + const positiveRe = utils$2.pattern.convertPatternsToRe(positive, this._micromatchOptions); + const negativeRe = utils$2.pattern.convertPatternsToRe(negative, this._micromatchOptions); + return entry => this._filter(entry, positiveRe, negativeRe); + } + + _filter(entry, positiveRe, negativeRe) { + if (this._settings.unique && this._isDuplicateEntry(entry)) { + return false; + } + + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + + if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { + return false; + } + + const filepath = this._settings.baseNameMatch ? entry.name : entry.path; + const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); + + if (this._settings.unique && isMatched) { + this._createIndexRecord(entry); + } + + return isMatched; + } + + _isDuplicateEntry(entry) { + return this.index.has(entry.path); + } + + _createIndexRecord(entry) { + this.index.set(entry.path, undefined); + } + + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + + _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { + if (!this._settings.absolute) { + return false; + } + + const fullpath = utils$2.path.makeAbsolute(this._settings.cwd, entryPath); + return utils$2.pattern.matchAny(fullpath, patternsRe); + } + + _isMatchToPatterns(entryPath, patternsRe) { + const filepath = utils$2.path.removeLeadingDotSegment(entryPath); + return utils$2.pattern.matchAny(filepath, patternsRe); + } + + } + + exports.default = EntryFilter; +}); + +var error = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + + getFilter() { + return error => this._isNonFatalError(error); + } + + _isNonFatalError(error) { + return utils$2.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } + + } + + exports.default = ErrorFilter; +}); + +var entry$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + + getTransformer() { + return entry => this._transform(entry); + } + + _transform(entry) { + let filepath = entry.path; + + if (this._settings.absolute) { + filepath = utils$2.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils$2.path.unixify(filepath); + } + + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + + if (!this._settings.objectMode) { + return filepath; + } + + return Object.assign(Object.assign({}, entry), { + path: filepath + }); + } + + } + + exports.default = EntryTransformer; +}); + +var provider = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error.default(this._settings); + this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry$1.default(this._settings); + } + + _getRootDirectory(task) { + return path__default['default'].resolve(this._settings.cwd, task.base); + } + + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } + + } + + exports.default = Provider; +}); + +var async$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ProviderAsync extends provider.default { + constructor() { + super(...arguments); + this._reader = new stream$2.default(this._settings); + } + + read(task) { + const root = this._getRootDirectory(task); + + const options = this._getReaderOptions(task); + + const entries = []; + return new Promise((resolve, reject) => { + const stream = this.api(root, task, options); + stream.once('error', reject); + stream.on('data', entry => entries.push(options.transform(entry))); + stream.once('end', () => resolve(entries)); + }); + } + + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + + return this._reader.static(task.patterns, options); + } + + } + + exports.default = ProviderAsync; +}); + +var stream$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ProviderStream extends provider.default { + constructor() { + super(...arguments); + this._reader = new stream$2.default(this._settings); + } + + read(task) { + const root = this._getRootDirectory(task); + + const options = this._getReaderOptions(task); + + const source = this.api(root, task, options); + const destination = new stream__default['default'].Readable({ + objectMode: true, + read: () => {} + }); + source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end')); + destination.once('close', () => source.destroy()); + return destination; + } + + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + + return this._reader.static(task.patterns, options); + } + + } + + exports.default = ProviderStream; +}); + +var sync$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ReaderSync extends reader$1.default { + constructor() { + super(...arguments); + this._walkSync = out$2.walkSync; + this._statSync = out.statSync; + } + + dynamic(root, options) { + return this._walkSync(root, options); + } + + static(patterns, options) { + const entries = []; + + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + + const entry = this._getEntry(filepath, pattern, options); + + if (entry === null || !options.entryFilter(entry)) { + continue; + } + + entries.push(entry); + } + + return entries; + } + + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + + return this._makeEntry(stats, pattern); + } catch (error) { + if (options.errorFilter(error)) { + return null; + } + + throw error; + } + } + + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } + + } + + exports.default = ReaderSync; +}); + +var sync$5 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ProviderSync extends provider.default { + constructor() { + super(...arguments); + this._reader = new sync$4.default(this._settings); + } + + read(task) { + const root = this._getRootDirectory(task); + + const options = this._getReaderOptions(task); + + const entries = this.api(root, task, options); + return entries.map(options.transform); + } + + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + + return this._reader.static(task.patterns, options); + } + + } + + exports.default = ProviderSync; +}); + +var settings$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; + const CPU_COUNT = os__default['default'].cpus().length; + exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + lstatSync: fs__default['default'].lstatSync, + stat: fs__default['default'].stat, + statSync: fs__default['default'].statSync, + readdir: fs__default['default'].readdir, + readdirSync: fs__default['default'].readdirSync + }; + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + + if (this.onlyDirectories) { + this.onlyFiles = false; + } + + if (this.stats) { + this.objectMode = true; + } + } + + _getValue(option, value) { + return option === undefined ? value : option; + } + + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } + + } + + exports.default = Settings; +}); + +async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async$4.default, options); + const result = await Promise.all(works); + return utils$2.array.flatten(result); +} // https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare + + +(function (FastGlob) { + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync$5.default, options); + return utils$2.array.flatten(works); + } + + FastGlob.sync = sync; + + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream$3.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + + return utils$2.stream.merge(works); + } + + FastGlob.stream = stream; + + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings$3.default(options); + return tasks.generate(patterns, settings); + } + + FastGlob.generateTasks = generateTasks; + + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings$3.default(options); + return utils$2.pattern.isDynamicPattern(source, settings); + } + + FastGlob.isDynamicPattern = isDynamicPattern; + + function escapePath(source) { + assertPatternsInput(source); + return utils$2.path.escape(source); + } + + FastGlob.escapePath = escapePath; +})(FastGlob || (FastGlob = {})); + +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings$3.default(options); + const tasks$1 = tasks.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks$1.map(provider.read, provider); +} + +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every(item => utils$2.string.isString(item) && !utils$2.string.isEmpty(item)); + + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} + +var out$3 = FastGlob; + +/** @typedef {import('./util').Context} Context */ + +/** + * @param {Context} context + */ + + +function* expandPatterns(context) { + const cwd = process.cwd(); + const seen = new Set(); + let noResults = true; + + for (const pathOrError of expandPatternsInternal(context)) { + noResults = false; + + if (typeof pathOrError !== "string") { + yield pathOrError; + continue; + } + + const relativePath = path__default['default'].relative(cwd, pathOrError); // filter out duplicates + + if (seen.has(relativePath)) { + continue; + } + + seen.add(relativePath); + yield relativePath; + } + + if (noResults) { + // If there was no files and no other errors, let's yield a general error. + yield { + error: `No matching files. Patterns: ${context.filePatterns.join(" ")}` + }; + } +} +/** + * @param {Context} context + */ + + +function* expandPatternsInternal(context) { + // Ignores files in version control systems directories and `node_modules` + const silentlyIgnoredDirs = { + ".git": true, + ".svn": true, + ".hg": true, + node_modules: context.argv["with-node-modules"] !== true + }; + const globOptions = { + dot: true, + ignore: Object.keys(silentlyIgnoredDirs).filter(dir => silentlyIgnoredDirs[dir]).map(dir => "**/" + dir) + }; + let supportedFilesGlob; + const cwd = process.cwd(); + /** @type {Array<{ type: 'file' | 'dir' | 'glob'; glob: string; input: string; }>} */ + + const entries = []; + + for (const pattern of context.filePatterns) { + const absolutePath = path__default['default'].resolve(cwd, pattern); + + if (containsIgnoredPathSegment(absolutePath, cwd, silentlyIgnoredDirs)) { + continue; + } + + const stat = statSafeSync(absolutePath); + + if (stat) { + if (stat.isFile()) { + entries.push({ + type: "file", + glob: escapePathForGlob(fixWindowsSlashes(pattern)), + input: pattern + }); + } else if (stat.isDirectory()) { + entries.push({ + type: "dir", + glob: escapePathForGlob(fixWindowsSlashes(pattern)) + "/" + getSupportedFilesGlob(), + input: pattern + }); + } + } else if (pattern[0] === "!") { + // convert negative patterns to `ignore` entries + globOptions.ignore.push(fixWindowsSlashes(pattern.slice(1))); + } else { + entries.push({ + type: "glob", + glob: fixWindowsSlashes(pattern), + input: pattern + }); + } + } + + for (const { + type, + glob, + input + } of entries) { + let result; + + try { + result = out$3.sync(glob, globOptions); + } catch ({ + message + }) { + /* istanbul ignore next */ + yield { + error: `${errorMessages.globError[type]}: ${input}\n${message}` + }; + /* istanbul ignore next */ + + continue; + } + + if (result.length === 0) { + yield { + error: `${errorMessages.emptyResults[type]}: "${input}".` + }; + } else { + yield* sortPaths(result); + } + } + + function getSupportedFilesGlob() { + if (!supportedFilesGlob) { + const extensions = flatten_1(context.languages.map(lang => lang.extensions || [])); + const filenames = flatten_1(context.languages.map(lang => lang.filenames || [])); + supportedFilesGlob = `**/{${extensions.map(ext => "*" + (ext[0] === "." ? ext : "." + ext)).concat(filenames)}}`; + } + + return supportedFilesGlob; + } +} + +const errorMessages = { + globError: { + file: "Unable to resolve file", + dir: "Unable to expand directory", + glob: "Unable to expand glob pattern" + }, + emptyResults: { + file: "Explicitly specified file was ignored due to negative glob patterns", + dir: "No supported files were found in the directory", + glob: "No files matching the pattern were found" + } +}; +/** + * @param {string} absolutePath + * @param {string} cwd + * @param {Record} ignoredDirectories + */ + +function containsIgnoredPathSegment(absolutePath, cwd, ignoredDirectories) { + return path__default['default'].relative(cwd, absolutePath).split(path__default['default'].sep).some(dir => ignoredDirectories[dir]); +} +/** + * @param {string[]} paths + */ + + +function sortPaths(paths) { + return paths.sort((a, b) => a.localeCompare(b)); +} +/** + * Get stats of a given path. + * @param {string} filePath The path to target file. + * @returns {fs.Stats | undefined} The stats. + */ + + +function statSafeSync(filePath) { + try { + return fs__default['default'].statSync(filePath); + } catch (error) { + /* istanbul ignore next */ + if (error.code !== "ENOENT") { + throw error; + } + } +} +/** + * This function should be replaced with `fastGlob.escapePath` when these issues are fixed: + * - https://github.com/mrmlnc/fast-glob/issues/261 + * - https://github.com/mrmlnc/fast-glob/issues/262 + * @param {string} path + */ + + +function escapePathForGlob(path) { + return out$3.escapePath(path.replace(/\\/g, "\0") // Workaround for fast-glob#262 (part 1) + ).replace(/\\!/g, "@(!)") // Workaround for fast-glob#261 + .replace(/\0/g, "@(\\\\)"); // Workaround for fast-glob#262 (part 2) +} + +const isWindows = path__default['default'].sep === "\\"; +/** + * Using backslashes in globs is probably not okay, but not accepting + * backslashes as path separators on Windows is even more not okay. + * https://github.com/prettier/prettier/pull/6776#discussion_r380723717 + * https://github.com/mrmlnc/fast-glob#how-to-write-patterns-on-windows + * @param {string} pattern + */ + +function fixWindowsSlashes(pattern) { + return isWindows ? pattern.replace(/\\/g, "/") : pattern; +} + +var expandPatterns_1 = { + expandPatterns, + fixWindowsSlashes +}; + +var lib = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either. + + function noop() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + } + + function createWeakMap() { + if (typeof WeakMap !== 'undefined') { + return new WeakMap(); + } else { + return fakeSetOrMap(); + } + } + /** + * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything. + */ + + + function fakeSetOrMap() { + return { + add: noop, + delete: noop, + get: noop, + set: noop, + has: function (k) { + return false; + } + }; + } // Safe hasOwnProperty + + + var hop = Object.prototype.hasOwnProperty; + + var has = function (obj, prop) { + return hop.call(obj, prop); + }; // Copy all own enumerable properties from source to target + + + function extend(target, source) { + for (var prop in source) { + if (has(source, prop)) { + target[prop] = source[prop]; + } + } + + return target; + } + + var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/; + var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/; + var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/; + var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/; + var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/; + + function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) { + // If first interpolated value is a reference to outdent, + // determine indentation level from the indentation of the interpolated value. + var indentationLevel = 0; + var match = strings[0].match(reDetectIndentation); + + if (match) { + indentationLevel = match[1].length; + } + + var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}"; + var reMatchIndent = new RegExp(reSource, 'g'); + + if (firstInterpolatedValueSetsIndentationLevel) { + strings = strings.slice(1); + } + + var newline = options.newline, + trimLeadingNewline = options.trimLeadingNewline, + trimTrailingNewline = options.trimTrailingNewline; + var normalizeNewlines = typeof newline === 'string'; + var l = strings.length; + var outdentedStrings = strings.map(function (v, i) { + // Remove leading indentation from all lines + v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string + + if (i === 0 && trimLeadingNewline) { + v = v.replace(reLeadingNewline, ''); + } // Trim a trailing newline from the last string + + + if (i === l - 1 && trimTrailingNewline) { + v = v.replace(reTrailingNewline, ''); + } // Normalize newlines + + + if (normalizeNewlines) { + v = v.replace(/\r\n|\n|\r/g, function (_) { + return newline; + }); + } + + return v; + }); + return outdentedStrings; + } + + function concatStringsAndValues(strings, values) { + var ret = ''; + + for (var i = 0, l = strings.length; i < l; i++) { + ret += strings[i]; + + if (i < l - 1) { + ret += values[i]; + } + } + + return ret; + } + + function isTemplateStringsArray(v) { + return has(v, 'raw') && has(v, 'length'); + } + /** + * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to + * makeInstance + * @param options + * @return {outdent} + */ + + + function createInstance(options) { + /** Cache of pre-processed template literal arrays */ + var arrayAutoIndentCache = createWeakMap(); + /** + * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent, + * before interpolated values are injected. + */ + + var arrayFirstInterpSetsIndentCache = createWeakMap(); + + function outdent(stringsOrOptions) { + var values = []; + + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + /* tslint:enable:no-shadowed-variable */ + + + if (isTemplateStringsArray(stringsOrOptions)) { + var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace? + + var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation + + var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache; + var renderedArray = cache.get(strings); + + if (!renderedArray) { + renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options); + cache.set(strings, renderedArray); + } + /** If no interpolated values, skip concatenation step */ + + + if (values.length === 0) { + return renderedArray[0]; + } + /** Concatenate string literals with interpolated values */ + + + var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values); + return rendered; + } else { + // Create and return a new instance of outdent with the given options + return createInstance(extend(extend({}, options), stringsOrOptions || {})); + } + } + + var fullOutdent = extend(outdent, { + string: function (str) { + return _outdentArray([str], false, options)[0]; + } + }); + return fullOutdent; + } + + var defaultOutdent = createInstance({ + trimLeadingNewline: true, + trimTrailingNewline: true + }); + exports.outdent = defaultOutdent; // Named exports. Simple and preferred. + // import outdent from 'outdent'; + + exports.default = defaultOutdent; + + { + // In webpack harmony-modules environments, module.exports is read-only, + // so we fail gracefully. + try { + module.exports = defaultOutdent; + Object.defineProperty(defaultOutdent, '__esModule', { + value: true + }); + defaultOutdent.default = defaultOutdent; + defaultOutdent.outdent = defaultOutdent; + } catch (e) {} + } +}); + +const { + outdent +} = lib; +const { + coreOptions +} = prettierInternal; +const categoryOrder = [coreOptions.CATEGORY_OUTPUT, coreOptions.CATEGORY_FORMAT, coreOptions.CATEGORY_CONFIG, coreOptions.CATEGORY_EDITOR, coreOptions.CATEGORY_OTHER]; +/** + * { + * [optionName]: { + * // The type of the option. For 'choice', see also `choices` below. + * // When passing a type other than the ones listed below, the option is + * // treated as taking any string as argument, and `--option <${type}>` will + * // be displayed in --help. + * type: "boolean" | "choice" | "int" | string; + * + * // Default value to be passed to the minimist option `default`. + * default?: any; + * + * // Alias name to be passed to the minimist option `alias`. + * alias?: string; + * + * // For grouping options by category in --help. + * category?: string; + * + * // Description to be displayed in --help. If omitted, the option won't be + * // shown at all in --help (but see also `oppositeDescription` below). + * description?: string; + * + * // Description for `--no-${name}` to be displayed in --help. If omitted, + * // `--no-${name}` won't be shown. + * oppositeDescription?: string; + * + * // Indicate if this option is simply passed to the API. + * // true: use camelified name as the API option name. + * // string: use this value as the API option name. + * forwardToApi?: boolean | string; + * + * // Indicate that a CLI flag should be an array when forwarded to the API. + * array?: boolean; + * + * // Specify available choices for validation. They will also be displayed + * // in --help as . + * // Use an object instead of a string if a choice is deprecated and should + * // be treated as `redirect` instead, or if you'd like to add description for + * // the choice. + * choices?: Array< + * | string + * | { value: string, description?: string, deprecated?: boolean, redirect?: string } + * >; + * + * // If the option has a value that is an exception to the regular value + * // constraints, indicate that value here (or use a function for more + * // flexibility). + * exception?: ((value: any) => boolean); + * + * // Indicate that the option is deprecated. Use a string to add an extra + * // message to --help for the option, for example to suggest a replacement + * // option. + * deprecated?: true | string; + * } + * } + * + * Note: The options below are sorted alphabetically. + */ + +const options = { + check: { + type: "boolean", + category: coreOptions.CATEGORY_OUTPUT, + alias: "c", + description: outdent` + Check if the given files are formatted, print a human-friendly summary + message and paths to unformatted files (see also --list-different). + ` + }, + color: { + // The supports-color package (a sub sub dependency) looks directly at + // `process.argv` for `--no-color` and such-like options. The reason it is + // listed here is to avoid "Ignored unknown option: --no-color" warnings. + // See https://github.com/chalk/supports-color/#info for more information. + type: "boolean", + default: true, + description: "Colorize error messages.", + oppositeDescription: "Do not colorize error messages." + }, + config: { + type: "path", + category: coreOptions.CATEGORY_CONFIG, + description: "Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).", + oppositeDescription: "Do not look for a configuration file.", + exception: value => value === false + }, + "config-precedence": { + type: "choice", + category: coreOptions.CATEGORY_CONFIG, + default: "cli-override", + choices: [{ + value: "cli-override", + description: "CLI options take precedence over config file" + }, { + value: "file-override", + description: "Config file take precedence over CLI options" + }, { + value: "prefer-file", + description: outdent` + If a config file is found will evaluate it and ignore other CLI options. + If no config file is found CLI options will evaluate as normal. + ` + }], + description: "Define in which order config files and CLI options should be evaluated." + }, + "debug-benchmark": { + // Run the formatting benchmarks. Requires 'benchmark' module to be installed. + type: "boolean" + }, + "debug-check": { + // Run the formatting once again on the formatted output, throw if different. + type: "boolean" + }, + "debug-print-doc": { + type: "boolean" + }, + "debug-repeat": { + // Repeat the formatting a few times and measure the average duration. + type: "int", + default: 0 + }, + editorconfig: { + type: "boolean", + category: coreOptions.CATEGORY_CONFIG, + description: "Take .editorconfig into account when parsing configuration.", + oppositeDescription: "Don't take .editorconfig into account when parsing configuration.", + default: true + }, + "find-config-path": { + type: "path", + category: coreOptions.CATEGORY_CONFIG, + description: "Find and print the path to a configuration file for the given input file." + }, + "file-info": { + type: "path", + description: outdent` + Extract the following info (as JSON) for a given file path. Reported fields: + * ignored (boolean) - true if file path is filtered by --ignore-path + * inferredParser (string | null) - name of parser inferred from file path + ` + }, + help: { + type: "flag", + alias: "h", + description: outdent` + Show CLI usage, or details about the given flag. + Example: --help write + `, + exception: value => value === "" + }, + "ignore-path": { + type: "path", + category: coreOptions.CATEGORY_CONFIG, + default: ".prettierignore", + description: "Path to a file with patterns describing files to ignore." + }, + "ignore-unknown": { + type: "boolean", + alias: "u", + description: "Ignore unknown files." + }, + "list-different": { + type: "boolean", + category: coreOptions.CATEGORY_OUTPUT, + alias: "l", + description: "Print the names of files that are different from Prettier's formatting (see also --check)." + }, + loglevel: { + type: "choice", + description: "What level of logs to report.", + default: "log", + choices: ["silent", "error", "warn", "log", "debug"] + }, + "support-info": { + type: "boolean", + description: "Print support information as JSON." + }, + version: { + type: "boolean", + alias: "v", + description: "Print Prettier version." + }, + "with-node-modules": { + type: "boolean", + category: coreOptions.CATEGORY_CONFIG, + description: "Process files inside 'node_modules' directory." + }, + write: { + type: "boolean", + alias: "w", + category: coreOptions.CATEGORY_OUTPUT, + description: "Edit files in-place. (Beware!)" + } +}; +const usageSummary = outdent` + Usage: prettier [options] [file/dir/glob ...] + + By default, output is written to stdout. + Stdin is read if it is piped to Prettier and no files are given. +`; +var constant$1 = { + categoryOrder, + options, + usageSummary +}; + +const { + isCI +} = thirdParty; // Some CI pipelines incorrectly report process.stdout.isTTY status, +// which causes unwanted lines in the output. An additional check for isCI() helps. +// See https://github.com/prettier/prettier/issues/5801 + +var isTty = function isTTY() { + return process.stdout.isTTY && !isCI(); +}; + +function Diff() {} + +Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } +}; + +function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; +} + +function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; +} + +var characterDiff = new Diff(); + +function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); +} + +function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; +} // +// Ranges and exceptions: +// Latin-1 Supplement, 0080–00FF +// - U+00D7 × Multiplication sign +// - U+00F7 ÷ Division sign +// Latin Extended-A, 0100–017F +// Latin Extended-B, 0180–024F +// IPA Extensions, 0250–02AF +// Spacing Modifier Letters, 02B0–02FF +// - U+02C7 ˇ ˇ Caron +// - U+02D8 ˘ ˘ Breve +// - U+02D9 ˙ ˙ Dot Above +// - U+02DA ˚ ˚ Ring Above +// - U+02DB ˛ ˛ Ogonek +// - U+02DC ˜ ˜ Small Tilde +// - U+02DD ˝ ˝ Double Acute Accent +// Latin Extended Additional, 1E00–1EFF + + +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace = /\S/; +var wordDiff = new Diff(); + +wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; + +wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; +}; + +function diffWords(oldStr, newStr, options) { + options = generateOptions(options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); +} + +function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); +} + +var lineDiff = new Diff(); + +lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; +}; + +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} + +function diffTrimmedLines(oldStr, newStr, callback) { + var options = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); +} + +var sentenceDiff = new Diff(); + +sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; + +function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); +} + +var cssDiff = new Diff(); + +cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); +}; + +function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); +} + +function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } +} + +function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); +} + +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); +} + +var objectPrototypeToString = Object.prototype.toString; +var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a +// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = lineDiff.tokenize; + +jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); +}; + +jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); +}; + +function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); +} // This function handles the presence of circular references by bailing out when encountering an +// object that is already on the "stack" of items being processed. Accepts an optional replacer + + +function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; +} + +var arrayDiff = new Diff(); + +arrayDiff.tokenize = function (value) { + return value.slice(); +}; + +arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; +}; + +function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); +} + +function parsePatch(uniDiff) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; +} // Iterator that traverses in the range of [min, max], stepping +// by distance from a given start position. I.e. for [0, 4], with +// start of 2, this will iterate 2, 3, 1, 4, 0. + + +function distanceIterator(start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; +} + +function applyPatch(source, uniDiff) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { + return line === patchContent; + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); +} // Wrapper that supports multiple file patches via callbacks. + + +function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); +} + +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; // If we have previous context, start with that + + + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; // Overlapping + + + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; // end the range and output + + + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; +} + +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} + +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} + +function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); +} + +function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; +} + +function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } +} + +function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; +} + +function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return structuredPatch(undefined, undefined, base, param); + } + + return param; +} + +function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; +} + +function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } +} + +function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; +} + +function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; +} + +function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + var _hunk$lines; // Mine inserted + + + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + var _hunk$lines2; // Theirs inserted + + + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); +} + +function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); +} + +function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + var _hunk$lines6; + + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } +} + +function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); +} + +function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } +} + +function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } +} + +function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; +} + +function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; +} + +function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); +} + +function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; +} + +function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; +} // See: http://code.google.com/p/google-diff-match-patch/wiki/API + + +function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; +} + +function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); +} + +function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; +} + +var index_es6 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Diff: Diff, + diffChars: diffChars, + diffWords: diffWords, + diffWordsWithSpace: diffWordsWithSpace, + diffLines: diffLines, + diffTrimmedLines: diffTrimmedLines, + diffSentences: diffSentences, + diffCss: diffCss, + diffJson: diffJson, + diffArrays: diffArrays, + structuredPatch: structuredPatch, + createTwoFilesPatch: createTwoFilesPatch, + createPatch: createPatch, + applyPatch: applyPatch, + applyPatches: applyPatches, + parsePatch: parsePatch, + merge: merge, + convertChangesToDMP: convertChangesToDMP, + convertChangesToXML: convertChangesToXML, + canonicalize: canonicalize +}); + +var require$$3 = getCjsExportFromNamespace(index_es6); + +// eslint-disable-next-line no-restricted-modules + + +const { + getStream +} = thirdParty; +const { + createIgnorer, + errors, + coreOptions: coreOptions$1, + optionsModule, + optionsNormalizer, + utils: { + arrayify + } +} = prettierInternal; +const { + expandPatterns: expandPatterns$1, + fixWindowsSlashes: fixWindowsSlashes$1 +} = expandPatterns_1; +const OPTION_USAGE_THRESHOLD = 25; +const CHOICE_USAGE_MARGIN = 3; +const CHOICE_USAGE_INDENTATION = 2; + +function getOptions(argv, detailedOptions) { + return fromPairs_1(detailedOptions.filter(({ + forwardToApi + }) => forwardToApi).map(({ + forwardToApi, + name + }) => [forwardToApi, argv[name]])); +} + +function cliifyOptions(object, apiDetailedOptionMap) { + return Object.keys(object || {}).reduce((output, key) => { + const apiOption = apiDetailedOptionMap[key]; + const cliKey = apiOption ? apiOption.name : key; + output[dashify(cliKey)] = object[key]; + return output; + }, {}); +} + +function diff(a, b) { + return require$$3.createTwoFilesPatch("", "", a, b, "", "", { + context: 2 + }); +} + +function handleError(context, filename, error) { + if (error instanceof errors.UndefinedParserError) { + // Can't test on CI, `isTTY()` is always false, see ./is-tty.js + + /* istanbul ignore next */ + if ((context.argv.write || context.argv["ignore-unknown"]) && isTty()) { + readline__default['default'].clearLine(process.stdout, 0); + readline__default['default'].cursorTo(process.stdout, 0, null); + } + + if (context.argv["ignore-unknown"]) { + return; + } + + if (!context.argv.check && !context.argv["list-different"]) { + process.exitCode = 2; + } + + context.logger.error(error.message); + return; + } + + if (context.argv.write) { + // Add newline to split errors from filename line. + process.stdout.write("\n"); + } + + const isParseError = Boolean(error && error.loc); + const isValidationError = /^Invalid \S+ value\./.test(error && error.message); + + if (isParseError) { + // `invalid.js: SyntaxError: Unexpected token (1:1)`. + context.logger.error(`${filename}: ${String(error)}`); + } else if (isValidationError || error instanceof errors.ConfigError) { + // `Invalid printWidth value. Expected an integer, but received 0.5.` + context.logger.error(error.message); // If validation fails for one file, it will fail for all of them. + + process.exit(1); + } else if (error instanceof errors.DebugError) { + // `invalid.js: Some debug error message` + context.logger.error(`${filename}: ${error.message}`); + } else { + // `invalid.js: Error: Some unexpected error\n[stack trace]` + + /* istanbul ignore next */ + context.logger.error(filename + ": " + (error.stack || error)); + } // Don't exit the process if one file failed + + + process.exitCode = 2; +} + +function logResolvedConfigPathOrDie(context) { + const configFile = src.resolveConfigFile.sync(context.argv["find-config-path"]); + + if (configFile) { + context.logger.log(path__default['default'].relative(process.cwd(), configFile)); + } else { + process.exit(1); + } +} + +function logFileInfoOrDie(context) { + const options = { + ignorePath: context.argv["ignore-path"], + withNodeModules: context.argv["with-node-modules"], + plugins: context.argv.plugin, + pluginSearchDirs: context.argv["plugin-search-dir"], + resolveConfig: context.argv.config !== false + }; + context.logger.log(src.format(fastJsonStableStringify(src.getFileInfo.sync(context.argv["file-info"], options)), { + parser: "json" + })); +} + +function writeOutput(context, result, options) { + // Don't use `console.log` here since it adds an extra newline at the end. + process.stdout.write(context.argv["debug-check"] ? result.filepath : result.formatted); + + if (options && options.cursorOffset >= 0) { + process.stderr.write(result.cursorOffset + "\n"); + } +} + +function listDifferent(context, input, options, filename) { + if (!context.argv.check && !context.argv["list-different"]) { + return; + } + + try { + if (!options.filepath && !options.parser) { + throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser."); + } + + if (!src.check(input, options)) { + if (!context.argv.write) { + context.logger.log(filename); + process.exitCode = 1; + } + } + } catch (error) { + context.logger.error(error.message); + } + + return true; +} + +function format(context, input, opt) { + if (!opt.parser && !opt.filepath) { + throw new errors.UndefinedParserError("No parser and no file path given, couldn't infer a parser."); + } + + if (context.argv["debug-print-doc"]) { + const doc = src.__debug.printToDoc(input, opt); + + return { + formatted: src.__debug.formatDoc(doc) + }; + } + + if (context.argv["debug-check"]) { + const pp = src.format(input, opt); + const pppp = src.format(pp, opt); + + if (pp !== pppp) { + throw new errors.DebugError("prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp)); + } else { + const stringify = obj => JSON.stringify(obj, null, 2); + + const ast = stringify(src.__debug.parse(input, opt, + /* massage */ + true).ast); + const past = stringify(src.__debug.parse(pp, opt, + /* massage */ + true).ast); + /* istanbul ignore next */ + + if (ast !== past) { + const MAX_AST_SIZE = 2097152; // 2MB + + const astDiff = ast.length > MAX_AST_SIZE || past.length > MAX_AST_SIZE ? "AST diff too large to render" : diff(ast, past); + throw new errors.DebugError("ast(input) !== ast(prettier(input))\n" + astDiff + "\n" + diff(input, pp)); + } + } + + return { + formatted: pp, + filepath: opt.filepath || "(stdin)\n" + }; + } + /* istanbul ignore next */ + + + if (context.argv["debug-benchmark"]) { + let benchmark; + + try { + benchmark = require("benchmark"); + } catch (err) { + context.logger.debug("'--debug-benchmark' requires the 'benchmark' package to be installed."); + process.exit(2); + } + + context.logger.debug("'--debug-benchmark' option found, measuring formatWithCursor with 'benchmark' module."); + const suite = new benchmark.Suite(); + suite.add("format", () => { + src.formatWithCursor(input, opt); + }).on("cycle", event => { + const results = { + benchmark: String(event.target), + hz: event.target.hz, + ms: event.target.times.cycle * 1000 + }; + context.logger.debug("'--debug-benchmark' measurements for formatWithCursor: " + JSON.stringify(results, null, 2)); + }).run({ + async: false + }); + } else if (context.argv["debug-repeat"] > 0) { + const repeat = context.argv["debug-repeat"]; + context.logger.debug("'--debug-repeat' option found, running formatWithCursor " + repeat + " times."); // should be using `performance.now()`, but only `Date` is cross-platform enough + + const now = Date.now ? () => Date.now() : () => +new Date(); + let totalMs = 0; + + for (let i = 0; i < repeat; ++i) { + const startMs = now(); + src.formatWithCursor(input, opt); + totalMs += now() - startMs; + } + + const averageMs = totalMs / repeat; + const results = { + repeat, + hz: 1000 / averageMs, + ms: averageMs + }; + context.logger.debug("'--debug-repeat' measurements for formatWithCursor: " + JSON.stringify(results, null, 2)); + } + + return src.formatWithCursor(input, opt); +} + +function getOptionsOrDie(context, filePath) { + try { + if (context.argv.config === false) { + context.logger.debug("'--no-config' option found, skip loading config file."); + return null; + } + + context.logger.debug(context.argv.config ? `load config file from '${context.argv.config}'` : `resolve config from '${filePath}'`); + const options = src.resolveConfig.sync(filePath, { + editorconfig: context.argv.editorconfig, + config: context.argv.config + }); + context.logger.debug("loaded options `" + JSON.stringify(options) + "`"); + return options; + } catch (error) { + context.logger.error(`Invalid configuration file \`${filePath}\`: ` + error.message); + process.exit(2); + } +} + +function getOptionsForFile(context, filepath) { + const options = getOptionsOrDie(context, filepath); + const hasPlugins = options && options.plugins; + + if (hasPlugins) { + pushContextPlugins(context, options.plugins); + } + + const appliedOptions = Object.assign({ + filepath + }, applyConfigPrecedence(context, options && optionsNormalizer.normalizeApiOptions(options, context.supportOptions, { + logger: context.logger + }))); + context.logger.debug(`applied config-precedence (${context.argv["config-precedence"]}): ` + `${JSON.stringify(appliedOptions)}`); + + if (hasPlugins) { + popContextPlugins(context); + } + + return appliedOptions; +} + +function parseArgsToOptions(context, overrideDefaults) { + const minimistOptions = createMinimistOptions(context.detailedOptions); + const apiDetailedOptionMap = createApiDetailedOptionMap(context.detailedOptions); + return getOptions(optionsNormalizer.normalizeCliOptions(minimist_1(context.args, { + string: minimistOptions.string, + boolean: minimistOptions.boolean, + default: cliifyOptions(overrideDefaults, apiDetailedOptionMap) + }), context.detailedOptions, { + logger: false + }), context.detailedOptions); +} + +function applyConfigPrecedence(context, options) { + try { + switch (context.argv["config-precedence"]) { + case "cli-override": + return parseArgsToOptions(context, options); + + case "file-override": + return Object.assign({}, parseArgsToOptions(context), options); + + case "prefer-file": + return options || parseArgsToOptions(context); + } + } catch (error) { + /* istanbul ignore next */ + context.logger.error(error.toString()); + /* istanbul ignore next */ + + process.exit(2); + } +} + +function formatStdin(context) { + const filepath = context.argv["stdin-filepath"] ? path__default['default'].resolve(process.cwd(), context.argv["stdin-filepath"]) : process.cwd(); + const ignorer = createIgnorerFromContextOrDie(context); // If there's an ignore-path set, the filename must be relative to the + // ignore path, not the current working directory. + + const relativeFilepath = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filepath) : path__default['default'].relative(process.cwd(), filepath); + getStream(process.stdin).then(input => { + if (relativeFilepath && ignorer.ignores(fixWindowsSlashes$1(relativeFilepath))) { + writeOutput(context, { + formatted: input + }); + return; + } + + const options = getOptionsForFile(context, filepath); + + if (listDifferent(context, input, options, "(stdin)")) { + return; + } + + writeOutput(context, format(context, input, options), options); + }).catch(error => { + handleError(context, relativeFilepath || "stdin", error); + }); +} + +function createIgnorerFromContextOrDie(context) { + try { + return createIgnorer.sync(context.argv["ignore-path"], context.argv["with-node-modules"]); + } catch (e) { + context.logger.error(e.message); + process.exit(2); + } +} + +function formatFiles(context) { + // The ignorer will be used to filter file paths after the glob is checked, + // before any files are actually written + const ignorer = createIgnorerFromContextOrDie(context); + let numberOfUnformattedFilesFound = 0; + + if (context.argv.check) { + context.logger.log("Checking formatting..."); + } + + for (const pathOrError of expandPatterns$1(context)) { + if (typeof pathOrError === "object") { + context.logger.error(pathOrError.error); // Don't exit, but set the exit code to 2 + + process.exitCode = 2; + continue; + } + + const filename = pathOrError; // If there's an ignore-path set, the filename must be relative to the + // ignore path, not the current working directory. + + const ignoreFilename = context.argv["ignore-path"] ? path__default['default'].relative(path__default['default'].dirname(context.argv["ignore-path"]), filename) : filename; + const fileIgnored = ignorer.ignores(fixWindowsSlashes$1(ignoreFilename)); + + if (fileIgnored && (context.argv["debug-check"] || context.argv.write || context.argv.check || context.argv["list-different"])) { + continue; + } + + const options = Object.assign({}, getOptionsForFile(context, filename), { + filepath: filename + }); + + if (isTty()) { + context.logger.log(filename, { + newline: false + }); + } + + let input; + + try { + input = fs__default['default'].readFileSync(filename, "utf8"); + } catch (error) { + // Add newline to split errors from filename line. + + /* istanbul ignore next */ + context.logger.log(""); + /* istanbul ignore next */ + + context.logger.error(`Unable to read file: ${filename}\n${error.message}`); // Don't exit the process if one file failed + + /* istanbul ignore next */ + + process.exitCode = 2; + /* istanbul ignore next */ + + continue; + } + + if (fileIgnored) { + writeOutput(context, { + formatted: input + }, options); + continue; + } + + const start = Date.now(); + let result; + let output; + + try { + result = format(context, input, options); + output = result.formatted; + } catch (error) { + handleError(context, filename, error); + continue; + } + + const isDifferent = output !== input; + + if (isTty()) { + // Remove previously printed filename to log it with duration. + readline__default['default'].clearLine(process.stdout, 0); + readline__default['default'].cursorTo(process.stdout, 0, null); + } + + if (context.argv.write) { + // Don't write the file if it won't change in order not to invalidate + // mtime based caches. + if (isDifferent) { + if (!context.argv.check && !context.argv["list-different"]) { + context.logger.log(`${filename} ${Date.now() - start}ms`); + } + + try { + fs__default['default'].writeFileSync(filename, output, "utf8"); + } catch (error) { + /* istanbul ignore next */ + context.logger.error(`Unable to write file: ${filename}\n${error.message}`); // Don't exit the process if one file failed + + /* istanbul ignore next */ + + process.exitCode = 2; + } + } else if (!context.argv.check && !context.argv["list-different"]) { + context.logger.log(`${source.grey(filename)} ${Date.now() - start}ms`); + } + } else if (context.argv["debug-check"]) { + /* istanbul ignore else */ + if (result.filepath) { + context.logger.log(result.filepath); + } else { + process.exitCode = 2; + } + } else if (!context.argv.check && !context.argv["list-different"]) { + writeOutput(context, result, options); + } + + if (isDifferent) { + if (context.argv.check) { + context.logger.warn(filename); + } else if (context.argv["list-different"]) { + context.logger.log(filename); + } + + numberOfUnformattedFilesFound += 1; + } + } // Print check summary based on expected exit code + + + if (context.argv.check) { + if (numberOfUnformattedFilesFound === 0) { + context.logger.log("All matched files use Prettier code style!"); + } else { + context.logger.warn(context.argv.write ? "Code style issues fixed in the above file(s)." : "Code style issues found in the above file(s). Forgot to run Prettier?"); + } + } // Ensure non-zero exitCode when using --check/list-different is not combined with --write + + + if ((context.argv.check || context.argv["list-different"]) && numberOfUnformattedFilesFound > 0 && !process.exitCode && !context.argv.write) { + process.exitCode = 1; + } +} + +function getOptionsWithOpposites(options) { + // Add --no-foo after --foo. + const optionsWithOpposites = options.map(option => [option.description ? option : null, option.oppositeDescription ? Object.assign({}, option, { + name: `no-${option.name}`, + type: "boolean", + description: option.oppositeDescription + }) : null]); + return flatten_1(optionsWithOpposites).filter(Boolean); +} + +function createUsage(context) { + const options = getOptionsWithOpposites(context.detailedOptions).filter( // remove unnecessary option (e.g. `semi`, `color`, etc.), which is only used for --help + option => !(option.type === "boolean" && option.oppositeDescription && !option.name.startsWith("no-"))); + const groupedOptions = groupBy_1(options, option => option.category); + const firstCategories = constant$1.categoryOrder.slice(0, -1); + const lastCategories = constant$1.categoryOrder.slice(-1); + const restCategories = Object.keys(groupedOptions).filter(category => !constant$1.categoryOrder.includes(category)); + const allCategories = [...firstCategories, ...restCategories, ...lastCategories]; + const optionsUsage = allCategories.map(category => { + const categoryOptions = groupedOptions[category].map(option => createOptionUsage(context, option, OPTION_USAGE_THRESHOLD)).join("\n"); + return `${category} options:\n\n${indent(categoryOptions, 2)}`; + }); + return [constant$1.usageSummary].concat(optionsUsage, [""]).join("\n\n"); +} + +function createOptionUsage(context, option, threshold) { + const header = createOptionUsageHeader(option); + const optionDefaultValue = getOptionDefaultValue(context, option.name); + return createOptionUsageRow(header, `${option.description}${optionDefaultValue === undefined ? "" : `\nDefaults to ${createDefaultValueDisplay(optionDefaultValue)}.`}`, threshold); +} + +function createDefaultValueDisplay(value) { + return Array.isArray(value) ? `[${value.map(createDefaultValueDisplay).join(", ")}]` : value; +} + +function createOptionUsageHeader(option) { + const name = `--${option.name}`; + const alias = option.alias ? `-${option.alias},` : null; + const type = createOptionUsageType(option); + return [alias, name, type].filter(Boolean).join(" "); +} + +function createOptionUsageRow(header, content, threshold) { + const separator = header.length >= threshold ? `\n${" ".repeat(threshold)}` : " ".repeat(threshold - header.length); + const description = content.replace(/\n/g, `\n${" ".repeat(threshold)}`); + return `${header}${separator}${description}`; +} + +function createOptionUsageType(option) { + switch (option.type) { + case "boolean": + return null; + + case "choice": + return `<${option.choices.filter(choice => !choice.deprecated && choice.since !== null).map(choice => choice.value).join("|")}>`; + + default: + return `<${option.type}>`; + } +} + +function createChoiceUsages(choices, margin, indentation) { + const activeChoices = choices.filter(choice => !choice.deprecated && choice.since !== null); + const threshold = activeChoices.map(choice => choice.value.length).reduce((current, length) => Math.max(current, length), 0) + margin; + return activeChoices.map(choice => indent(createOptionUsageRow(choice.value, choice.description, threshold), indentation)); +} + +function createDetailedUsage(context, flag) { + const option = getOptionsWithOpposites(context.detailedOptions).find(option => option.name === flag || option.alias === flag); + const header = createOptionUsageHeader(option); + const description = `\n\n${indent(option.description, 2)}`; + const choices = option.type !== "choice" ? "" : `\n\nValid options:\n\n${createChoiceUsages(option.choices, CHOICE_USAGE_MARGIN, CHOICE_USAGE_INDENTATION).join("\n")}`; + const optionDefaultValue = getOptionDefaultValue(context, option.name); + const defaults = optionDefaultValue !== undefined ? `\n\nDefault: ${createDefaultValueDisplay(optionDefaultValue)}` : ""; + const pluginDefaults = option.pluginDefaults && Object.keys(option.pluginDefaults).length ? `\nPlugin defaults:${Object.keys(option.pluginDefaults).map(key => `\n* ${key}: ${createDefaultValueDisplay(option.pluginDefaults[key])}`)}` : ""; + return `${header}${description}${choices}${defaults}${pluginDefaults}`; +} + +function getOptionDefaultValue(context, optionName) { + // --no-option + if (!(optionName in context.detailedOptionMap)) { + return; + } + + const option = context.detailedOptionMap[optionName]; + + if (option.default !== undefined) { + return option.default; + } + + const optionCamelName = camelcase(optionName); + + if (optionCamelName in context.apiDefaultOptions) { + return context.apiDefaultOptions[optionCamelName]; + } +} + +function indent(str, spaces) { + return str.replace(/^/gm, " ".repeat(spaces)); +} + +function createLogger(logLevel) { + return { + warn: createLogFunc("warn", "yellow"), + error: createLogFunc("error", "red"), + debug: createLogFunc("debug", "blue"), + log: createLogFunc("log") + }; + + function createLogFunc(loggerName, color) { + if (!shouldLog(loggerName)) { + return () => {}; + } + + const prefix = color ? `[${source[color](loggerName)}] ` : ""; + return function (message, opts) { + opts = Object.assign({ + newline: true + }, opts); + const stream = process[loggerName === "log" ? "stdout" : "stderr"]; + stream.write(message.replace(/^/gm, prefix) + (opts.newline ? "\n" : "")); + }; + } + + function shouldLog(loggerName) { + switch (logLevel) { + case "silent": + return false; + + case "debug": + if (loggerName === "debug") { + return true; + } + + // fall through + + case "log": + if (loggerName === "log") { + return true; + } + + // fall through + + case "warn": + if (loggerName === "warn") { + return true; + } + + // fall through + + case "error": + return loggerName === "error"; + } + } +} + +function normalizeDetailedOption(name, option) { + return Object.assign({ + category: coreOptions$1.CATEGORY_OTHER + }, option, { + choices: option.choices && option.choices.map(choice => { + const newChoice = Object.assign({ + description: "", + deprecated: false + }, typeof choice === "object" ? choice : { + value: choice + }); + /* istanbul ignore next */ + + if (newChoice.value === true) { + newChoice.value = ""; // backward compatibility for original boolean option + } + + return newChoice; + }) + }); +} + +function normalizeDetailedOptionMap(detailedOptionMap) { + return fromPairs_1(Object.entries(detailedOptionMap).sort(([leftName], [rightName]) => leftName.localeCompare(rightName)).map(([name, option]) => [name, normalizeDetailedOption(name, option)])); +} + +function createMinimistOptions(detailedOptions) { + const [boolean, string] = partition_1(detailedOptions, ({ + type + }) => type === "boolean").map(detailedOptions => flatten_1(detailedOptions.map(({ + name, + alias + }) => alias ? [name, alias] : [name]))); + const defaults = fromPairs_1(detailedOptions.filter(option => !option.deprecated && (!option.forwardToApi || option.name === "plugin" || option.name === "plugin-search-dir") && option.default !== undefined).map(option => [option.name, option.default])); + return { + // we use vnopts' AliasSchema to handle aliases for better error messages + alias: {}, + boolean, + string, + default: defaults + }; +} + +function createApiDetailedOptionMap(detailedOptions) { + return fromPairs_1(detailedOptions.filter(option => option.forwardToApi && option.forwardToApi !== option.name).map(option => [option.forwardToApi, option])); +} + +function createDetailedOptionMap(supportOptions) { + return fromPairs_1(supportOptions.map(option => { + const newOption = Object.assign({}, option, { + name: option.cliName || dashify(option.name), + description: option.cliDescription || option.description, + category: option.cliCategory || coreOptions$1.CATEGORY_FORMAT, + forwardToApi: option.name + }); + /* istanbul ignore next */ + + if (option.deprecated) { + delete newOption.forwardToApi; + delete newOption.description; + delete newOption.oppositeDescription; + newOption.deprecated = true; + } + + return [newOption.name, newOption]; + })); +} //-----------------------------context-util-start------------------------------- + +/** + * @typedef {Object} Context + * @property logger + * @property {string[]} args + * @property argv + * @property {string[]} filePatterns + * @property {any[]} supportOptions + * @property detailedOptions + * @property detailedOptionMap + * @property apiDefaultOptions + * @property languages + * @property {Partial[]} stack + */ + +/** @returns {Context} */ + + +function createContext(args) { + const context = { + args, + stack: [] + }; + updateContextArgv(context); + normalizeContextArgv(context, ["loglevel", "plugin", "plugin-search-dir"]); + context.logger = createLogger(context.argv.loglevel); + updateContextArgv(context, context.argv.plugin, context.argv["plugin-search-dir"]); + return ( + /** @type {Context} */ + context + ); +} + +function initContext(context) { + // split into 2 step so that we could wrap this in a `try..catch` in cli/index.js + normalizeContextArgv(context); +} +/** + * @param {Context} context + * @param {string[]} plugins + * @param {string[]=} pluginSearchDirs + */ + + +function updateContextOptions(context, plugins, pluginSearchDirs) { + const { + options: supportOptions, + languages + } = src.getSupportInfo({ + showDeprecated: true, + showUnreleased: true, + showInternal: true, + plugins, + pluginSearchDirs + }); + const detailedOptionMap = normalizeDetailedOptionMap(Object.assign({}, createDetailedOptionMap(supportOptions), constant$1.options)); + const detailedOptions = arrayify(detailedOptionMap, "name"); + const apiDefaultOptions = Object.assign({}, optionsModule.hiddenDefaults, fromPairs_1(supportOptions.filter(({ + deprecated + }) => !deprecated).map(option => [option.name, option.default]))); + Object.assign(context, { + supportOptions, + detailedOptions, + detailedOptionMap, + apiDefaultOptions, + languages + }); +} +/** + * @param {Context} context + * @param {string[]} plugins + * @param {string[]=} pluginSearchDirs + */ + + +function pushContextPlugins(context, plugins, pluginSearchDirs) { + context.stack.push(pick_1(context, ["supportOptions", "detailedOptions", "detailedOptionMap", "apiDefaultOptions", "languages"])); + updateContextOptions(context, plugins, pluginSearchDirs); +} +/** + * @param {Context} context + */ + + +function popContextPlugins(context) { + Object.assign(context, context.stack.pop()); +} + +function updateContextArgv(context, plugins, pluginSearchDirs) { + pushContextPlugins(context, plugins, pluginSearchDirs); + const minimistOptions = createMinimistOptions(context.detailedOptions); + const argv = minimist_1(context.args, minimistOptions); + context.argv = argv; + context.filePatterns = argv._; +} + +function normalizeContextArgv(context, keys) { + const detailedOptions = !keys ? context.detailedOptions : context.detailedOptions.filter(option => keys.includes(option.name)); + const argv = !keys ? context.argv : pick_1(context.argv, keys); + context.argv = optionsNormalizer.normalizeCliOptions(argv, detailedOptions, { + logger: context.logger + }); +} //------------------------------context-util-end-------------------------------- + + +var util$1 = { + createContext, + createDetailedOptionMap, + createDetailedUsage, + createUsage, + format, + formatFiles, + formatStdin, + initContext, + logResolvedConfigPathOrDie, + logFileInfoOrDie, + normalizeDetailedOptionMap +}; + +var require$$1 = getCjsExportFromNamespace(_package$1); + +pleaseUpgradeNode(require$$1); // eslint-disable-next-line no-restricted-modules + +function run(args) { + const context = util$1.createContext(args); + + try { + util$1.initContext(context); + context.logger.debug(`normalized argv: ${JSON.stringify(context.argv)}`); + + if (context.argv.check && context.argv["list-different"]) { + context.logger.error("Cannot use --check and --list-different together."); + process.exit(1); + } + + if (context.argv.write && context.argv["debug-check"]) { + context.logger.error("Cannot use --write and --debug-check together."); + process.exit(1); + } + + if (context.argv["find-config-path"] && context.filePatterns.length) { + context.logger.error("Cannot use --find-config-path with multiple files"); + process.exit(1); + } + + if (context.argv["file-info"] && context.filePatterns.length) { + context.logger.error("Cannot use --file-info with multiple files"); + process.exit(1); + } + + if (context.argv.version) { + context.logger.log(src.version); + process.exit(0); + } + + if (context.argv.help !== undefined) { + context.logger.log(typeof context.argv.help === "string" && context.argv.help !== "" ? util$1.createDetailedUsage(context, context.argv.help) : util$1.createUsage(context)); + process.exit(0); + } + + if (context.argv["support-info"]) { + context.logger.log(src.format(fastJsonStableStringify(src.getSupportInfo()), { + parser: "json" + })); + process.exit(0); + } + + const hasFilePatterns = context.filePatterns.length !== 0; + const useStdin = !hasFilePatterns && (!process.stdin.isTTY || context.args["stdin-filepath"]); + + if (context.argv["find-config-path"]) { + util$1.logResolvedConfigPathOrDie(context); + } else if (context.argv["file-info"]) { + util$1.logFileInfoOrDie(context); + } else if (useStdin) { + util$1.formatStdin(context); + } else if (hasFilePatterns) { + util$1.formatFiles(context); + } else { + context.logger.log(util$1.createUsage(context)); + process.exit(1); + } + } catch (error) { + context.logger.error(error.message); + process.exit(1); + } +} + +var cli = { + run +}; + +cli.run(process.argv.slice(2)); diff --git a/node_modules/prettier/doc.js b/node_modules/prettier/doc.js new file mode 100644 index 0000000..e9aa3da --- /dev/null +++ b/node_modules/prettier/doc.js @@ -0,0 +1,3779 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.doc = factory()); +}(this, (function () { 'use strict'; + + /** + * @param {Doc[]} parts + * @returns Doc + */ + + + function concat(parts) { + // access the internals of a document directly. + // if(parts.length === 1) { + // // If it's a single document, no need to concat it. + // return parts[0]; + // } + + + return { + type: "concat", + parts + }; + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function indent(contents) { + + return { + type: "indent", + contents + }; + } + /** + * @param {number | string} n + * @param {Doc} contents + * @returns Doc + */ + + + function align(n, contents) { + + return { + type: "align", + contents, + n + }; + } + /** + * @param {Doc} contents + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + + function group(contents, opts) { + opts = opts || {}; + + return { + type: "group", + id: opts.id, + contents, + break: !!opts.shouldBreak, + expandedStates: opts.expandedStates + }; + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function dedentToRoot(contents) { + return align(-Infinity, contents); + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function markAsRoot(contents) { + // @ts-ignore - TBD ???: + return align({ + type: "root" + }, contents); + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function dedent(contents) { + return align(-1, contents); + } + /** + * @param {Doc[]} states + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + + function conditionalGroup(states, opts) { + return group(states[0], Object.assign({}, opts, { + expandedStates: states + })); + } + /** + * @param {Doc[]} parts + * @returns Doc + */ + + + function fill(parts) { + + return { + type: "fill", + parts + }; + } + /** + * @param {Doc} [breakContents] + * @param {Doc} [flatContents] + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + + function ifBreak(breakContents, flatContents, opts) { + opts = opts || {}; + + return { + type: "if-break", + breakContents, + flatContents, + groupId: opts.groupId + }; + } + /** + * @param {Doc} contents + * @returns Doc + */ + + + function lineSuffix(contents) { + + return { + type: "line-suffix", + contents + }; + } + + const lineSuffixBoundary = { + type: "line-suffix-boundary" + }; + const breakParent = { + type: "break-parent" + }; + const trim = { + type: "trim" + }; + const line = { + type: "line" + }; + const softline = { + type: "line", + soft: true + }; + const hardline = concat([{ + type: "line", + hard: true + }, breakParent]); + const literalline = concat([{ + type: "line", + hard: true, + literal: true + }, breakParent]); + const cursor = { + type: "cursor", + placeholder: Symbol("cursor") + }; + /** + * @param {Doc} sep + * @param {Doc[]} arr + * @returns Doc + */ + + function join(sep, arr) { + const res = []; + + for (let i = 0; i < arr.length; i++) { + if (i !== 0) { + res.push(sep); + } + + res.push(arr[i]); + } + + return concat(res); + } + /** + * @param {Doc} doc + * @param {number} size + * @param {number} tabWidth + */ + + + function addAlignmentToDoc(doc, size, tabWidth) { + let aligned = doc; + + if (size > 0) { + // Use indent to add tabs for all the levels of tabs we need + for (let i = 0; i < Math.floor(size / tabWidth); ++i) { + aligned = indent(aligned); + } // Use align for all the spaces that are needed + + + aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current + // indentation, so we use -Infinity to reset the indentation to 0 + + aligned = align(-Infinity, aligned); + } + + return aligned; + } + + var docBuilders = { + concat, + join, + line, + softline, + hardline, + literalline, + group, + conditionalGroup, + fill, + lineSuffix, + lineSuffixBoundary, + cursor, + breakParent, + ifBreak, + trim, + indent, + align, + addAlignmentToDoc, + markAsRoot, + dedentToRoot, + dedent + }; + + var ansiRegex = ({ + onlyFirst = false + } = {}) => { + const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[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'); + }; + + var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + + /* eslint-disable yoda */ + + 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; + }; + + var isFullwidthCodePoint_1 = isFullwidthCodePoint; + var _default = isFullwidthCodePoint; + isFullwidthCodePoint_1.default = _default; + + var emojiRegex = function emojiRegex() { + // 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\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\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; + }; + + const stringWidth = string => { + string = string.replace(emojiRegex(), ' '); + + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + 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_1(code) ? 2 : 1; + } + + return width; + }; + + var stringWidth_1 = stringWidth; // TODO: remove this in the next major version + + var _default$1 = stringWidth; + stringWidth_1.default = _default$1; + + var escapeStringRegexp = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + + + return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); + }; + + var getLast = arr => arr[arr.length - 1]; + + function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; + } + + function _taggedTemplateLiteral(strings, raw) { + if (!raw) { + raw = strings.slice(0); + } + + return Object.freeze(Object.defineProperties(strings, { + raw: { + value: Object.freeze(raw) + } + })); + } + + var global$1 = typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; + + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + + function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined'); + } + + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + 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); + } + + function nextTick(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); + }; + + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + function binding(name) { + throw new Error('process.binding is not supported'); + } + function cwd() { + return '/'; + } + function chdir(dir) { + throw new Error('process.chdir is not supported'); + } + function umask() { + return 0; + } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + + var performance = global$1.performance || {}; + + var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { + return new Date().getTime(); + }; // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + + + function hrtime(previousTimestamp) { + var clocktime = performanceNow.call(performance) * 1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor(clocktime % 1 * 1e9); + + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + + if (nanoseconds < 0) { + seconds--; + nanoseconds += 1e9; + } + } + + return [seconds, nanoseconds]; + } + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {}; + var debug_1 = debug; + + // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + const SEMVER_SPEC_VERSION = '2.0.0'; + const MAX_LENGTH = 256; + const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ + 9007199254740991; // Max safe segment length for coercion. + + const MAX_SAFE_COMPONENT_LENGTH = 16; + var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH + }; + + function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; + } + + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } + + function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); + } + + var re_1 = createCommonjsModule(function (module, exports) { + const { + MAX_SAFE_COMPONENT_LENGTH + } = constants; + exports = module.exports = {}; // The actual regexps go on exports.re + + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug_1(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIER], ")")); + createToken('MAINVERSIONLOOSE', "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")\\.") + "(".concat(src[t.NUMERICIDENTIFIERLOOSE], ")")); // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', "(?:".concat(src[t.NUMERICIDENTIFIER], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); + createToken('PRERELEASEIDENTIFIERLOOSE', "(?:".concat(src[t.NUMERICIDENTIFIERLOOSE], "|").concat(src[t.NONNUMERICIDENTIFIER], ")")); // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', "(?:-(".concat(src[t.PRERELEASEIDENTIFIER], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIER], ")*))")); + createToken('PRERELEASELOOSE', "(?:-?(".concat(src[t.PRERELEASEIDENTIFIERLOOSE], "(?:\\.").concat(src[t.PRERELEASEIDENTIFIERLOOSE], ")*))")); // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', "(?:\\+(".concat(src[t.BUILDIDENTIFIER], "(?:\\.").concat(src[t.BUILDIDENTIFIER], ")*))")); // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', "v?".concat(src[t.MAINVERSION]).concat(src[t.PRERELEASE], "?").concat(src[t.BUILD], "?")); + createToken('FULL', "^".concat(src[t.FULLPLAIN], "$")); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + + createToken('LOOSEPLAIN', "[v=\\s]*".concat(src[t.MAINVERSIONLOOSE]).concat(src[t.PRERELEASELOOSE], "?").concat(src[t.BUILD], "?")); + createToken('LOOSE', "^".concat(src[t.LOOSEPLAIN], "$")); + createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + + createToken('XRANGEIDENTIFIERLOOSE', "".concat(src[t.NUMERICIDENTIFIERLOOSE], "|x|X|\\*")); + createToken('XRANGEIDENTIFIER', "".concat(src[t.NUMERICIDENTIFIER], "|x|X|\\*")); + createToken('XRANGEPLAIN', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIER], ")") + "(?:".concat(src[t.PRERELEASE], ")?").concat(src[t.BUILD], "?") + ")?)?"); + createToken('XRANGEPLAINLOOSE', "[v=\\s]*(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:\\.(".concat(src[t.XRANGEIDENTIFIERLOOSE], ")") + "(?:".concat(src[t.PRERELEASELOOSE], ")?").concat(src[t.BUILD], "?") + ")?)?"); + createToken('XRANGE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAIN], "$")); + createToken('XRANGELOOSE', "^".concat(src[t.GTLT], "\\s*").concat(src[t.XRANGEPLAINLOOSE], "$")); // Coercion. + // Extract anything that could conceivably be a part of a valid semver + + createToken('COERCE', "".concat('(^|[^\\d])' + '(\\d{1,').concat(MAX_SAFE_COMPONENT_LENGTH, "})") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:\\.(\\d{1,".concat(MAX_SAFE_COMPONENT_LENGTH, "}))?") + "(?:$|[^\\d])"); + createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges. + // Meaning is "reasonably at or greater than" + + createToken('LONETILDE', '(?:~>?)'); + createToken('TILDETRIM', "(\\s*)".concat(src[t.LONETILDE], "\\s+"), true); + exports.tildeTrimReplace = '$1~'; + createToken('TILDE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAIN], "$")); + createToken('TILDELOOSE', "^".concat(src[t.LONETILDE]).concat(src[t.XRANGEPLAINLOOSE], "$")); // Caret ranges. + // Meaning is "at least and backwards compatible with" + + createToken('LONECARET', '(?:\\^)'); + createToken('CARETTRIM', "(\\s*)".concat(src[t.LONECARET], "\\s+"), true); + exports.caretTrimReplace = '$1^'; + createToken('CARET', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAIN], "$")); + createToken('CARETLOOSE', "^".concat(src[t.LONECARET]).concat(src[t.XRANGEPLAINLOOSE], "$")); // A simple gt/lt/eq thing, or just "" to indicate "any version" + + createToken('COMPARATORLOOSE', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], ")$|^$")); + createToken('COMPARATOR', "^".concat(src[t.GTLT], "\\s*(").concat(src[t.FULLPLAIN], ")$|^$")); // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + + createToken('COMPARATORTRIM', "(\\s*)".concat(src[t.GTLT], "\\s*(").concat(src[t.LOOSEPLAIN], "|").concat(src[t.XRANGEPLAIN], ")"), true); + exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + + createToken('HYPHENRANGE', "^\\s*(".concat(src[t.XRANGEPLAIN], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAIN], ")") + "\\s*$"); + createToken('HYPHENRANGELOOSE', "^\\s*(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s+-\\s+" + "(".concat(src[t.XRANGEPLAINLOOSE], ")") + "\\s*$"); // Star ranges basically just allow anything at all. + + createToken('STAR', '(<|>)?=?\\s*\\*'); // >=0.0.0 is like a star + + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); + }); + + const numeric = /^[0-9]+$/; + + const compareIdentifiers = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + }; + + const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); + + var identifiers = { + compareIdentifiers, + rcompareIdentifiers + }; + + const { + MAX_LENGTH: MAX_LENGTH$1, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1 + } = constants; + const { + re, + t + } = re_1; + const { + compareIdentifiers: compareIdentifiers$1 + } = identifiers; + + class SemVer { + constructor(version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError("Invalid Version: ".concat(version)); + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError("version is longer than ".concat(MAX_LENGTH$1, " characters")); + } + + debug_1('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + + this.includePrerelease = !!options.includePrerelease; + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); + + if (!m) { + throw new TypeError("Invalid Version: ".concat(version)); + } + + this.raw = version; // these are actually numbers + + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) { + throw new TypeError('Invalid major version'); + } + + if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) { + throw new TypeError('Invalid minor version'); + } + + if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) { + throw new TypeError('Invalid patch version'); + } // numberify any prerelease numeric ids + + + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map(id => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + + if (num >= 0 && num < MAX_SAFE_INTEGER$1) { + return num; + } + } + + return id; + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format() { + this.version = "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); + + if (this.prerelease.length) { + this.version += "-".concat(this.prerelease.join('.')); + } + + return this.version; + } + + toString() { + return this.version; + } + + compare(other) { + debug_1('SemVer.compare', this.version, this.options, other); + + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0; + } + + other = new SemVer(other, this.options); + } + + if (other.version === this.version) { + return 0; + } + + return this.compareMain(other) || this.comparePre(other); + } + + compareMain(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch); + } + + comparePre(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } // NOT having a prerelease is > having one + + + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + + let i = 0; + + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug_1('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers$1(a, b); + } + } while (++i); + } + + compareBuild(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + let i = 0; + + do { + const a = this.build[i]; + const b = other.build[i]; + debug_1('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers$1(a, b); + } + } while (++i); + } // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + + + inc(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + + this.patch = 0; + this.prerelease = []; + break; + + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + + break; + + default: + throw new Error("invalid increment argument: ".concat(release)); + } + + this.format(); + this.raw = this.version; + return this; + } + + } + + var semver = SemVer; + + const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose)); + + var compare_1 = compare; + + const lt = (a, b, loose) => compare_1(a, b, loose) < 0; + + var lt_1 = lt; + + const gte = (a, b, loose) => compare_1(a, b, loose) >= 0; + + var gte_1 = gte; + + var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({ + [keyName]: key + }, value)); + + var name = "prettier"; + var version$1 = "2.1.2"; + var description = "Prettier is an opinionated code formatter"; + var bin = "./bin/prettier.js"; + var repository = "prettier/prettier"; + var homepage = "https://prettier.io"; + var author = "James Long"; + var license = "MIT"; + var main = "./index.js"; + var browser$1 = "./standalone.js"; + var unpkg = "./standalone.js"; + var engines = { + node: ">=10.13.0" + }; + var files = [ + "index.js", + "standalone.js", + "src", + "bin" + ]; + var dependencies = { + "@angular/compiler": "10.0.12", + "@babel/code-frame": "7.10.4", + "@babel/parser": "7.11.2", + "@glimmer/syntax": "0.59.0", + "@iarna/toml": "2.2.5", + "@typescript-eslint/typescript-estree": "3.10.0", + "angular-estree-parser": "2.2.0", + "angular-html-parser": "1.7.1", + camelcase: "6.0.0", + chalk: "4.1.0", + "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", + "cjk-regex": "2.0.0", + cosmiconfig: "7.0.0", + dashify: "2.0.0", + diff: "4.0.2", + editorconfig: "0.15.3", + "editorconfig-to-prettier": "0.1.1", + "escape-string-regexp": "4.0.0", + esutils: "2.0.3", + "fast-glob": "3.2.4", + "fast-json-stable-stringify": "2.1.0", + "find-parent-dir": "0.3.0", + "flow-parser": "0.132.0", + "get-stream": "6.0.0", + globby: "11.0.1", + graphql: "15.3.0", + "html-element-attributes": "2.2.1", + "html-styles": "1.0.0", + "html-tag-names": "1.1.5", + "html-void-elements": "1.0.5", + ignore: "4.0.6", + "jest-docblock": "26.0.0", + json5: "2.1.3", + leven: "3.1.0", + "lines-and-columns": "1.1.6", + "linguist-languages": "7.10.0", + lodash: "4.17.20", + mem: "6.1.0", + minimatch: "3.0.4", + minimist: "1.2.5", + "n-readlines": "1.0.0", + outdent: "0.7.1", + "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee", + "please-upgrade-node": "3.2.0", + "postcss-less": "3.1.4", + "postcss-media-query-parser": "0.2.3", + "postcss-scss": "2.1.1", + "postcss-selector-parser": "2.2.3", + "postcss-values-parser": "2.0.1", + "regexp-util": "1.2.2", + "remark-footnotes": "2.0.0", + "remark-math": "1.0.6", + "remark-parse": "8.0.3", + resolve: "1.17.0", + semver: "7.3.2", + "string-width": "4.2.0", + typescript: "4.0.2", + "unicode-regex": "3.0.0", + unified: "9.2.0", + vnopts: "1.0.2", + "yaml-unist-parser": "1.3.1" + }; + var devDependencies = { + "@babel/core": "7.11.4", + "@babel/preset-env": "7.11.0", + "@babel/types": "7.11.0", + "@glimmer/reference": "0.59.0", + "@rollup/plugin-alias": "3.1.1", + "@rollup/plugin-babel": "5.2.0", + "@rollup/plugin-commonjs": "14.0.0", + "@rollup/plugin-json": "4.1.0", + "@rollup/plugin-node-resolve": "9.0.0", + "@rollup/plugin-replace": "2.3.3", + "@types/estree": "0.0.45", + "@types/node": "14.6.0", + "@typescript-eslint/types": "3.10.0", + "babel-loader": "8.1.0", + benchmark: "2.1.4", + "builtin-modules": "3.1.0", + "cross-env": "7.0.2", + cspell: "4.1.0", + eslint: "7.7.0", + "eslint-config-prettier": "6.11.0", + "eslint-formatter-friendly": "7.0.0", + "eslint-plugin-import": "2.22.0", + "eslint-plugin-jest": "23.20.0", + "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules", + "eslint-plugin-react": "7.20.6", + "eslint-plugin-unicorn": "21.0.0", + execa: "4.0.3", + jest: "26.4.2", + "jest-snapshot-serializer-ansi": "1.0.0", + "jest-snapshot-serializer-raw": "1.1.0", + "jest-watch-typeahead": "0.6.0", + "npm-run-all": "4.1.5", + prettier: "2.1.1", + rimraf: "3.0.2", + rollup: "2.26.5", + "rollup-plugin-node-globals": "1.4.0", + "rollup-plugin-terser": "7.0.0", + shelljs: "0.8.4", + "snapshot-diff": "0.8.1", + "strip-ansi": "6.0.0", + "synchronous-promise": "2.0.13", + tempy: "0.6.0", + "terser-webpack-plugin": "4.1.0", + webpack: "4.44.1" + }; + var scripts = { + prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1", + "prepare-release": "yarn && yarn build && yarn test:dist", + test: "jest", + "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest", + "test:dist": "cross-env NODE_ENV=production jest", + "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest", + "test:integration": "jest tests_integration", + "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + lint: "run-p lint:*", + "lint:typecheck": "tsc", + "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly", + "lint:changelog": "node ./scripts/lint-changelog.js", + "lint:prettier": "prettier . \"!test*\" --check", + "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"", + "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"", + "lint:deps": "node ./scripts/check-deps.js", + fix: "run-s fix:eslint fix:prettier", + "fix:eslint": "yarn lint:eslint --fix", + "fix:prettier": "yarn lint:prettier --write", + build: "node ./scripts/build/build.js", + "build-docs": "node ./scripts/build-docs.js" + }; + var _package = { + name: name, + version: version$1, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + browser: browser$1, + unpkg: unpkg, + engines: engines, + files: files, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts + }; + + var _package$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name, + version: version$1, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + browser: browser$1, + unpkg: unpkg, + engines: engines, + files: files, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts, + 'default': _package + }); + + var lib = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either. + + function noop() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + } + + function createWeakMap() { + if (typeof WeakMap !== 'undefined') { + return new WeakMap(); + } else { + return fakeSetOrMap(); + } + } + /** + * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything. + */ + + + function fakeSetOrMap() { + return { + add: noop, + delete: noop, + get: noop, + set: noop, + has: function has(k) { + return false; + } + }; + } // Safe hasOwnProperty + + + var hop = Object.prototype.hasOwnProperty; + + var has = function has(obj, prop) { + return hop.call(obj, prop); + }; // Copy all own enumerable properties from source to target + + + function extend(target, source) { + for (var prop in source) { + if (has(source, prop)) { + target[prop] = source[prop]; + } + } + + return target; + } + + var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/; + var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/; + var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/; + var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/; + var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/; + + function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) { + // If first interpolated value is a reference to outdent, + // determine indentation level from the indentation of the interpolated value. + var indentationLevel = 0; + var match = strings[0].match(reDetectIndentation); + + if (match) { + indentationLevel = match[1].length; + } + + var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}"; + var reMatchIndent = new RegExp(reSource, 'g'); + + if (firstInterpolatedValueSetsIndentationLevel) { + strings = strings.slice(1); + } + + var newline = options.newline, + trimLeadingNewline = options.trimLeadingNewline, + trimTrailingNewline = options.trimTrailingNewline; + var normalizeNewlines = typeof newline === 'string'; + var l = strings.length; + var outdentedStrings = strings.map(function (v, i) { + // Remove leading indentation from all lines + v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string + + if (i === 0 && trimLeadingNewline) { + v = v.replace(reLeadingNewline, ''); + } // Trim a trailing newline from the last string + + + if (i === l - 1 && trimTrailingNewline) { + v = v.replace(reTrailingNewline, ''); + } // Normalize newlines + + + if (normalizeNewlines) { + v = v.replace(/\r\n|\n|\r/g, function (_) { + return newline; + }); + } + + return v; + }); + return outdentedStrings; + } + + function concatStringsAndValues(strings, values) { + var ret = ''; + + for (var i = 0, l = strings.length; i < l; i++) { + ret += strings[i]; + + if (i < l - 1) { + ret += values[i]; + } + } + + return ret; + } + + function isTemplateStringsArray(v) { + return has(v, 'raw') && has(v, 'length'); + } + /** + * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to + * makeInstance + * @param options + * @return {outdent} + */ + + + function createInstance(options) { + /** Cache of pre-processed template literal arrays */ + var arrayAutoIndentCache = createWeakMap(); + /** + * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent, + * before interpolated values are injected. + */ + + var arrayFirstInterpSetsIndentCache = createWeakMap(); + + function outdent(stringsOrOptions) { + var values = []; + + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + /* tslint:enable:no-shadowed-variable */ + + + if (isTemplateStringsArray(stringsOrOptions)) { + var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace? + + var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation + + var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache; + var renderedArray = cache.get(strings); + + if (!renderedArray) { + renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options); + cache.set(strings, renderedArray); + } + /** If no interpolated values, skip concatenation step */ + + + if (values.length === 0) { + return renderedArray[0]; + } + /** Concatenate string literals with interpolated values */ + + + var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values); + return rendered; + } else { + // Create and return a new instance of outdent with the given options + return createInstance(extend(extend({}, options), stringsOrOptions || {})); + } + } + + var fullOutdent = extend(outdent, { + string: function string(str) { + return _outdentArray([str], false, options)[0]; + } + }); + return fullOutdent; + } + + var defaultOutdent = createInstance({ + trimLeadingNewline: true, + trimTrailingNewline: true + }); + exports.outdent = defaultOutdent; // Named exports. Simple and preferred. + // import outdent from 'outdent'; + + exports.default = defaultOutdent; + + { + // In webpack harmony-modules environments, module.exports is read-only, + // so we fail gracefully. + try { + module.exports = defaultOutdent; + Object.defineProperty(defaultOutdent, '__esModule', { + value: true + }); + defaultOutdent.default = defaultOutdent; + defaultOutdent.outdent = defaultOutdent; + } catch (e) {} + } + }); + + function _templateObject6() { + const data = _taggedTemplateLiteral(["\n Require either '@prettier' or '@format' to be present in the file's first docblock comment\n in order for it to be formatted.\n "]); + + _templateObject6 = function _templateObject6() { + return data; + }; + + return data; + } + + function _templateObject5() { + const data = _taggedTemplateLiteral(["\n Format code starting at a given character offset.\n The range will extend backwards to the start of the first line containing the selected statement.\n This option cannot be used with --cursor-offset.\n "]); + + _templateObject5 = function _templateObject5() { + return data; + }; + + return data; + } + + function _templateObject4() { + const data = _taggedTemplateLiteral(["\n Format code ending at a given character offset (exclusive).\n The range will extend forwards to the end of the selected statement.\n This option cannot be used with --cursor-offset.\n "]); + + _templateObject4 = function _templateObject4() { + return data; + }; + + return data; + } + + function _templateObject3() { + const data = _taggedTemplateLiteral(["\n Custom directory that contains prettier plugins in node_modules subdirectory.\n Overrides default behavior when plugins are searched relatively to the location of Prettier.\n Multiple values are accepted.\n "]); + + _templateObject3 = function _templateObject3() { + return data; + }; + + return data; + } + + function _templateObject2() { + const data = _taggedTemplateLiteral(["\n Maintain existing\n (mixed values within one file are normalised by looking at what's used after the first line)\n "]); + + _templateObject2 = function _templateObject2() { + return data; + }; + + return data; + } + + function _templateObject() { + const data = _taggedTemplateLiteral(["\n Print (to stderr) where a cursor at the given position would move to after formatting.\n This option cannot be used with --range-start and --range-end.\n "]); + + _templateObject = function _templateObject() { + return data; + }; + + return data; + } + + const { + outdent + } = lib; + const CATEGORY_CONFIG = "Config"; + const CATEGORY_EDITOR = "Editor"; + const CATEGORY_FORMAT = "Format"; + const CATEGORY_OTHER = "Other"; + const CATEGORY_OUTPUT = "Output"; + const CATEGORY_GLOBAL = "Global"; + const CATEGORY_SPECIAL = "Special"; + /** + * @typedef {Object} OptionInfo + * @property {string} [since] - available since version + * @property {string} category + * @property {'int' | 'boolean' | 'choice' | 'path'} type + * @property {boolean} [array] - indicate it's an array of the specified type + * @property {OptionValueInfo} [default] + * @property {OptionRangeInfo} [range] - for type int + * @property {string} description + * @property {string} [deprecated] - deprecated since version + * @property {OptionRedirectInfo} [redirect] - redirect deprecated option + * @property {(value: any) => boolean} [exception] + * @property {OptionChoiceInfo[]} [choices] - for type choice + * @property {string} [cliName] + * @property {string} [cliCategory] + * @property {string} [cliDescription] + * + * @typedef {number | boolean | string} OptionValue + * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo + * + * @typedef {Object} OptionRedirectInfo + * @property {string} option + * @property {OptionValue} value + * + * @typedef {Object} OptionRangeInfo + * @property {number} start - recommended range start + * @property {number} end - recommended range end + * @property {number} step - recommended range step + * + * @typedef {Object} OptionChoiceInfo + * @property {boolean | string} value - boolean for the option that is originally boolean type + * @property {string} description + * @property {string} [since] - undefined if available since the first version of the option + * @property {string} [deprecated] - deprecated since version + * @property {OptionValueInfo} [redirect] - redirect deprecated value + */ + + /** @type {{ [name: string]: OptionInfo }} */ + + const options = { + cursorOffset: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: -1, + range: { + start: -1, + end: Infinity, + step: 1 + }, + description: outdent(_templateObject()), + cliCategory: CATEGORY_EDITOR + }, + endOfLine: { + since: "1.15.0", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "1.15.0", + value: "auto" + }, { + since: "2.0.0", + value: "lf" + }], + description: "Which end of line characters to apply.", + choices: [{ + value: "lf", + description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos" + }, { + value: "crlf", + description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows" + }, { + value: "cr", + description: "Carriage Return character only (\\r), used very rarely" + }, { + value: "auto", + description: outdent(_templateObject2()) + }] + }, + filepath: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "path", + description: "Specify the input filepath. This will be used to do parser inference.", + cliName: "stdin-filepath", + cliCategory: CATEGORY_OTHER, + cliDescription: "Path to the file to pretend that stdin comes from." + }, + insertPragma: { + since: "1.8.0", + category: CATEGORY_SPECIAL, + type: "boolean", + default: false, + description: "Insert @format pragma into file's first docblock comment.", + cliCategory: CATEGORY_OTHER + }, + parser: { + since: "0.0.10", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "0.0.10", + value: "babylon" + }, { + since: "1.13.0", + value: undefined + }], + description: "Which parser to use.", + exception: value => typeof value === "string" || typeof value === "function", + choices: [{ + value: "flow", + description: "Flow" + }, { + value: "babel", + since: "1.16.0", + description: "JavaScript" + }, { + value: "babel-flow", + since: "1.16.0", + description: "Flow" + }, { + value: "babel-ts", + since: "2.0.0", + description: "TypeScript" + }, { + value: "typescript", + since: "1.4.0", + description: "TypeScript" + }, { + value: "css", + since: "1.7.1", + description: "CSS" + }, { + value: "less", + since: "1.7.1", + description: "Less" + }, { + value: "scss", + since: "1.7.1", + description: "SCSS" + }, { + value: "json", + since: "1.5.0", + description: "JSON" + }, { + value: "json5", + since: "1.13.0", + description: "JSON5" + }, { + value: "json-stringify", + since: "1.13.0", + description: "JSON.stringify" + }, { + value: "graphql", + since: "1.5.0", + description: "GraphQL" + }, { + value: "markdown", + since: "1.8.0", + description: "Markdown" + }, { + value: "mdx", + since: "1.15.0", + description: "MDX" + }, { + value: "vue", + since: "1.10.0", + description: "Vue" + }, { + value: "yaml", + since: "1.14.0", + description: "YAML" + }, { + value: "glimmer", + since: null, + description: "Handlebars" + }, { + value: "html", + since: "1.15.0", + description: "HTML" + }, { + value: "angular", + since: "1.15.0", + description: "Angular" + }, { + value: "lwc", + since: "1.17.0", + description: "Lightning Web Components" + }] + }, + plugins: { + since: "1.10.0", + type: "path", + array: true, + default: [{ + value: [] + }], + category: CATEGORY_GLOBAL, + description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.", + exception: value => typeof value === "string" || typeof value === "object", + cliName: "plugin", + cliCategory: CATEGORY_CONFIG + }, + pluginSearchDirs: { + since: "1.13.0", + type: "path", + array: true, + default: [{ + value: [] + }], + category: CATEGORY_GLOBAL, + description: outdent(_templateObject3()), + exception: value => typeof value === "string" || typeof value === "object", + cliName: "plugin-search-dir", + cliCategory: CATEGORY_CONFIG + }, + printWidth: { + since: "0.0.0", + category: CATEGORY_GLOBAL, + type: "int", + default: 80, + description: "The line length where Prettier will try wrap.", + range: { + start: 0, + end: Infinity, + step: 1 + } + }, + rangeEnd: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: Infinity, + range: { + start: 0, + end: Infinity, + step: 1 + }, + description: outdent(_templateObject4()), + cliCategory: CATEGORY_EDITOR + }, + rangeStart: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: 0, + range: { + start: 0, + end: Infinity, + step: 1 + }, + description: outdent(_templateObject5()), + cliCategory: CATEGORY_EDITOR + }, + requirePragma: { + since: "1.7.0", + category: CATEGORY_SPECIAL, + type: "boolean", + default: false, + description: outdent(_templateObject6()), + cliCategory: CATEGORY_OTHER + }, + tabWidth: { + type: "int", + category: CATEGORY_GLOBAL, + default: 2, + description: "Number of spaces per indentation level.", + range: { + start: 0, + end: Infinity, + step: 1 + } + }, + useTabs: { + since: "1.0.0", + category: CATEGORY_GLOBAL, + type: "boolean", + default: false, + description: "Indent with tabs instead of spaces." + }, + embeddedLanguageFormatting: { + since: "2.1.0", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "2.1.0", + value: "auto" + }], + description: "Control how Prettier formats quoted code embedded in the file.", + choices: [{ + value: "auto", + description: "Format embedded code if Prettier can automatically identify it." + }, { + value: "off", + description: "Never automatically format embedded code." + }] + } + }; + var coreOptions = { + CATEGORY_CONFIG, + CATEGORY_EDITOR, + CATEGORY_FORMAT, + CATEGORY_OTHER, + CATEGORY_OUTPUT, + CATEGORY_GLOBAL, + CATEGORY_SPECIAL, + options + }; + + var require$$3 = getCjsExportFromNamespace(_package$1); + + const semver$1 = { + compare: compare_1, + lt: lt_1, + gte: gte_1 + }; + const currentVersion = require$$3.version; + const coreOptions$1 = coreOptions.options; + /** + * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version + * of this function created by `withPlugins`. Don't pass them here directly. + * @param {object} param0 + * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`. + * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`. + * @param {boolean=} param0.showUnreleased + * @param {boolean=} param0.showDeprecated + * @param {boolean=} param0.showInternal + */ + + function getSupportInfo({ + plugins = [], + showUnreleased = false, + showDeprecated = false, + showInternal = false + } = {}) { + // pre-release version is smaller than the normal version in semver, + // we need to treat it as the normal one so as to test new features. + const version = currentVersion.split("-", 1)[0]; + const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince); + const options = arrayify(Object.assign({}, ...plugins.map(({ + options + }) => options), coreOptions$1), "name").filter(option => filterSince(option) && filterDeprecated(option)).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1).map(mapInternal).map(option => { + option = Object.assign({}, option); + + if (Array.isArray(option.default)) { + option.default = option.default.length === 1 ? option.default[0].value : option.default.filter(filterSince).sort((info1, info2) => semver$1.compare(info2.since, info1.since))[0].value; + } + + if (Array.isArray(option.choices)) { + option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option)); + + if (option.name === "parser") { + collectParsersFromLanguages(option, languages, plugins); + } + } + + const pluginDefaults = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined).reduce((reduced, plugin) => { + reduced[plugin.name] = plugin.defaultOptions[option.name]; + return reduced; + }, {}); + return Object.assign({}, option, { + pluginDefaults + }); + }); + return { + languages, + options + }; + + function filterSince(object) { + return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since); + } + + function filterDeprecated(object) { + return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated); + } + + function mapInternal(object) { + if (showInternal) { + return object; + } + + const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]); + + return newObject; + } + } + + function collectParsersFromLanguages(option, languages, plugins) { + const existingValues = new Set(option.choices.map(choice => choice.value)); + + for (const language of languages) { + if (language.parsers) { + for (const value of language.parsers) { + if (!existingValues.has(value)) { + existingValues.add(value); + const plugin = plugins.find(plugin => plugin.parsers && plugin.parsers[value]); + let description = language.name; + + if (plugin && plugin.name) { + description += " (plugin: ".concat(plugin.name, ")"); + } + + option.choices.push({ + value, + description + }); + } + } + } + } + } + + var support = { + getSupportInfo + }; + + const notAsciiRegex = /[^\x20-\x7F]/; + + const getPenultimate = arr => arr[arr.length - 2]; + /** + * @typedef {{backwards?: boolean}} SkipOptions + */ + + /** + * @param {string | RegExp} chars + * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + + function skip(chars) { + return (text, index, opts) => { + const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having + // to check for failures (did someone say monads?). + + /* istanbul ignore next */ + + if (index === false) { + return false; + } + + const { + length + } = text; + let cursor = index; + + while (cursor >= 0 && cursor < length) { + const c = text.charAt(cursor); + + if (chars instanceof RegExp) { + if (!chars.test(c)) { + return cursor; + } + } else if (!chars.includes(c)) { + return cursor; + } + + backwards ? cursor-- : cursor++; + } + + if (cursor === -1 || cursor === length) { + // If we reached the beginning or end of the file, return the + // out-of-bounds cursor. It's up to the caller to handle this + // correctly. We don't want to indicate `false` though if it + // actually skipped valid characters. + return cursor; + } + + return false; + }; + } + /** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + + const skipWhitespace = skip(/\s/); + /** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + const skipSpaces = skip(" \t"); + /** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + const skipToLineEnd = skip(",; \t"); + /** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + const skipEverythingButNewLine = skip(/[^\n\r]/); + /** + * @param {string} text + * @param {number | false} index + * @returns {number | false} + */ + + function skipInlineComment(text, index) { + /* istanbul ignore next */ + if (index === false) { + return false; + } + + if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") { + for (let i = index + 2; i < text.length; ++i) { + if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") { + return i + 2; + } + } + } + + return index; + } + /** + * @param {string} text + * @param {number | false} index + * @returns {number | false} + */ + + + function skipTrailingComment(text, index) { + /* istanbul ignore next */ + if (index === false) { + return false; + } + + if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") { + return skipEverythingButNewLine(text, index); + } + + return index; + } // This one doesn't use the above helper function because it wants to + // test \r\n in order and `skip` doesn't support ordering and we only + // want to skip one newline. It's simple to implement. + + /** + * @param {string} text + * @param {number | false} index + * @param {SkipOptions=} opts + * @returns {number | false} + */ + + + function skipNewline(text, index, opts) { + const backwards = opts && opts.backwards; + + if (index === false) { + return false; + } + + const atIndex = text.charAt(index); + + if (backwards) { + // We already replace `\r\n` with `\n` before parsing + + /* istanbul ignore next */ + if (text.charAt(index - 1) === "\r" && atIndex === "\n") { + return index - 2; + } + + if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { + return index - 1; + } + } else { + // We already replace `\r\n` with `\n` before parsing + + /* istanbul ignore next */ + if (atIndex === "\r" && text.charAt(index + 1) === "\n") { + return index + 2; + } + + if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { + return index + 1; + } + } + + return index; + } + /** + * @param {string} text + * @param {number} index + * @param {SkipOptions=} opts + * @returns {boolean} + */ + + + function hasNewline(text, index, opts) { + opts = opts || {}; + const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); + const idx2 = skipNewline(text, idx, opts); + return idx !== idx2; + } + /** + * @param {string} text + * @param {number} start + * @param {number} end + * @returns {boolean} + */ + + + function hasNewlineInRange(text, start, end) { + for (let i = start; i < end; ++i) { + if (text.charAt(i) === "\n") { + return true; + } + } + + return false; + } // Note: this function doesn't ignore leading comments unlike isNextLineEmpty + + /** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locStart + */ + + + function isPreviousLineEmpty(text, node, locStart) { + /** @type {number | false} */ + let idx = locStart(node) - 1; + idx = skipSpaces(text, idx, { + backwards: true + }); + idx = skipNewline(text, idx, { + backwards: true + }); + idx = skipSpaces(text, idx, { + backwards: true + }); + const idx2 = skipNewline(text, idx, { + backwards: true + }); + return idx !== idx2; + } + /** + * @param {string} text + * @param {number} index + * @returns {boolean} + */ + + + function isNextLineEmptyAfterIndex(text, index) { + /** @type {number | false} */ + let oldIdx = null; + /** @type {number | false} */ + + let idx = index; + + while (idx !== oldIdx) { + // We need to skip all the potential trailing inline comments + oldIdx = idx; + idx = skipToLineEnd(text, idx); + idx = skipInlineComment(text, idx); + idx = skipSpaces(text, idx); + } + + idx = skipTrailingComment(text, idx); + idx = skipNewline(text, idx); + return idx !== false && hasNewline(text, idx); + } + /** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {boolean} + */ + + + function isNextLineEmpty(text, node, locEnd) { + return isNextLineEmptyAfterIndex(text, locEnd(node)); + } + /** + * @param {string} text + * @param {number} idx + * @returns {number | false} + */ + + + function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) { + /** @type {number | false} */ + let oldIdx = null; + /** @type {number | false} */ + + let nextIdx = idx; + + while (nextIdx !== oldIdx) { + oldIdx = nextIdx; + nextIdx = skipSpaces(text, nextIdx); + nextIdx = skipInlineComment(text, nextIdx); + nextIdx = skipTrailingComment(text, nextIdx); + nextIdx = skipNewline(text, nextIdx); + } + + return nextIdx; + } + /** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {number | false} + */ + + + function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) { + return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node)); + } + /** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {string} + */ + + + function getNextNonSpaceNonCommentCharacter(text, node, locEnd) { + return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback? + getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)); + } // Not using, but it's public utils + + /* istanbul ignore next */ + + /** + * @param {string} text + * @param {number} index + * @param {SkipOptions=} opts + * @returns {boolean} + */ + + + function hasSpaces(text, index, opts) { + opts = opts || {}; + const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); + return idx !== index; + } + /** + * @param {string} value + * @param {number} tabWidth + * @param {number=} startIndex + * @returns {number} + */ + + + function getAlignmentSize(value, tabWidth, startIndex) { + startIndex = startIndex || 0; + let size = 0; + + for (let i = startIndex; i < value.length; ++i) { + if (value[i] === "\t") { + // Tabs behave in a way that they are aligned to the nearest + // multiple of tabWidth: + // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4 + // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ... + size = size + tabWidth - size % tabWidth; + } else { + size++; + } + } + + return size; + } + /** + * @param {string} value + * @param {number} tabWidth + * @returns {number} + */ + + + function getIndentSize(value, tabWidth) { + const lastNewlineIndex = value.lastIndexOf("\n"); + + if (lastNewlineIndex === -1) { + return 0; + } + + return getAlignmentSize( // All the leading whitespaces + value.slice(lastNewlineIndex + 1).match(/^[\t ]*/)[0], tabWidth); + } + /** + * @typedef {'"' | "'"} Quote + */ + + /** + * + * @param {string} raw + * @param {Quote} preferredQuote + * @returns {Quote} + */ + + + function getPreferredQuote(raw, preferredQuote) { + // `rawContent` is the string exactly like it appeared in the input source + // code, without its enclosing quotes. + const rawContent = raw.slice(1, -1); + /** @type {{ quote: '"', regex: RegExp }} */ + + const double = { + quote: '"', + regex: /"/g + }; + /** @type {{ quote: "'", regex: RegExp }} */ + + const single = { + quote: "'", + regex: /'/g + }; + const preferred = preferredQuote === "'" ? single : double; + const alternate = preferred === single ? double : single; + let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing + // the string, we might want to enclose with the alternate quote instead, to + // minimize the number of escaped quotes. + + if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) { + const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length; + const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length; + result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote; + } + + return result; + } + + function printString(raw, options, isDirectiveLiteral) { + // `rawContent` is the string exactly like it appeared in the input source + // code, without its enclosing quotes. + const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap + // the quotes on a DirectiveLiteral. + + const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'"); + /** @type {Quote} */ + + const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't + // change the escape sequences they use. + // See https://github.com/prettier/prettier/issues/1555 + // and https://tc39.github.io/ecma262/#directive-prologue + + if (isDirectiveLiteral) { + if (canChangeDirectiveQuotes) { + return enclosingQuote + rawContent + enclosingQuote; + } + + return raw; + } // It might sound unnecessary to use `makeString` even if the string already + // is enclosed with `enclosingQuote`, but it isn't. The string could contain + // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes + // sure that we consistently output the minimum amount of escaped quotes. + + + return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml)); + } + /** + * @param {string} rawContent + * @param {Quote} enclosingQuote + * @param {boolean=} unescapeUnnecessaryEscapes + * @returns {string} + */ + + + function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) { + const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double). + + const regex = /\\([\S\s])|(["'])/g; // Escape and unescape single and double quotes as needed to be able to + // enclose `rawContent` with `enclosingQuote`. + + const newContent = rawContent.replace(regex, (match, escaped, quote) => { + // If we matched an escape, and the escaped character is a quote of the + // other type than we intend to enclose the string with, there's no need for + // it to be escaped, so return it _without_ the backslash. + if (escaped === otherQuote) { + return escaped; + } // If we matched an unescaped quote and it is of the _same_ type as we + // intend to enclose the string with, it must be escaped, so return it with + // a backslash. + + + if (quote === enclosingQuote) { + return "\\" + quote; + } + + if (quote) { + return quote; + } // Unescape any unnecessarily escaped character. + // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27 + + + return unescapeUnnecessaryEscapes && /^[^\n\r"'0-7\\bfnrt-vx\u2028\u2029]$/.test(escaped) ? escaped : "\\" + escaped; + }); + return enclosingQuote + newContent + enclosingQuote; + } + + function printNumber(rawNumber) { + return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation. + .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0). + .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit. + .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes. + .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot. + .replace(/\.(?=e|$)/, ""); + } + /** + * @param {string} str + * @param {string} target + * @returns {number} + */ + + + function getMaxContinuousCount(str, target) { + const results = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g")); + + if (results === null) { + return 0; + } + + return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0); + } + + function getMinNotPresentContinuousCount(str, target) { + const matches = str.match(new RegExp("(".concat(escapeStringRegexp(target), ")+"), "g")); + + if (matches === null) { + return 0; + } + + const countPresent = new Map(); + let max = 0; + + for (const match of matches) { + const count = match.length / target.length; + countPresent.set(count, true); + + if (count > max) { + max = count; + } + } + + for (let i = 1; i < max; i++) { + if (!countPresent.get(i)) { + return i; + } + } + + return max + 1; + } + /** + * @param {string} text + * @returns {number} + */ + + + function getStringWidth(text) { + if (!text) { + return 0; + } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width` + + + if (!notAsciiRegex.test(text)) { + return text.length; + } + + return stringWidth_1(text); + } + + function hasIgnoreComment(path) { + const node = path.getValue(); + return hasNodeIgnoreComment(node); + } + + function hasNodeIgnoreComment(node) { + return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore); + } + + function isNodeIgnoreComment(comment) { + return comment.value.trim() === "prettier-ignore"; + } + + function addCommentHelper(node, comment) { + const comments = node.comments || (node.comments = []); + comments.push(comment); + comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment + // We already "print" it via the raw text, we don't need to re-print it as a + // comment + + /* istanbul ignore next */ + + if (node.type === "JSXText") { + comment.printed = true; + } + } + + function addLeadingComment(node, comment) { + comment.leading = true; + comment.trailing = false; + addCommentHelper(node, comment); + } + + function addDanglingComment(node, comment, marker) { + comment.leading = false; + comment.trailing = false; + + if (marker) { + comment.marker = marker; + } + + addCommentHelper(node, comment); + } + + function addTrailingComment(node, comment) { + comment.leading = false; + comment.trailing = true; + addCommentHelper(node, comment); + } // Not using + + /* istanbul ignore next */ + + + function isWithinParentArrayProperty(path, propertyName) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (parent == null) { + return false; + } + + if (!Array.isArray(parent[propertyName])) { + return false; + } + + const key = path.getName(); + return parent[propertyName][key] === node; + } + + function replaceEndOfLineWith(text, replacement) { + const parts = []; + + for (const part of text.split("\n")) { + if (parts.length !== 0) { + parts.push(replacement); + } + + parts.push(part); + } + + return parts; + } + + function getParserName(lang, options) { + const supportInfo = support.getSupportInfo({ + plugins: options.plugins + }); + const language = supportInfo.languages.find(language => language.name.toLowerCase() === lang || language.aliases && language.aliases.includes(lang) || language.extensions && language.extensions.some(ext => ext === ".".concat(lang))); + + if (language) { + return language.parsers[0]; + } + + return null; + } + + function isFrontMatterNode(node) { + return node && node.type === "front-matter"; + } + + function getShebang(text) { + if (!text.startsWith("#!")) { + return ""; + } + + const index = text.indexOf("\n"); + + if (index === -1) { + return text; + } + + return text.slice(0, index); + } + + var util = { + replaceEndOfLineWith, + getStringWidth, + getMaxContinuousCount, + getMinNotPresentContinuousCount, + getParserName, + getPenultimate, + getLast, + getNextNonSpaceNonCommentCharacterIndexWithStartIndex, + getNextNonSpaceNonCommentCharacterIndex, + getNextNonSpaceNonCommentCharacter, + skip, + skipWhitespace, + skipSpaces, + skipToLineEnd, + skipEverythingButNewLine, + skipInlineComment, + skipTrailingComment, + skipNewline, + isNextLineEmptyAfterIndex, + isNextLineEmpty, + isPreviousLineEmpty, + hasNewline, + hasNewlineInRange, + hasSpaces, + getAlignmentSize, + getIndentSize, + getPreferredQuote, + printString, + printNumber, + hasIgnoreComment, + hasNodeIgnoreComment, + isNodeIgnoreComment, + makeString, + addLeadingComment, + addDanglingComment, + addTrailingComment, + isWithinParentArrayProperty, + isFrontMatterNode, + getShebang + }; + + function guessEndOfLine(text) { + const index = text.indexOf("\r"); + + if (index >= 0) { + return text.charAt(index + 1) === "\n" ? "crlf" : "cr"; + } + + return "lf"; + } + + function convertEndOfLineToChars(value) { + switch (value) { + case "cr": + return "\r"; + + case "crlf": + return "\r\n"; + + default: + return "\n"; + } + } + + function countEndOfLineChars(text, eol) { + let regex; + /* istanbul ignore else */ + + if (eol === "\n") { + regex = /\n/g; + } else if (eol === "\r") { + regex = /\r/g; + } else if (eol === "\r\n") { + regex = /\r\n/g; + } else { + throw new Error("Unexpected \"eol\" ".concat(JSON.stringify(eol), ".")); + } + + const endOfLines = text.match(regex); + return endOfLines ? endOfLines.length : 0; + } + + function normalizeEndOfLine(text) { + return text.replace(/\r\n?/g, "\n"); + } + + var endOfLine = { + guessEndOfLine, + convertEndOfLineToChars, + countEndOfLineChars, + normalizeEndOfLine + }; + + const { + getStringWidth: getStringWidth$1 + } = util; + const { + convertEndOfLineToChars: convertEndOfLineToChars$1 + } = endOfLine; + const { + concat: concat$1, + fill: fill$1, + cursor: cursor$1 + } = docBuilders; + /** @type {Record} */ + + let groupModeMap; + const MODE_BREAK = 1; + const MODE_FLAT = 2; + + function rootIndent() { + return { + value: "", + length: 0, + queue: [] + }; + } + + function makeIndent(ind, options) { + return generateInd(ind, { + type: "indent" + }, options); + } + + function makeAlign(indent, n, options) { + if (n === -Infinity) { + return indent.root || rootIndent(); + } + + if (n < 0) { + return generateInd(indent, { + type: "dedent" + }, options); + } + + if (!n) { + return indent; + } + + if (n.type === "root") { + return Object.assign({}, indent, { + root: indent + }); + } + + const alignType = typeof n === "string" ? "stringAlign" : "numberAlign"; + return generateInd(indent, { + type: alignType, + n + }, options); + } + + function generateInd(ind, newPart, options) { + const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart); + let value = ""; + let length = 0; + let lastTabs = 0; + let lastSpaces = 0; + + for (const part of queue) { + switch (part.type) { + case "indent": + flush(); + + if (options.useTabs) { + addTabs(1); + } else { + addSpaces(options.tabWidth); + } + + break; + + case "stringAlign": + flush(); + value += part.n; + length += part.n.length; + break; + + case "numberAlign": + lastTabs += 1; + lastSpaces += part.n; + break; + + /* istanbul ignore next */ + + default: + throw new Error("Unexpected type '".concat(part.type, "'")); + } + } + + flushSpaces(); + return Object.assign({}, ind, { + value, + length, + queue + }); + + function addTabs(count) { + value += "\t".repeat(count); + length += options.tabWidth * count; + } + + function addSpaces(count) { + value += " ".repeat(count); + length += count; + } + + function flush() { + if (options.useTabs) { + flushTabs(); + } else { + flushSpaces(); + } + } + + function flushTabs() { + if (lastTabs > 0) { + addTabs(lastTabs); + } + + resetLast(); + } + + function flushSpaces() { + if (lastSpaces > 0) { + addSpaces(lastSpaces); + } + + resetLast(); + } + + function resetLast() { + lastTabs = 0; + lastSpaces = 0; + } + } + + function trim$1(out) { + if (out.length === 0) { + return 0; + } + + let trimCount = 0; // Trim whitespace at the end of line + + while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[\t ]*$/)) { + trimCount += out.pop().length; + } + + if (out.length && typeof out[out.length - 1] === "string") { + const trimmed = out[out.length - 1].replace(/[\t ]*$/, ""); + trimCount += out[out.length - 1].length - trimmed.length; + out[out.length - 1] = trimmed; + } + + return trimCount; + } + + function fits(next, restCommands, width, options, mustBeFlat) { + let restIdx = restCommands.length; + const cmds = [next]; // `out` is only used for width counting because `trim` requires to look + // backwards for space characters. + + const out = []; + + while (width >= 0) { + if (cmds.length === 0) { + if (restIdx === 0) { + return true; + } + + cmds.push(restCommands[restIdx - 1]); + restIdx--; + continue; + } + + const [ind, mode, doc] = cmds.pop(); + + if (typeof doc === "string") { + out.push(doc); + width -= getStringWidth$1(doc); + } else { + switch (doc.type) { + case "concat": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "indent": + cmds.push([makeIndent(ind, options), mode, doc.contents]); + break; + + case "align": + cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); + break; + + case "trim": + width += trim$1(out); + break; + + case "group": + if (mustBeFlat && doc.break) { + return false; + } + + cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]); + + if (doc.id) { + groupModeMap[doc.id] = cmds[cmds.length - 1][1]; + } + + break; + + case "fill": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "if-break": + { + const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; + + if (groupMode === MODE_BREAK) { + if (doc.breakContents) { + cmds.push([ind, mode, doc.breakContents]); + } + } + + if (groupMode === MODE_FLAT) { + if (doc.flatContents) { + cmds.push([ind, mode, doc.flatContents]); + } + } + + break; + } + + case "line": + switch (mode) { + // fallthrough + case MODE_FLAT: + if (!doc.hard) { + if (!doc.soft) { + out.push(" "); + width -= 1; + } + + break; + } + + return true; + + case MODE_BREAK: + return true; + } + + break; + } + } + } + + return false; + } + + function printDocToString(doc, options) { + groupModeMap = {}; + const width = options.printWidth; + const newLine = convertEndOfLineToChars$1(options.endOfLine); + let pos = 0; // cmds is basically a stack. We've turned a recursive call into a + // while loop which is much faster. The while loop below adds new + // cmds to the array instead of recursively calling `print`. + + const cmds = [[rootIndent(), MODE_BREAK, doc]]; + const out = []; + let shouldRemeasure = false; + let lineSuffix = []; + + while (cmds.length !== 0) { + const [ind, mode, doc] = cmds.pop(); + + if (typeof doc === "string") { + const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc; + out.push(formatted); + pos += getStringWidth$1(formatted); + } else { + switch (doc.type) { + case "cursor": + out.push(cursor$1.placeholder); + break; + + case "concat": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "indent": + cmds.push([makeIndent(ind, options), mode, doc.contents]); + break; + + case "align": + cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); + break; + + case "trim": + pos -= trim$1(out); + break; + + case "group": + switch (mode) { + case MODE_FLAT: + if (!shouldRemeasure) { + cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]); + break; + } + + // fallthrough + + case MODE_BREAK: + { + shouldRemeasure = false; + const next = [ind, MODE_FLAT, doc.contents]; + const rem = width - pos; + + if (!doc.break && fits(next, cmds, rem, options)) { + cmds.push(next); + } else { + // Expanded states are a rare case where a document + // can manually provide multiple representations of + // itself. It provides an array of documents + // going from the least expanded (most flattened) + // representation first to the most expanded. If a + // group has these, we need to manually go through + // these states and find the first one that fits. + if (doc.expandedStates) { + const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1]; + + if (doc.break) { + cmds.push([ind, MODE_BREAK, mostExpanded]); + break; + } else { + for (let i = 1; i < doc.expandedStates.length + 1; i++) { + if (i >= doc.expandedStates.length) { + cmds.push([ind, MODE_BREAK, mostExpanded]); + break; + } else { + const state = doc.expandedStates[i]; + const cmd = [ind, MODE_FLAT, state]; + + if (fits(cmd, cmds, rem, options)) { + cmds.push(cmd); + break; + } + } + } + } + } else { + cmds.push([ind, MODE_BREAK, doc.contents]); + } + } + + break; + } + } + + if (doc.id) { + groupModeMap[doc.id] = cmds[cmds.length - 1][1]; + } + + break; + // Fills each line with as much code as possible before moving to a new + // line with the same indentation. + // + // Expects doc.parts to be an array of alternating content and + // whitespace. The whitespace contains the linebreaks. + // + // For example: + // ["I", line, "love", line, "monkeys"] + // or + // [{ type: group, ... }, softline, { type: group, ... }] + // + // It uses this parts structure to handle three main layout cases: + // * The first two content items fit on the same line without + // breaking + // -> output the first content item and the whitespace "flat". + // * Only the first content item fits on the line without breaking + // -> output the first content item "flat" and the whitespace with + // "break". + // * Neither content item fits on the line without breaking + // -> output the first content item and the whitespace with "break". + + case "fill": + { + const rem = width - pos; + const { + parts + } = doc; + + if (parts.length === 0) { + break; + } + + const [content, whitespace] = parts; + const contentFlatCmd = [ind, MODE_FLAT, content]; + const contentBreakCmd = [ind, MODE_BREAK, content]; + const contentFits = fits(contentFlatCmd, [], rem, options, true); + + if (parts.length === 1) { + if (contentFits) { + cmds.push(contentFlatCmd); + } else { + cmds.push(contentBreakCmd); + } + + break; + } + + const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace]; + const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace]; + + if (parts.length === 2) { + if (contentFits) { + cmds.push(whitespaceFlatCmd); + cmds.push(contentFlatCmd); + } else { + cmds.push(whitespaceBreakCmd); + cmds.push(contentBreakCmd); + } + + break; + } // At this point we've handled the first pair (context, separator) + // and will create a new fill doc for the rest of the content. + // Ideally we wouldn't mutate the array here but copying all the + // elements to a new array would make this algorithm quadratic, + // which is unusable for large arrays (e.g. large texts in JSX). + + + parts.splice(0, 2); + const remainingCmd = [ind, mode, fill$1(parts)]; + const secondContent = parts[0]; + const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])]; + const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true); + + if (firstAndSecondContentFits) { + cmds.push(remainingCmd); + cmds.push(whitespaceFlatCmd); + cmds.push(contentFlatCmd); + } else if (contentFits) { + cmds.push(remainingCmd); + cmds.push(whitespaceBreakCmd); + cmds.push(contentFlatCmd); + } else { + cmds.push(remainingCmd); + cmds.push(whitespaceBreakCmd); + cmds.push(contentBreakCmd); + } + + break; + } + + case "if-break": + { + const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; + + if (groupMode === MODE_BREAK) { + if (doc.breakContents) { + cmds.push([ind, mode, doc.breakContents]); + } + } + + if (groupMode === MODE_FLAT) { + if (doc.flatContents) { + cmds.push([ind, mode, doc.flatContents]); + } + } + + break; + } + + case "line-suffix": + lineSuffix.push([ind, mode, doc.contents]); + break; + + case "line-suffix-boundary": + if (lineSuffix.length > 0) { + cmds.push([ind, mode, { + type: "line", + hard: true + }]); + } + + break; + + case "line": + switch (mode) { + case MODE_FLAT: + if (!doc.hard) { + if (!doc.soft) { + out.push(" "); + pos += 1; + } + + break; + } else { + // This line was forced into the output even if we + // were in flattened mode, so we need to tell the next + // group that no matter what, it needs to remeasure + // because the previous measurement didn't accurately + // capture the entire expression (this is necessary + // for nested groups) + shouldRemeasure = true; + } + + // fallthrough + + case MODE_BREAK: + if (lineSuffix.length) { + cmds.push([ind, mode, doc]); + cmds.push(...lineSuffix.reverse()); + lineSuffix = []; + break; + } + + if (doc.literal) { + if (ind.root) { + out.push(newLine, ind.root.value); + pos = ind.root.length; + } else { + out.push(newLine); + pos = 0; + } + } else { + pos -= trim$1(out); + out.push(newLine + ind.value); + pos = ind.length; + } + + break; + } + + break; + } + } + } + + const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder); + + if (cursorPlaceholderIndex !== -1) { + const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1); + const beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); + const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join(""); + const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join(""); + return { + formatted: beforeCursor + aroundCursor + afterCursor, + cursorNodeStart: beforeCursor.length, + cursorNodeText: aroundCursor + }; + } + + return { + formatted: out.join("") + }; + } + + var docPrinter = { + printDocToString + }; + + const { + literalline: literalline$1, + concat: concat$2 + } = docBuilders; // Using a unique object to compare by reference. + + const traverseDocOnExitStackMarker = {}; + + function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { + const docsStack = [doc]; + + while (docsStack.length !== 0) { + const doc = docsStack.pop(); + + if (doc === traverseDocOnExitStackMarker) { + onExit(docsStack.pop()); + continue; + } + + if (onExit) { + docsStack.push(doc, traverseDocOnExitStackMarker); + } + + if ( // Should Recurse + !onEnter || onEnter(doc) !== false) { + // When there are multiple parts to process, + // the parts need to be pushed onto the stack in reverse order, + // so that they are processed in the original order + // when the stack is popped. + if (doc.type === "concat" || doc.type === "fill") { + for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) { + docsStack.push(doc.parts[i]); + } + } else if (doc.type === "if-break") { + if (doc.flatContents) { + docsStack.push(doc.flatContents); + } + + if (doc.breakContents) { + docsStack.push(doc.breakContents); + } + } else if (doc.type === "group" && doc.expandedStates) { + if (shouldTraverseConditionalGroups) { + for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) { + docsStack.push(doc.expandedStates[i]); + } + } else { + docsStack.push(doc.contents); + } + } else if (doc.contents) { + docsStack.push(doc.contents); + } + } + } + } + + function mapDoc(doc, cb) { + if (doc.type === "concat" || doc.type === "fill") { + const parts = doc.parts.map(part => mapDoc(part, cb)); + return cb(Object.assign({}, doc, { + parts + })); + } else if (doc.type === "if-break") { + const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb); + const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb); + return cb(Object.assign({}, doc, { + breakContents, + flatContents + })); + } else if (doc.contents) { + const contents = mapDoc(doc.contents, cb); + return cb(Object.assign({}, doc, { + contents + })); + } + + return cb(doc); + } + + function findInDoc(doc, fn, defaultValue) { + let result = defaultValue; + let hasStopped = false; + + function findInDocOnEnterFn(doc) { + const maybeResult = fn(doc); + + if (maybeResult !== undefined) { + hasStopped = true; + result = maybeResult; + } + + if (hasStopped) { + return false; + } + } + + traverseDoc(doc, findInDocOnEnterFn); + return result; + } + + function isEmpty(n) { + return typeof n === "string" && n.length === 0; + } + + function isLineNextFn(doc) { + if (typeof doc === "string") { + return false; + } + + if (doc.type === "line") { + return true; + } + } + + function isLineNext(doc) { + return findInDoc(doc, isLineNextFn, false); + } + + function willBreakFn(doc) { + if (doc.type === "group" && doc.break) { + return true; + } + + if (doc.type === "line" && doc.hard) { + return true; + } + + if (doc.type === "break-parent") { + return true; + } + } + + function willBreak(doc) { + return findInDoc(doc, willBreakFn, false); + } + + function breakParentGroup(groupStack) { + if (groupStack.length > 0) { + const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because + // the user is expected to manually handle what breaks. + + if (!parentGroup.expandedStates) { + parentGroup.break = true; + } + } + + return null; + } + + function propagateBreaks(doc) { + const alreadyVisitedSet = new Set(); + const groupStack = []; + + function propagateBreaksOnEnterFn(doc) { + if (doc.type === "break-parent") { + breakParentGroup(groupStack); + } + + if (doc.type === "group") { + groupStack.push(doc); + + if (alreadyVisitedSet.has(doc)) { + return false; + } + + alreadyVisitedSet.add(doc); + } + } + + function propagateBreaksOnExitFn(doc) { + if (doc.type === "group") { + const group = groupStack.pop(); + + if (group.break) { + breakParentGroup(groupStack); + } + } + } + + traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, + /* shouldTraverseConditionalGroups */ + true); + } + + function removeLinesFn(doc) { + // Force this doc into flat mode by statically converting all + // lines into spaces (or soft lines into nothing). Hard lines + // should still output because there's too great of a chance + // of breaking existing assumptions otherwise. + if (doc.type === "line" && !doc.hard) { + return doc.soft ? "" : " "; + } else if (doc.type === "if-break") { + return doc.flatContents || ""; + } + + return doc; + } + + function removeLines(doc) { + return mapDoc(doc, removeLinesFn); + } + + function getInnerParts(doc) { + let { + parts + } = doc; + let lastPart; // Avoid a falsy element like "" + + for (let i = doc.parts.length; i > 0 && !lastPart; i--) { + lastPart = parts[i - 1]; + } + + if (lastPart.type === "group") { + parts = lastPart.contents.parts; + } + + return parts; + } + + function stripTrailingHardline(doc, withInnerParts = false) { + // HACK remove ending hardline, original PR: #1984 + if (doc.type === "concat" && doc.parts.length !== 0) { + const parts = withInnerParts ? getInnerParts(doc) : doc.parts; + const lastPart = parts[parts.length - 1]; + + if (lastPart.type === "concat") { + if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") { + return { + type: "concat", + parts: parts.slice(0, -1) + }; + } + + return { + type: "concat", + parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart)) + }; + } + } + + return doc; + } + + function normalizeParts(parts) { + const newParts = []; + const restParts = parts.filter(Boolean); + + while (restParts.length !== 0) { + const part = restParts.shift(); + + if (!part) { + continue; + } + + if (part.type === "concat") { + restParts.unshift(...part.parts); + continue; + } + + if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") { + newParts[newParts.length - 1] += part; + continue; + } + + newParts.push(part); + } + + return newParts; + } + + function normalizeDoc(doc) { + return mapDoc(doc, currentDoc => { + if (!currentDoc.parts) { + return currentDoc; + } + + return Object.assign({}, currentDoc, { + parts: normalizeParts(currentDoc.parts) + }); + }); + } + + function replaceNewlinesWithLiterallines(doc) { + return mapDoc(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$2(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$1)) : currentDoc); + } + + var docUtils = { + isEmpty, + willBreak, + isLineNext, + traverseDoc, + findInDoc, + mapDoc, + propagateBreaks, + removeLines, + stripTrailingHardline, + normalizeParts, + normalizeDoc, + replaceNewlinesWithLiterallines + }; + + function flattenDoc(doc) { + if (doc.type === "concat") { + const res = []; + + for (let i = 0; i < doc.parts.length; ++i) { + const doc2 = doc.parts[i]; + + if (typeof doc2 !== "string" && doc2.type === "concat") { + res.push(...flattenDoc(doc2).parts); + } else { + const flattened = flattenDoc(doc2); + + if (flattened !== "") { + res.push(flattened); + } + } + } + + return Object.assign({}, doc, { + parts: res + }); + } else if (doc.type === "if-break") { + return Object.assign({}, doc, { + breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null, + flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null + }); + } else if (doc.type === "group") { + return Object.assign({}, doc, { + contents: flattenDoc(doc.contents), + expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates + }); + } else if (doc.contents) { + return Object.assign({}, doc, { + contents: flattenDoc(doc.contents) + }); + } + + return doc; + } + + function printDoc(doc) { + if (typeof doc === "string") { + return JSON.stringify(doc); + } + + if (doc.type === "line") { + if (doc.literal) { + return "literalline"; + } + + if (doc.hard) { + return "hardline"; + } + + if (doc.soft) { + return "softline"; + } + + return "line"; + } + + if (doc.type === "break-parent") { + return "breakParent"; + } + + if (doc.type === "trim") { + return "trim"; + } + + if (doc.type === "concat") { + return "[" + doc.parts.map(printDoc).join(", ") + "]"; + } + + if (doc.type === "indent") { + return "indent(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "align") { + return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")"; + } + + if (doc.type === "if-break") { + return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")"; + } + + if (doc.type === "group") { + if (doc.expandedStates) { + return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])"; + } + + return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "fill") { + return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")"; + } + + if (doc.type === "line-suffix") { + return "lineSuffix(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "line-suffix-boundary") { + return "lineSuffixBoundary"; + } + + throw new Error("Unknown doc type " + doc.type); + } + + var docDebug = { + printDocToDebug(doc) { + return printDoc(flattenDoc(doc)); + } + + }; + + /** + * @typedef {import("./doc-builders").Doc} Doc + */ + + + var document = { + builders: docBuilders, + printer: docPrinter, + utils: docUtils, + debug: docDebug + }; + + return document; + +}))); diff --git a/node_modules/prettier/index.js b/node_modules/prettier/index.js new file mode 100644 index 0000000..4736dea --- /dev/null +++ b/node_modules/prettier/index.js @@ -0,0 +1,54762 @@ +'use strict'; + +var fs$3 = require('fs'); +var path$2 = require('path'); +var os$1 = require('os'); +var tty$1 = require('tty'); +var assert$1 = require('assert'); +var util$4 = require('util'); +var stream$6 = require('stream'); +var events$1 = require('events'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var fs__default = /*#__PURE__*/_interopDefaultLegacy(fs$3); +var path__default = /*#__PURE__*/_interopDefaultLegacy(path$2); +var os__default = /*#__PURE__*/_interopDefaultLegacy(os$1); +var tty__default = /*#__PURE__*/_interopDefaultLegacy(tty$1); +var assert__default = /*#__PURE__*/_interopDefaultLegacy(assert$1); +var util__default = /*#__PURE__*/_interopDefaultLegacy(util$4); +var stream__default = /*#__PURE__*/_interopDefaultLegacy(stream$6); +var events__default = /*#__PURE__*/_interopDefaultLegacy(events$1); + +var name = "prettier"; +var version = "2.1.2"; +var description = "Prettier is an opinionated code formatter"; +var bin = "./bin/prettier.js"; +var repository = "prettier/prettier"; +var homepage = "https://prettier.io"; +var author = "James Long"; +var license = "MIT"; +var main = "./index.js"; +var browser = "./standalone.js"; +var unpkg = "./standalone.js"; +var engines = { + node: ">=10.13.0" +}; +var files = [ + "index.js", + "standalone.js", + "src", + "bin" +]; +var dependencies = { + "@angular/compiler": "10.0.12", + "@babel/code-frame": "7.10.4", + "@babel/parser": "7.11.2", + "@glimmer/syntax": "0.59.0", + "@iarna/toml": "2.2.5", + "@typescript-eslint/typescript-estree": "3.10.0", + "angular-estree-parser": "2.2.0", + "angular-html-parser": "1.7.1", + camelcase: "6.0.0", + chalk: "4.1.0", + "ci-info": "watson/ci-info#f43f6a1cefff47fb361c88cf4b943fdbcaafe540", + "cjk-regex": "2.0.0", + cosmiconfig: "7.0.0", + dashify: "2.0.0", + diff: "4.0.2", + editorconfig: "0.15.3", + "editorconfig-to-prettier": "0.1.1", + "escape-string-regexp": "4.0.0", + esutils: "2.0.3", + "fast-glob": "3.2.4", + "fast-json-stable-stringify": "2.1.0", + "find-parent-dir": "0.3.0", + "flow-parser": "0.132.0", + "get-stream": "6.0.0", + globby: "11.0.1", + graphql: "15.3.0", + "html-element-attributes": "2.2.1", + "html-styles": "1.0.0", + "html-tag-names": "1.1.5", + "html-void-elements": "1.0.5", + ignore: "4.0.6", + "jest-docblock": "26.0.0", + json5: "2.1.3", + leven: "3.1.0", + "lines-and-columns": "1.1.6", + "linguist-languages": "7.10.0", + lodash: "4.17.20", + mem: "6.1.0", + minimatch: "3.0.4", + minimist: "1.2.5", + "n-readlines": "1.0.0", + outdent: "0.7.1", + "parse-srcset": "ikatyang/parse-srcset#54eb9c1cb21db5c62b4d0e275d7249516df6f0ee", + "please-upgrade-node": "3.2.0", + "postcss-less": "3.1.4", + "postcss-media-query-parser": "0.2.3", + "postcss-scss": "2.1.1", + "postcss-selector-parser": "2.2.3", + "postcss-values-parser": "2.0.1", + "regexp-util": "1.2.2", + "remark-footnotes": "2.0.0", + "remark-math": "1.0.6", + "remark-parse": "8.0.3", + resolve: "1.17.0", + semver: "7.3.2", + "string-width": "4.2.0", + typescript: "4.0.2", + "unicode-regex": "3.0.0", + unified: "9.2.0", + vnopts: "1.0.2", + "yaml-unist-parser": "1.3.1" +}; +var devDependencies = { + "@babel/core": "7.11.4", + "@babel/preset-env": "7.11.0", + "@babel/types": "7.11.0", + "@glimmer/reference": "0.59.0", + "@rollup/plugin-alias": "3.1.1", + "@rollup/plugin-babel": "5.2.0", + "@rollup/plugin-commonjs": "14.0.0", + "@rollup/plugin-json": "4.1.0", + "@rollup/plugin-node-resolve": "9.0.0", + "@rollup/plugin-replace": "2.3.3", + "@types/estree": "0.0.45", + "@types/node": "14.6.0", + "@typescript-eslint/types": "3.10.0", + "babel-loader": "8.1.0", + benchmark: "2.1.4", + "builtin-modules": "3.1.0", + "cross-env": "7.0.2", + cspell: "4.1.0", + eslint: "7.7.0", + "eslint-config-prettier": "6.11.0", + "eslint-formatter-friendly": "7.0.0", + "eslint-plugin-import": "2.22.0", + "eslint-plugin-jest": "23.20.0", + "eslint-plugin-prettier-internal-rules": "file:scripts/tools/eslint-plugin-prettier-internal-rules", + "eslint-plugin-react": "7.20.6", + "eslint-plugin-unicorn": "21.0.0", + execa: "4.0.3", + jest: "26.4.2", + "jest-snapshot-serializer-ansi": "1.0.0", + "jest-snapshot-serializer-raw": "1.1.0", + "jest-watch-typeahead": "0.6.0", + "npm-run-all": "4.1.5", + prettier: "2.1.1", + rimraf: "3.0.2", + rollup: "2.26.5", + "rollup-plugin-node-globals": "1.4.0", + "rollup-plugin-terser": "7.0.0", + shelljs: "0.8.4", + "snapshot-diff": "0.8.1", + "strip-ansi": "6.0.0", + "synchronous-promise": "2.0.13", + tempy: "0.6.0", + "terser-webpack-plugin": "4.1.0", + webpack: "4.44.1" +}; +var scripts = { + prepublishOnly: "echo \"Error: must publish from dist/\" && exit 1", + "prepare-release": "yarn && yarn build && yarn test:dist", + test: "jest", + "test:dev-package": "cross-env INSTALL_PACKAGE=1 jest", + "test:dist": "cross-env NODE_ENV=production jest", + "test:dist-standalone": "cross-env NODE_ENV=production TEST_STANDALONE=1 jest", + "test:integration": "jest tests_integration", + "perf:repeat": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf:repeat-inspect": "yarn && yarn build && cross-env NODE_ENV=production node --inspect-brk ./dist/bin-prettier.js --debug-repeat ${PERF_REPEAT:-1000} --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + "perf:benchmark": "yarn && yarn build && cross-env NODE_ENV=production node ./dist/bin-prettier.js --debug-benchmark --loglevel debug ${PERF_FILE:-./index.js} > /dev/null", + lint: "run-p lint:*", + "lint:typecheck": "tsc", + "lint:eslint": "cross-env EFF_NO_LINK_RULES=true eslint . --format friendly", + "lint:changelog": "node ./scripts/lint-changelog.js", + "lint:prettier": "prettier . \"!test*\" --check", + "lint:dist": "eslint --no-eslintrc --no-ignore --env=es6,browser --parser-options=ecmaVersion:2016 \"dist/!(bin-prettier|index|third-party).js\"", + "lint:spellcheck": "cspell \"**/*\" \".github/**/*\"", + "lint:deps": "node ./scripts/check-deps.js", + fix: "run-s fix:eslint fix:prettier", + "fix:eslint": "yarn lint:eslint --fix", + "fix:prettier": "yarn lint:prettier --write", + build: "node ./scripts/build/build.js", + "build-docs": "node ./scripts/build-docs.js" +}; +var _package = { + name: name, + version: version, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + browser: browser, + unpkg: unpkg, + engines: engines, + files: files, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts +}; + +var _package$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name, + version: version, + description: description, + bin: bin, + repository: repository, + homepage: homepage, + author: author, + license: license, + main: main, + browser: browser, + unpkg: unpkg, + engines: engines, + files: files, + dependencies: dependencies, + devDependencies: devDependencies, + scripts: scripts, + 'default': _package +}); + +function Diff() {} + +Diff.prototype = { + diff: function diff(oldString, newString) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = void 0; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + castInput: function castInput(value) { + return value; + }, + tokenize: function tokenize(value) { + return value.split(''); + }, + join: function join(chars) { + return chars.join(''); + } +}; + +function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; +} + +function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; +} + +var characterDiff = new Diff(); + +function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); +} + +function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; +} // +// Ranges and exceptions: +// Latin-1 Supplement, 0080–00FF +// - U+00D7 × Multiplication sign +// - U+00F7 ÷ Division sign +// Latin Extended-A, 0100–017F +// Latin Extended-B, 0180–024F +// IPA Extensions, 0250–02AF +// Spacing Modifier Letters, 02B0–02FF +// - U+02C7 ˇ ˇ Caron +// - U+02D8 ˘ ˘ Breve +// - U+02D9 ˙ ˙ Dot Above +// - U+02DA ˚ ˚ Ring Above +// - U+02DB ˛ ˛ Ogonek +// - U+02DC ˜ ˜ Small Tilde +// - U+02DD ˝ ˝ Double Acute Accent +// Latin Extended Additional, 1E00–1EFF + + +var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; +var reWhitespace = /\S/; +var wordDiff = new Diff(); + +wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); +}; + +wordDiff.tokenize = function (value) { + var tokens = value.split(/(\s+|[()[\]{}'"]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; +}; + +function diffWords(oldStr, newStr, options) { + options = generateOptions(options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); +} + +function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); +} + +var lineDiff = new Diff(); + +lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; +}; + +function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); +} + +function diffTrimmedLines(oldStr, newStr, callback) { + var options = generateOptions(callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); +} + +var sentenceDiff = new Diff(); + +sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); +}; + +function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); +} + +var cssDiff = new Diff(); + +cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); +}; + +function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); +} + +function _typeof(obj) { + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } +} + +function _iterableToArray(iter) { + if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); +} + +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance"); +} + +var objectPrototypeToString = Object.prototype.toString; +var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a +// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + +jsonDiff.useLongestToken = true; +jsonDiff.tokenize = lineDiff.tokenize; + +jsonDiff.castInput = function (value) { + var _this$options = this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { + return typeof v === 'undefined' ? undefinedReplacement : v; + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); +}; + +jsonDiff.equals = function (left, right) { + return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); +}; + +function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); +} // This function handles the presence of circular references by bailing out when encountering an +// object that is already on the "stack" of items being processed. Accepts an optional replacer + + +function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if (_typeof(obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; +} + +var arrayDiff = new Diff(); + +arrayDiff.tokenize = function (value) { + return value.slice(); +}; + +arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; +}; + +function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); +} + +function parsePatch(uniDiff) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: +chunkHeader[2] || 1, + newStart: +chunkHeader[3], + newLines: +chunkHeader[4] || 1, + lines: [], + linedelimiters: [] + }; + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; +} // Iterator that traverses in the range of [min, max], stepping +// by distance from a given start position. I.e. for [0, 4], with +// start of 2, this will iterate 2, 3, 1, 4, 0. + + +function distanceIterator(start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; +} + +function applyPatch(source, uniDiff) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { + return line === patchContent; + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = distanceIterator(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + if (_toPos < 0) { + // Creating a new file + _toPos = 0; + } + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); +} // Wrapper that supports multiple file patches via callbacks. + + +function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = parsePatch(uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); +} + +function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = diffLines(oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + var _loop = function _loop(i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + var _curRange; // If we have previous context, start with that + + + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + var _curRange2; // Overlapping + + + (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); + } else { + var _curRange3; // end the range and output + + + var contextSize = Math.min(lines.length, options.context); + + (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + _loop(i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; +} + +function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + var diff = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; +} + +function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); +} + +function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); +} + +function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; +} + +function calcLineCount(hunk) { + var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } +} + +function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; +} + +function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return parsePatch(param)[0]; + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return structuredPatch(undefined, undefined, base, param); + } + + return param; +} + +function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; +} + +function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } +} + +function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; +} + +function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; +} + +function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + var _hunk$lines; // Mine inserted + + + (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + var _hunk$lines2; // Theirs inserted + + + (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); +} + +function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + var _hunk$lines3; + + (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); + + return; + } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + var _hunk$lines4; + + (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); + + return; + } + } else if (arrayEqual(myChanges, theirChanges)) { + var _hunk$lines5; + + (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); +} + +function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + var _hunk$lines6; + + (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } +} + +function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); +} + +function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } +} + +function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } +} + +function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; +} + +function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; +} + +function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); +} + +function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; +} + +function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; +} // See: http://code.google.com/p/google-diff-match-patch/wiki/API + + +function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; +} + +function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); +} + +function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; +} + +var index_es6 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Diff: Diff, + diffChars: diffChars, + diffWords: diffWords, + diffWordsWithSpace: diffWordsWithSpace, + diffLines: diffLines, + diffTrimmedLines: diffTrimmedLines, + diffSentences: diffSentences, + diffCss: diffCss, + diffJson: diffJson, + diffArrays: diffArrays, + structuredPatch: structuredPatch, + createTwoFilesPatch: createTwoFilesPatch, + createPatch: createPatch, + applyPatch: applyPatch, + applyPatches: applyPatches, + parsePatch: parsePatch, + merge: merge, + convertChangesToDMP: convertChangesToDMP, + convertChangesToXML: convertChangesToXML, + canonicalize: canonicalize +}); + +/** + * @param {Doc[]} parts + * @returns Doc + */ + + +function concat(parts) { + // access the internals of a document directly. + // if(parts.length === 1) { + // // If it's a single document, no need to concat it. + // return parts[0]; + // } + + + return { + type: "concat", + parts + }; +} +/** + * @param {Doc} contents + * @returns Doc + */ + + +function indent(contents) { + + return { + type: "indent", + contents + }; +} +/** + * @param {number | string} n + * @param {Doc} contents + * @returns Doc + */ + + +function align(n, contents) { + + return { + type: "align", + contents, + n + }; +} +/** + * @param {Doc} contents + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + +function group(contents, opts) { + opts = opts || {}; + + return { + type: "group", + id: opts.id, + contents, + break: !!opts.shouldBreak, + expandedStates: opts.expandedStates + }; +} +/** + * @param {Doc} contents + * @returns Doc + */ + + +function dedentToRoot(contents) { + return align(-Infinity, contents); +} +/** + * @param {Doc} contents + * @returns Doc + */ + + +function markAsRoot(contents) { + // @ts-ignore - TBD ???: + return align({ + type: "root" + }, contents); +} +/** + * @param {Doc} contents + * @returns Doc + */ + + +function dedent(contents) { + return align(-1, contents); +} +/** + * @param {Doc[]} states + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + +function conditionalGroup(states, opts) { + return group(states[0], Object.assign({}, opts, { + expandedStates: states + })); +} +/** + * @param {Doc[]} parts + * @returns Doc + */ + + +function fill(parts) { + + return { + type: "fill", + parts + }; +} +/** + * @param {Doc} [breakContents] + * @param {Doc} [flatContents] + * @param {object} [opts] - TBD ??? + * @returns Doc + */ + + +function ifBreak(breakContents, flatContents, opts) { + opts = opts || {}; + + return { + type: "if-break", + breakContents, + flatContents, + groupId: opts.groupId + }; +} +/** + * @param {Doc} contents + * @returns Doc + */ + + +function lineSuffix(contents) { + + return { + type: "line-suffix", + contents + }; +} + +const lineSuffixBoundary = { + type: "line-suffix-boundary" +}; +const breakParent = { + type: "break-parent" +}; +const trim = { + type: "trim" +}; +const line = { + type: "line" +}; +const softline = { + type: "line", + soft: true +}; +const hardline = concat([{ + type: "line", + hard: true +}, breakParent]); +const literalline = concat([{ + type: "line", + hard: true, + literal: true +}, breakParent]); +const cursor = { + type: "cursor", + placeholder: Symbol("cursor") +}; +/** + * @param {Doc} sep + * @param {Doc[]} arr + * @returns Doc + */ + +function join(sep, arr) { + const res = []; + + for (let i = 0; i < arr.length; i++) { + if (i !== 0) { + res.push(sep); + } + + res.push(arr[i]); + } + + return concat(res); +} +/** + * @param {Doc} doc + * @param {number} size + * @param {number} tabWidth + */ + + +function addAlignmentToDoc(doc, size, tabWidth) { + let aligned = doc; + + if (size > 0) { + // Use indent to add tabs for all the levels of tabs we need + for (let i = 0; i < Math.floor(size / tabWidth); ++i) { + aligned = indent(aligned); + } // Use align for all the spaces that are needed + + + aligned = align(size % tabWidth, aligned); // size is absolute from 0 and not relative to the current + // indentation, so we use -Infinity to reset the indentation to 0 + + aligned = align(-Infinity, aligned); + } + + return aligned; +} + +var docBuilders = { + concat, + join, + line, + softline, + hardline, + literalline, + group, + conditionalGroup, + fill, + lineSuffix, + lineSuffixBoundary, + cursor, + breakParent, + ifBreak, + trim, + indent, + align, + addAlignmentToDoc, + markAsRoot, + dedentToRoot, + dedent +}; + +var ansiRegex = ({ + onlyFirst = false +} = {}) => { + const pattern = ['[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[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'); +}; + +var stripAnsi = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; + +/* eslint-disable yoda */ + +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; +}; + +var isFullwidthCodePoint_1 = isFullwidthCodePoint; +var _default = isFullwidthCodePoint; +isFullwidthCodePoint_1.default = _default; + +var emojiRegex = 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\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\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; +}; + +const stringWidth = string => { + string = string.replace(emojiRegex(), ' '); + + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + 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_1(code) ? 2 : 1; + } + + return width; +}; + +var stringWidth_1 = stringWidth; // TODO: remove this in the next major version + +var _default$1 = stringWidth; +stringWidth_1.default = _default$1; + +var escapeStringRegexp = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + + + return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); +}; + +var getLast = arr => arr[arr.length - 1]; + +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} + +const debug = typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args) => console.error('SEMVER', ...args) : () => {}; +var debug_1 = debug; + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0'; +const MAX_LENGTH = 256; +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ +9007199254740991; // Max safe segment length for coercion. + +const MAX_SAFE_COMPONENT_LENGTH = 16; +var constants = { + SEMVER_SPEC_VERSION, + MAX_LENGTH, + MAX_SAFE_INTEGER, + MAX_SAFE_COMPONENT_LENGTH +}; + +function createCommonjsModule(fn, basedir, module) { + return module = { + path: basedir, + exports: {}, + require: function (path, base) { + return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); + } + }, fn(module, module.exports), module.exports; +} + +function getCjsExportFromNamespace (n) { + return n && n['default'] || n; +} + +function commonjsRequire () { + throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); +} + +var re_1 = createCommonjsModule(function (module, exports) { + const { + MAX_SAFE_COMPONENT_LENGTH + } = constants; + exports = module.exports = {}; // The actual regexps go on exports.re + + const re = exports.re = []; + const src = exports.src = []; + const t = exports.t = {}; + let R = 0; + + const createToken = (name, value, isGlobal) => { + const index = R++; + debug_1(index, value); + t[name] = index; + src[index] = value; + re[index] = new RegExp(value, isGlobal ? 'g' : undefined); + }; // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + + createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*'); + createToken('NUMERICIDENTIFIERLOOSE', '[0-9]+'); // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + createToken('NONNUMERICIDENTIFIER', '\\d*[a-zA-Z-][a-zA-Z0-9-]*'); // ## Main Version + // Three dot-separated numeric identifiers. + + createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})\\.` + `(${src[t.NUMERICIDENTIFIER]})`); + createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + `(${src[t.NUMERICIDENTIFIERLOOSE]})`); // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NUMERICIDENTIFIER]}|${src[t.NONNUMERICIDENTIFIER]})`); + createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NUMERICIDENTIFIERLOOSE]}|${src[t.NONNUMERICIDENTIFIER]})`); // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`); + createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`); // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + createToken('BUILDIDENTIFIER', '[0-9A-Za-z-]+'); // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]}(?:\\.${src[t.BUILDIDENTIFIER]})*))`); // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + createToken('FULLPLAIN', `v?${src[t.MAINVERSION]}${src[t.PRERELEASE]}?${src[t.BUILD]}?`); + createToken('FULL', `^${src[t.FULLPLAIN]}$`); // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + + createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]}${src[t.PRERELEASELOOSE]}?${src[t.BUILD]}?`); + createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`); + createToken('GTLT', '((?:<|>)?=?)'); // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + + createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`); + createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`); + createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + `(?:${src[t.PRERELEASE]})?${src[t.BUILD]}?` + `)?)?`); + createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + `(?:${src[t.PRERELEASELOOSE]})?${src[t.BUILD]}?` + `)?)?`); + createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`); + createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`); // Coercion. + // Extract anything that could conceivably be a part of a valid semver + + createToken('COERCE', `${'(^|[^\\d])' + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + `(?:$|[^\\d])`); + createToken('COERCERTL', src[t.COERCE], true); // Tilde ranges. + // Meaning is "reasonably at or greater than" + + createToken('LONETILDE', '(?:~>?)'); + createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true); + exports.tildeTrimReplace = '$1~'; + createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`); + createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`); // Caret ranges. + // Meaning is "at least and backwards compatible with" + + createToken('LONECARET', '(?:\\^)'); + createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true); + exports.caretTrimReplace = '$1^'; + createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`); + createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`); // A simple gt/lt/eq thing, or just "" to indicate "any version" + + createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`); + createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`); // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + + createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true); + exports.comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + + createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAIN]})` + `\\s*$`); + createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + `\\s+-\\s+` + `(${src[t.XRANGEPLAINLOOSE]})` + `\\s*$`); // Star ranges basically just allow anything at all. + + createToken('STAR', '(<|>)?=?\\s*\\*'); // >=0.0.0 is like a star + + createToken('GTE0', '^\\s*>=\\s*0\.0\.0\\s*$'); + createToken('GTE0PRE', '^\\s*>=\\s*0\.0\.0-0\\s*$'); +}); + +const numeric = /^[0-9]+$/; + +const compareIdentifiers = (a, b) => { + const anum = numeric.test(a); + const bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; +}; + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a); + +var identifiers = { + compareIdentifiers, + rcompareIdentifiers +}; + +const { + MAX_LENGTH: MAX_LENGTH$1, + MAX_SAFE_INTEGER: MAX_SAFE_INTEGER$1 +} = constants; +const { + re, + t +} = re_1; +const { + compareIdentifiers: compareIdentifiers$1 +} = identifiers; + +class SemVer { + constructor(version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && version.includePrerelease === !!options.includePrerelease) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid Version: ${version}`); + } + + if (version.length > MAX_LENGTH$1) { + throw new TypeError(`version is longer than ${MAX_LENGTH$1} characters`); + } + + debug_1('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + + this.includePrerelease = !!options.includePrerelease; + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]); + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`); + } + + this.raw = version; // these are actually numbers + + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER$1 || this.major < 0) { + throw new TypeError('Invalid major version'); + } + + if (this.minor > MAX_SAFE_INTEGER$1 || this.minor < 0) { + throw new TypeError('Invalid minor version'); + } + + if (this.patch > MAX_SAFE_INTEGER$1 || this.patch < 0) { + throw new TypeError('Invalid patch version'); + } // numberify any prerelease numeric ids + + + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map(id => { + if (/^[0-9]+$/.test(id)) { + const num = +id; + + if (num >= 0 && num < MAX_SAFE_INTEGER$1) { + return num; + } + } + + return id; + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + format() { + this.version = `${this.major}.${this.minor}.${this.patch}`; + + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}`; + } + + return this.version; + } + + toString() { + return this.version; + } + + compare(other) { + debug_1('SemVer.compare', this.version, this.options, other); + + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0; + } + + other = new SemVer(other, this.options); + } + + if (other.version === this.version) { + return 0; + } + + return this.compareMain(other) || this.comparePre(other); + } + + compareMain(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + return compareIdentifiers$1(this.major, other.major) || compareIdentifiers$1(this.minor, other.minor) || compareIdentifiers$1(this.patch, other.patch); + } + + comparePre(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } // NOT having a prerelease is > having one + + + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + + let i = 0; + + do { + const a = this.prerelease[i]; + const b = other.prerelease[i]; + debug_1('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers$1(a, b); + } + } while (++i); + } + + compareBuild(other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + let i = 0; + + do { + const a = this.build[i]; + const b = other.build[i]; + debug_1('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers$1(a, b); + } + } while (++i); + } // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + + + inc(release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + + this.patch = 0; + this.prerelease = []; + break; + + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + let i = this.prerelease.length; + + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + + break; + + default: + throw new Error(`invalid increment argument: ${release}`); + } + + this.format(); + this.raw = this.version; + return this; + } + +} + +var semver = SemVer; + +const compare = (a, b, loose) => new semver(a, loose).compare(new semver(b, loose)); + +var compare_1 = compare; + +const lt = (a, b, loose) => compare_1(a, b, loose) < 0; + +var lt_1 = lt; + +const gte = (a, b, loose) => compare_1(a, b, loose) >= 0; + +var gte_1 = gte; + +var arrayify = (object, keyName) => Object.entries(object).map(([key, value]) => Object.assign({ + [keyName]: key +}, value)); + +var lib = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); // In the absence of a WeakSet or WeakMap implementation, don't break, but don't cache either. + + function noop() { + var args = []; + + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + } + + function createWeakMap() { + if (typeof WeakMap !== 'undefined') { + return new WeakMap(); + } else { + return fakeSetOrMap(); + } + } + /** + * Creates and returns a no-op implementation of a WeakMap / WeakSet that never stores anything. + */ + + + function fakeSetOrMap() { + return { + add: noop, + delete: noop, + get: noop, + set: noop, + has: function (k) { + return false; + } + }; + } // Safe hasOwnProperty + + + var hop = Object.prototype.hasOwnProperty; + + var has = function (obj, prop) { + return hop.call(obj, prop); + }; // Copy all own enumerable properties from source to target + + + function extend(target, source) { + for (var prop in source) { + if (has(source, prop)) { + target[prop] = source[prop]; + } + } + + return target; + } + + var reLeadingNewline = /^[ \t]*(?:\r\n|\r|\n)/; + var reTrailingNewline = /(?:\r\n|\r|\n)[ \t]*$/; + var reStartsWithNewlineOrIsEmpty = /^(?:[\r\n]|$)/; + var reDetectIndentation = /(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/; + var reOnlyWhitespaceWithAtLeastOneNewline = /^[ \t]*[\r\n][ \t\r\n]*$/; + + function _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options) { + // If first interpolated value is a reference to outdent, + // determine indentation level from the indentation of the interpolated value. + var indentationLevel = 0; + var match = strings[0].match(reDetectIndentation); + + if (match) { + indentationLevel = match[1].length; + } + + var reSource = "(\\r\\n|\\r|\\n).{0," + indentationLevel + "}"; + var reMatchIndent = new RegExp(reSource, 'g'); + + if (firstInterpolatedValueSetsIndentationLevel) { + strings = strings.slice(1); + } + + var newline = options.newline, + trimLeadingNewline = options.trimLeadingNewline, + trimTrailingNewline = options.trimTrailingNewline; + var normalizeNewlines = typeof newline === 'string'; + var l = strings.length; + var outdentedStrings = strings.map(function (v, i) { + // Remove leading indentation from all lines + v = v.replace(reMatchIndent, '$1'); // Trim a leading newline from the first string + + if (i === 0 && trimLeadingNewline) { + v = v.replace(reLeadingNewline, ''); + } // Trim a trailing newline from the last string + + + if (i === l - 1 && trimTrailingNewline) { + v = v.replace(reTrailingNewline, ''); + } // Normalize newlines + + + if (normalizeNewlines) { + v = v.replace(/\r\n|\n|\r/g, function (_) { + return newline; + }); + } + + return v; + }); + return outdentedStrings; + } + + function concatStringsAndValues(strings, values) { + var ret = ''; + + for (var i = 0, l = strings.length; i < l; i++) { + ret += strings[i]; + + if (i < l - 1) { + ret += values[i]; + } + } + + return ret; + } + + function isTemplateStringsArray(v) { + return has(v, 'raw') && has(v, 'length'); + } + /** + * It is assumed that opts will not change. If this is a problem, clone your options object and pass the clone to + * makeInstance + * @param options + * @return {outdent} + */ + + + function createInstance(options) { + /** Cache of pre-processed template literal arrays */ + var arrayAutoIndentCache = createWeakMap(); + /** + * Cache of pre-processed template literal arrays, where first interpolated value is a reference to outdent, + * before interpolated values are injected. + */ + + var arrayFirstInterpSetsIndentCache = createWeakMap(); + + function outdent(stringsOrOptions) { + var values = []; + + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + /* tslint:enable:no-shadowed-variable */ + + + if (isTemplateStringsArray(stringsOrOptions)) { + var strings = stringsOrOptions; // Is first interpolated value a reference to outdent, alone on its own line, without any preceding non-whitespace? + + var firstInterpolatedValueSetsIndentationLevel = (values[0] === outdent || values[0] === defaultOutdent) && reOnlyWhitespaceWithAtLeastOneNewline.test(strings[0]) && reStartsWithNewlineOrIsEmpty.test(strings[1]); // Perform outdentation + + var cache = firstInterpolatedValueSetsIndentationLevel ? arrayFirstInterpSetsIndentCache : arrayAutoIndentCache; + var renderedArray = cache.get(strings); + + if (!renderedArray) { + renderedArray = _outdentArray(strings, firstInterpolatedValueSetsIndentationLevel, options); + cache.set(strings, renderedArray); + } + /** If no interpolated values, skip concatenation step */ + + + if (values.length === 0) { + return renderedArray[0]; + } + /** Concatenate string literals with interpolated values */ + + + var rendered = concatStringsAndValues(renderedArray, firstInterpolatedValueSetsIndentationLevel ? values.slice(1) : values); + return rendered; + } else { + // Create and return a new instance of outdent with the given options + return createInstance(extend(extend({}, options), stringsOrOptions || {})); + } + } + + var fullOutdent = extend(outdent, { + string: function (str) { + return _outdentArray([str], false, options)[0]; + } + }); + return fullOutdent; + } + + var defaultOutdent = createInstance({ + trimLeadingNewline: true, + trimTrailingNewline: true + }); + exports.outdent = defaultOutdent; // Named exports. Simple and preferred. + // import outdent from 'outdent'; + + exports.default = defaultOutdent; + + { + // In webpack harmony-modules environments, module.exports is read-only, + // so we fail gracefully. + try { + module.exports = defaultOutdent; + Object.defineProperty(defaultOutdent, '__esModule', { + value: true + }); + defaultOutdent.default = defaultOutdent; + defaultOutdent.outdent = defaultOutdent; + } catch (e) {} + } +}); + +const { + outdent +} = lib; +const CATEGORY_CONFIG = "Config"; +const CATEGORY_EDITOR = "Editor"; +const CATEGORY_FORMAT = "Format"; +const CATEGORY_OTHER = "Other"; +const CATEGORY_OUTPUT = "Output"; +const CATEGORY_GLOBAL = "Global"; +const CATEGORY_SPECIAL = "Special"; +/** + * @typedef {Object} OptionInfo + * @property {string} [since] - available since version + * @property {string} category + * @property {'int' | 'boolean' | 'choice' | 'path'} type + * @property {boolean} [array] - indicate it's an array of the specified type + * @property {OptionValueInfo} [default] + * @property {OptionRangeInfo} [range] - for type int + * @property {string} description + * @property {string} [deprecated] - deprecated since version + * @property {OptionRedirectInfo} [redirect] - redirect deprecated option + * @property {(value: any) => boolean} [exception] + * @property {OptionChoiceInfo[]} [choices] - for type choice + * @property {string} [cliName] + * @property {string} [cliCategory] + * @property {string} [cliDescription] + * + * @typedef {number | boolean | string} OptionValue + * @typedef {OptionValue | [{ value: OptionValue[] }] | Array<{ since: string, value: OptionValue}>} OptionValueInfo + * + * @typedef {Object} OptionRedirectInfo + * @property {string} option + * @property {OptionValue} value + * + * @typedef {Object} OptionRangeInfo + * @property {number} start - recommended range start + * @property {number} end - recommended range end + * @property {number} step - recommended range step + * + * @typedef {Object} OptionChoiceInfo + * @property {boolean | string} value - boolean for the option that is originally boolean type + * @property {string} description + * @property {string} [since] - undefined if available since the first version of the option + * @property {string} [deprecated] - deprecated since version + * @property {OptionValueInfo} [redirect] - redirect deprecated value + */ + +/** @type {{ [name: string]: OptionInfo }} */ + +const options = { + cursorOffset: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: -1, + range: { + start: -1, + end: Infinity, + step: 1 + }, + description: outdent` + Print (to stderr) where a cursor at the given position would move to after formatting. + This option cannot be used with --range-start and --range-end. + `, + cliCategory: CATEGORY_EDITOR + }, + endOfLine: { + since: "1.15.0", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "1.15.0", + value: "auto" + }, { + since: "2.0.0", + value: "lf" + }], + description: "Which end of line characters to apply.", + choices: [{ + value: "lf", + description: "Line Feed only (\\n), common on Linux and macOS as well as inside git repos" + }, { + value: "crlf", + description: "Carriage Return + Line Feed characters (\\r\\n), common on Windows" + }, { + value: "cr", + description: "Carriage Return character only (\\r), used very rarely" + }, { + value: "auto", + description: outdent` + Maintain existing + (mixed values within one file are normalised by looking at what's used after the first line) + ` + }] + }, + filepath: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "path", + description: "Specify the input filepath. This will be used to do parser inference.", + cliName: "stdin-filepath", + cliCategory: CATEGORY_OTHER, + cliDescription: "Path to the file to pretend that stdin comes from." + }, + insertPragma: { + since: "1.8.0", + category: CATEGORY_SPECIAL, + type: "boolean", + default: false, + description: "Insert @format pragma into file's first docblock comment.", + cliCategory: CATEGORY_OTHER + }, + parser: { + since: "0.0.10", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "0.0.10", + value: "babylon" + }, { + since: "1.13.0", + value: undefined + }], + description: "Which parser to use.", + exception: value => typeof value === "string" || typeof value === "function", + choices: [{ + value: "flow", + description: "Flow" + }, { + value: "babel", + since: "1.16.0", + description: "JavaScript" + }, { + value: "babel-flow", + since: "1.16.0", + description: "Flow" + }, { + value: "babel-ts", + since: "2.0.0", + description: "TypeScript" + }, { + value: "typescript", + since: "1.4.0", + description: "TypeScript" + }, { + value: "css", + since: "1.7.1", + description: "CSS" + }, { + value: "less", + since: "1.7.1", + description: "Less" + }, { + value: "scss", + since: "1.7.1", + description: "SCSS" + }, { + value: "json", + since: "1.5.0", + description: "JSON" + }, { + value: "json5", + since: "1.13.0", + description: "JSON5" + }, { + value: "json-stringify", + since: "1.13.0", + description: "JSON.stringify" + }, { + value: "graphql", + since: "1.5.0", + description: "GraphQL" + }, { + value: "markdown", + since: "1.8.0", + description: "Markdown" + }, { + value: "mdx", + since: "1.15.0", + description: "MDX" + }, { + value: "vue", + since: "1.10.0", + description: "Vue" + }, { + value: "yaml", + since: "1.14.0", + description: "YAML" + }, { + value: "glimmer", + since: null, + description: "Handlebars" + }, { + value: "html", + since: "1.15.0", + description: "HTML" + }, { + value: "angular", + since: "1.15.0", + description: "Angular" + }, { + value: "lwc", + since: "1.17.0", + description: "Lightning Web Components" + }] + }, + plugins: { + since: "1.10.0", + type: "path", + array: true, + default: [{ + value: [] + }], + category: CATEGORY_GLOBAL, + description: "Add a plugin. Multiple plugins can be passed as separate `--plugin`s.", + exception: value => typeof value === "string" || typeof value === "object", + cliName: "plugin", + cliCategory: CATEGORY_CONFIG + }, + pluginSearchDirs: { + since: "1.13.0", + type: "path", + array: true, + default: [{ + value: [] + }], + category: CATEGORY_GLOBAL, + description: outdent` + Custom directory that contains prettier plugins in node_modules subdirectory. + Overrides default behavior when plugins are searched relatively to the location of Prettier. + Multiple values are accepted. + `, + exception: value => typeof value === "string" || typeof value === "object", + cliName: "plugin-search-dir", + cliCategory: CATEGORY_CONFIG + }, + printWidth: { + since: "0.0.0", + category: CATEGORY_GLOBAL, + type: "int", + default: 80, + description: "The line length where Prettier will try wrap.", + range: { + start: 0, + end: Infinity, + step: 1 + } + }, + rangeEnd: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: Infinity, + range: { + start: 0, + end: Infinity, + step: 1 + }, + description: outdent` + Format code ending at a given character offset (exclusive). + The range will extend forwards to the end of the selected statement. + This option cannot be used with --cursor-offset. + `, + cliCategory: CATEGORY_EDITOR + }, + rangeStart: { + since: "1.4.0", + category: CATEGORY_SPECIAL, + type: "int", + default: 0, + range: { + start: 0, + end: Infinity, + step: 1 + }, + description: outdent` + Format code starting at a given character offset. + The range will extend backwards to the start of the first line containing the selected statement. + This option cannot be used with --cursor-offset. + `, + cliCategory: CATEGORY_EDITOR + }, + requirePragma: { + since: "1.7.0", + category: CATEGORY_SPECIAL, + type: "boolean", + default: false, + description: outdent` + Require either '@prettier' or '@format' to be present in the file's first docblock comment + in order for it to be formatted. + `, + cliCategory: CATEGORY_OTHER + }, + tabWidth: { + type: "int", + category: CATEGORY_GLOBAL, + default: 2, + description: "Number of spaces per indentation level.", + range: { + start: 0, + end: Infinity, + step: 1 + } + }, + useTabs: { + since: "1.0.0", + category: CATEGORY_GLOBAL, + type: "boolean", + default: false, + description: "Indent with tabs instead of spaces." + }, + embeddedLanguageFormatting: { + since: "2.1.0", + category: CATEGORY_GLOBAL, + type: "choice", + default: [{ + since: "2.1.0", + value: "auto" + }], + description: "Control how Prettier formats quoted code embedded in the file.", + choices: [{ + value: "auto", + description: "Format embedded code if Prettier can automatically identify it." + }, { + value: "off", + description: "Never automatically format embedded code." + }] + } +}; +var coreOptions = { + CATEGORY_CONFIG, + CATEGORY_EDITOR, + CATEGORY_FORMAT, + CATEGORY_OTHER, + CATEGORY_OUTPUT, + CATEGORY_GLOBAL, + CATEGORY_SPECIAL, + options +}; + +var require$$0 = getCjsExportFromNamespace(_package$1); + +const semver$1 = { + compare: compare_1, + lt: lt_1, + gte: gte_1 +}; +const currentVersion = require$$0.version; +const coreOptions$1 = coreOptions.options; +/** + * Strings in `plugins` and `pluginSearchDirs` are handled by a wrapped version + * of this function created by `withPlugins`. Don't pass them here directly. + * @param {object} param0 + * @param {(string | object)[]=} param0.plugins Strings are resolved by `withPlugins`. + * @param {string[]=} param0.pluginSearchDirs Added by `withPlugins`. + * @param {boolean=} param0.showUnreleased + * @param {boolean=} param0.showDeprecated + * @param {boolean=} param0.showInternal + */ + +function getSupportInfo({ + plugins = [], + showUnreleased = false, + showDeprecated = false, + showInternal = false +} = {}) { + // pre-release version is smaller than the normal version in semver, + // we need to treat it as the normal one so as to test new features. + const version = currentVersion.split("-", 1)[0]; + const languages = plugins.reduce((all, plugin) => all.concat(plugin.languages || []), []).filter(filterSince); + const options = arrayify(Object.assign({}, ...plugins.map(({ + options + }) => options), coreOptions$1), "name").filter(option => filterSince(option) && filterDeprecated(option)).sort((a, b) => a.name === b.name ? 0 : a.name < b.name ? -1 : 1).map(mapInternal).map(option => { + option = Object.assign({}, option); + + if (Array.isArray(option.default)) { + option.default = option.default.length === 1 ? option.default[0].value : option.default.filter(filterSince).sort((info1, info2) => semver$1.compare(info2.since, info1.since))[0].value; + } + + if (Array.isArray(option.choices)) { + option.choices = option.choices.filter(option => filterSince(option) && filterDeprecated(option)); + + if (option.name === "parser") { + collectParsersFromLanguages(option, languages, plugins); + } + } + + const pluginDefaults = plugins.filter(plugin => plugin.defaultOptions && plugin.defaultOptions[option.name] !== undefined).reduce((reduced, plugin) => { + reduced[plugin.name] = plugin.defaultOptions[option.name]; + return reduced; + }, {}); + return Object.assign({}, option, { + pluginDefaults + }); + }); + return { + languages, + options + }; + + function filterSince(object) { + return showUnreleased || !("since" in object) || object.since && semver$1.gte(version, object.since); + } + + function filterDeprecated(object) { + return showDeprecated || !("deprecated" in object) || object.deprecated && semver$1.lt(version, object.deprecated); + } + + function mapInternal(object) { + if (showInternal) { + return object; + } + + const newObject = _objectWithoutPropertiesLoose(object, ["cliName", "cliCategory", "cliDescription"]); + + return newObject; + } +} + +function collectParsersFromLanguages(option, languages, plugins) { + const existingValues = new Set(option.choices.map(choice => choice.value)); + + for (const language of languages) { + if (language.parsers) { + for (const value of language.parsers) { + if (!existingValues.has(value)) { + existingValues.add(value); + const plugin = plugins.find(plugin => plugin.parsers && plugin.parsers[value]); + let description = language.name; + + if (plugin && plugin.name) { + description += ` (plugin: ${plugin.name})`; + } + + option.choices.push({ + value, + description + }); + } + } + } + } +} + +var support = { + getSupportInfo +}; + +const notAsciiRegex = /[^\x20-\x7F]/; + +const getPenultimate = arr => arr[arr.length - 2]; +/** + * @typedef {{backwards?: boolean}} SkipOptions + */ + +/** + * @param {string | RegExp} chars + * @returns {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + +function skip(chars) { + return (text, index, opts) => { + const backwards = opts && opts.backwards; // Allow `skip` functions to be threaded together without having + // to check for failures (did someone say monads?). + + /* istanbul ignore next */ + + if (index === false) { + return false; + } + + const { + length + } = text; + let cursor = index; + + while (cursor >= 0 && cursor < length) { + const c = text.charAt(cursor); + + if (chars instanceof RegExp) { + if (!chars.test(c)) { + return cursor; + } + } else if (!chars.includes(c)) { + return cursor; + } + + backwards ? cursor-- : cursor++; + } + + if (cursor === -1 || cursor === length) { + // If we reached the beginning or end of the file, return the + // out-of-bounds cursor. It's up to the caller to handle this + // correctly. We don't want to indicate `false` though if it + // actually skipped valid characters. + return cursor; + } + + return false; + }; +} +/** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + + +const skipWhitespace = skip(/\s/); +/** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + +const skipSpaces = skip(" \t"); +/** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + +const skipToLineEnd = skip(",; \t"); +/** + * @type {(text: string, index: number | false, opts?: SkipOptions) => number | false} + */ + +const skipEverythingButNewLine = skip(/[^\n\r]/); +/** + * @param {string} text + * @param {number | false} index + * @returns {number | false} + */ + +function skipInlineComment(text, index) { + /* istanbul ignore next */ + if (index === false) { + return false; + } + + if (text.charAt(index) === "/" && text.charAt(index + 1) === "*") { + for (let i = index + 2; i < text.length; ++i) { + if (text.charAt(i) === "*" && text.charAt(i + 1) === "/") { + return i + 2; + } + } + } + + return index; +} +/** + * @param {string} text + * @param {number | false} index + * @returns {number | false} + */ + + +function skipTrailingComment(text, index) { + /* istanbul ignore next */ + if (index === false) { + return false; + } + + if (text.charAt(index) === "/" && text.charAt(index + 1) === "/") { + return skipEverythingButNewLine(text, index); + } + + return index; +} // This one doesn't use the above helper function because it wants to +// test \r\n in order and `skip` doesn't support ordering and we only +// want to skip one newline. It's simple to implement. + +/** + * @param {string} text + * @param {number | false} index + * @param {SkipOptions=} opts + * @returns {number | false} + */ + + +function skipNewline(text, index, opts) { + const backwards = opts && opts.backwards; + + if (index === false) { + return false; + } + + const atIndex = text.charAt(index); + + if (backwards) { + // We already replace `\r\n` with `\n` before parsing + + /* istanbul ignore next */ + if (text.charAt(index - 1) === "\r" && atIndex === "\n") { + return index - 2; + } + + if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { + return index - 1; + } + } else { + // We already replace `\r\n` with `\n` before parsing + + /* istanbul ignore next */ + if (atIndex === "\r" && text.charAt(index + 1) === "\n") { + return index + 2; + } + + if (atIndex === "\n" || atIndex === "\r" || atIndex === "\u2028" || atIndex === "\u2029") { + return index + 1; + } + } + + return index; +} +/** + * @param {string} text + * @param {number} index + * @param {SkipOptions=} opts + * @returns {boolean} + */ + + +function hasNewline(text, index, opts) { + opts = opts || {}; + const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); + const idx2 = skipNewline(text, idx, opts); + return idx !== idx2; +} +/** + * @param {string} text + * @param {number} start + * @param {number} end + * @returns {boolean} + */ + + +function hasNewlineInRange(text, start, end) { + for (let i = start; i < end; ++i) { + if (text.charAt(i) === "\n") { + return true; + } + } + + return false; +} // Note: this function doesn't ignore leading comments unlike isNextLineEmpty + +/** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locStart + */ + + +function isPreviousLineEmpty(text, node, locStart) { + /** @type {number | false} */ + let idx = locStart(node) - 1; + idx = skipSpaces(text, idx, { + backwards: true + }); + idx = skipNewline(text, idx, { + backwards: true + }); + idx = skipSpaces(text, idx, { + backwards: true + }); + const idx2 = skipNewline(text, idx, { + backwards: true + }); + return idx !== idx2; +} +/** + * @param {string} text + * @param {number} index + * @returns {boolean} + */ + + +function isNextLineEmptyAfterIndex(text, index) { + /** @type {number | false} */ + let oldIdx = null; + /** @type {number | false} */ + + let idx = index; + + while (idx !== oldIdx) { + // We need to skip all the potential trailing inline comments + oldIdx = idx; + idx = skipToLineEnd(text, idx); + idx = skipInlineComment(text, idx); + idx = skipSpaces(text, idx); + } + + idx = skipTrailingComment(text, idx); + idx = skipNewline(text, idx); + return idx !== false && hasNewline(text, idx); +} +/** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {boolean} + */ + + +function isNextLineEmpty(text, node, locEnd) { + return isNextLineEmptyAfterIndex(text, locEnd(node)); +} +/** + * @param {string} text + * @param {number} idx + * @returns {number | false} + */ + + +function getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, idx) { + /** @type {number | false} */ + let oldIdx = null; + /** @type {number | false} */ + + let nextIdx = idx; + + while (nextIdx !== oldIdx) { + oldIdx = nextIdx; + nextIdx = skipSpaces(text, nextIdx); + nextIdx = skipInlineComment(text, nextIdx); + nextIdx = skipTrailingComment(text, nextIdx); + nextIdx = skipNewline(text, nextIdx); + } + + return nextIdx; +} +/** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {number | false} + */ + + +function getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd) { + return getNextNonSpaceNonCommentCharacterIndexWithStartIndex(text, locEnd(node)); +} +/** + * @template N + * @param {string} text + * @param {N} node + * @param {(node: N) => number} locEnd + * @returns {string} + */ + + +function getNextNonSpaceNonCommentCharacter(text, node, locEnd) { + return text.charAt( // @ts-ignore => TBD: can return false, should we define a fallback? + getNextNonSpaceNonCommentCharacterIndex(text, node, locEnd)); +} // Not using, but it's public utils + +/* istanbul ignore next */ + +/** + * @param {string} text + * @param {number} index + * @param {SkipOptions=} opts + * @returns {boolean} + */ + + +function hasSpaces(text, index, opts) { + opts = opts || {}; + const idx = skipSpaces(text, opts.backwards ? index - 1 : index, opts); + return idx !== index; +} +/** + * @param {string} value + * @param {number} tabWidth + * @param {number=} startIndex + * @returns {number} + */ + + +function getAlignmentSize(value, tabWidth, startIndex) { + startIndex = startIndex || 0; + let size = 0; + + for (let i = startIndex; i < value.length; ++i) { + if (value[i] === "\t") { + // Tabs behave in a way that they are aligned to the nearest + // multiple of tabWidth: + // 0 -> 4, 1 -> 4, 2 -> 4, 3 -> 4 + // 4 -> 8, 5 -> 8, 6 -> 8, 7 -> 8 ... + size = size + tabWidth - size % tabWidth; + } else { + size++; + } + } + + return size; +} +/** + * @param {string} value + * @param {number} tabWidth + * @returns {number} + */ + + +function getIndentSize(value, tabWidth) { + const lastNewlineIndex = value.lastIndexOf("\n"); + + if (lastNewlineIndex === -1) { + return 0; + } + + return getAlignmentSize( // All the leading whitespaces + value.slice(lastNewlineIndex + 1).match(/^[\t ]*/)[0], tabWidth); +} +/** + * @typedef {'"' | "'"} Quote + */ + +/** + * + * @param {string} raw + * @param {Quote} preferredQuote + * @returns {Quote} + */ + + +function getPreferredQuote(raw, preferredQuote) { + // `rawContent` is the string exactly like it appeared in the input source + // code, without its enclosing quotes. + const rawContent = raw.slice(1, -1); + /** @type {{ quote: '"', regex: RegExp }} */ + + const double = { + quote: '"', + regex: /"/g + }; + /** @type {{ quote: "'", regex: RegExp }} */ + + const single = { + quote: "'", + regex: /'/g + }; + const preferred = preferredQuote === "'" ? single : double; + const alternate = preferred === single ? double : single; + let result = preferred.quote; // If `rawContent` contains at least one of the quote preferred for enclosing + // the string, we might want to enclose with the alternate quote instead, to + // minimize the number of escaped quotes. + + if (rawContent.includes(preferred.quote) || rawContent.includes(alternate.quote)) { + const numPreferredQuotes = (rawContent.match(preferred.regex) || []).length; + const numAlternateQuotes = (rawContent.match(alternate.regex) || []).length; + result = numPreferredQuotes > numAlternateQuotes ? alternate.quote : preferred.quote; + } + + return result; +} + +function printString(raw, options, isDirectiveLiteral) { + // `rawContent` is the string exactly like it appeared in the input source + // code, without its enclosing quotes. + const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap + // the quotes on a DirectiveLiteral. + + const canChangeDirectiveQuotes = !rawContent.includes('"') && !rawContent.includes("'"); + /** @type {Quote} */ + + const enclosingQuote = options.parser === "json" ? '"' : options.__isInHtmlAttribute ? "'" : getPreferredQuote(raw, options.singleQuote ? "'" : '"'); // Directives are exact code unit sequences, which means that you can't + // change the escape sequences they use. + // See https://github.com/prettier/prettier/issues/1555 + // and https://tc39.github.io/ecma262/#directive-prologue + + if (isDirectiveLiteral) { + if (canChangeDirectiveQuotes) { + return enclosingQuote + rawContent + enclosingQuote; + } + + return raw; + } // It might sound unnecessary to use `makeString` even if the string already + // is enclosed with `enclosingQuote`, but it isn't. The string could contain + // unnecessary escapes (such as in `"\'"`). Always using `makeString` makes + // sure that we consistently output the minimum amount of escaped quotes. + + + return makeString(rawContent, enclosingQuote, !(options.parser === "css" || options.parser === "less" || options.parser === "scss" || options.embeddedInHtml)); +} +/** + * @param {string} rawContent + * @param {Quote} enclosingQuote + * @param {boolean=} unescapeUnnecessaryEscapes + * @returns {string} + */ + + +function makeString(rawContent, enclosingQuote, unescapeUnnecessaryEscapes) { + const otherQuote = enclosingQuote === '"' ? "'" : '"'; // Matches _any_ escape and unescaped quotes (both single and double). + + const regex = /\\([\S\s])|(["'])/g; // Escape and unescape single and double quotes as needed to be able to + // enclose `rawContent` with `enclosingQuote`. + + const newContent = rawContent.replace(regex, (match, escaped, quote) => { + // If we matched an escape, and the escaped character is a quote of the + // other type than we intend to enclose the string with, there's no need for + // it to be escaped, so return it _without_ the backslash. + if (escaped === otherQuote) { + return escaped; + } // If we matched an unescaped quote and it is of the _same_ type as we + // intend to enclose the string with, it must be escaped, so return it with + // a backslash. + + + if (quote === enclosingQuote) { + return "\\" + quote; + } + + if (quote) { + return quote; + } // Unescape any unnecessarily escaped character. + // Adapted from https://github.com/eslint/eslint/blob/de0b4ad7bd820ade41b1f606008bea68683dc11a/lib/rules/no-useless-escape.js#L27 + + + return unescapeUnnecessaryEscapes && /^[^\n\r"'0-7\\bfnrt-vx\u2028\u2029]$/.test(escaped) ? escaped : "\\" + escaped; + }); + return enclosingQuote + newContent + enclosingQuote; +} + +function printNumber(rawNumber) { + return rawNumber.toLowerCase() // Remove unnecessary plus and zeroes from scientific notation. + .replace(/^([+-]?[\d.]+e)(?:\+|(-))?0*(\d)/, "$1$2$3") // Remove unnecessary scientific notation (1e0). + .replace(/^([+-]?[\d.]+)e[+-]?0+$/, "$1") // Make sure numbers always start with a digit. + .replace(/^([+-])?\./, "$10.") // Remove extraneous trailing decimal zeroes. + .replace(/(\.\d+?)0+(?=e|$)/, "$1") // Remove trailing dot. + .replace(/\.(?=e|$)/, ""); +} +/** + * @param {string} str + * @param {string} target + * @returns {number} + */ + + +function getMaxContinuousCount(str, target) { + const results = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g")); + + if (results === null) { + return 0; + } + + return results.reduce((maxCount, result) => Math.max(maxCount, result.length / target.length), 0); +} + +function getMinNotPresentContinuousCount(str, target) { + const matches = str.match(new RegExp(`(${escapeStringRegexp(target)})+`, "g")); + + if (matches === null) { + return 0; + } + + const countPresent = new Map(); + let max = 0; + + for (const match of matches) { + const count = match.length / target.length; + countPresent.set(count, true); + + if (count > max) { + max = count; + } + } + + for (let i = 1; i < max; i++) { + if (!countPresent.get(i)) { + return i; + } + } + + return max + 1; +} +/** + * @param {string} text + * @returns {number} + */ + + +function getStringWidth(text) { + if (!text) { + return 0; + } // shortcut to avoid needless string `RegExp`s, replacements, and allocations within `string-width` + + + if (!notAsciiRegex.test(text)) { + return text.length; + } + + return stringWidth_1(text); +} + +function hasIgnoreComment(path) { + const node = path.getValue(); + return hasNodeIgnoreComment(node); +} + +function hasNodeIgnoreComment(node) { + return node && (node.comments && node.comments.length > 0 && node.comments.some(comment => isNodeIgnoreComment(comment) && !comment.unignore) || node.prettierIgnore); +} + +function isNodeIgnoreComment(comment) { + return comment.value.trim() === "prettier-ignore"; +} + +function addCommentHelper(node, comment) { + const comments = node.comments || (node.comments = []); + comments.push(comment); + comment.printed = false; // For some reason, TypeScript parses `// x` inside of JSXText as a comment + // We already "print" it via the raw text, we don't need to re-print it as a + // comment + + /* istanbul ignore next */ + + if (node.type === "JSXText") { + comment.printed = true; + } +} + +function addLeadingComment(node, comment) { + comment.leading = true; + comment.trailing = false; + addCommentHelper(node, comment); +} + +function addDanglingComment(node, comment, marker) { + comment.leading = false; + comment.trailing = false; + + if (marker) { + comment.marker = marker; + } + + addCommentHelper(node, comment); +} + +function addTrailingComment(node, comment) { + comment.leading = false; + comment.trailing = true; + addCommentHelper(node, comment); +} // Not using + +/* istanbul ignore next */ + + +function isWithinParentArrayProperty(path, propertyName) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (parent == null) { + return false; + } + + if (!Array.isArray(parent[propertyName])) { + return false; + } + + const key = path.getName(); + return parent[propertyName][key] === node; +} + +function replaceEndOfLineWith(text, replacement) { + const parts = []; + + for (const part of text.split("\n")) { + if (parts.length !== 0) { + parts.push(replacement); + } + + parts.push(part); + } + + return parts; +} + +function getParserName(lang, options) { + const supportInfo = support.getSupportInfo({ + plugins: options.plugins + }); + const language = supportInfo.languages.find(language => language.name.toLowerCase() === lang || language.aliases && language.aliases.includes(lang) || language.extensions && language.extensions.some(ext => ext === `.${lang}`)); + + if (language) { + return language.parsers[0]; + } + + return null; +} + +function isFrontMatterNode(node) { + return node && node.type === "front-matter"; +} + +function getShebang(text) { + if (!text.startsWith("#!")) { + return ""; + } + + const index = text.indexOf("\n"); + + if (index === -1) { + return text; + } + + return text.slice(0, index); +} + +var util = { + replaceEndOfLineWith, + getStringWidth, + getMaxContinuousCount, + getMinNotPresentContinuousCount, + getParserName, + getPenultimate, + getLast, + getNextNonSpaceNonCommentCharacterIndexWithStartIndex, + getNextNonSpaceNonCommentCharacterIndex, + getNextNonSpaceNonCommentCharacter, + skip, + skipWhitespace, + skipSpaces, + skipToLineEnd, + skipEverythingButNewLine, + skipInlineComment, + skipTrailingComment, + skipNewline, + isNextLineEmptyAfterIndex, + isNextLineEmpty, + isPreviousLineEmpty, + hasNewline, + hasNewlineInRange, + hasSpaces, + getAlignmentSize, + getIndentSize, + getPreferredQuote, + printString, + printNumber, + hasIgnoreComment, + hasNodeIgnoreComment, + isNodeIgnoreComment, + makeString, + addLeadingComment, + addDanglingComment, + addTrailingComment, + isWithinParentArrayProperty, + isFrontMatterNode, + getShebang +}; + +function guessEndOfLine(text) { + const index = text.indexOf("\r"); + + if (index >= 0) { + return text.charAt(index + 1) === "\n" ? "crlf" : "cr"; + } + + return "lf"; +} + +function convertEndOfLineToChars(value) { + switch (value) { + case "cr": + return "\r"; + + case "crlf": + return "\r\n"; + + default: + return "\n"; + } +} + +function countEndOfLineChars(text, eol) { + let regex; + /* istanbul ignore else */ + + if (eol === "\n") { + regex = /\n/g; + } else if (eol === "\r") { + regex = /\r/g; + } else if (eol === "\r\n") { + regex = /\r\n/g; + } else { + throw new Error(`Unexpected "eol" ${JSON.stringify(eol)}.`); + } + + const endOfLines = text.match(regex); + return endOfLines ? endOfLines.length : 0; +} + +function normalizeEndOfLine(text) { + return text.replace(/\r\n?/g, "\n"); +} + +var endOfLine = { + guessEndOfLine, + convertEndOfLineToChars, + countEndOfLineChars, + normalizeEndOfLine +}; + +const { + getStringWidth: getStringWidth$1 +} = util; +const { + convertEndOfLineToChars: convertEndOfLineToChars$1 +} = endOfLine; +const { + concat: concat$1, + fill: fill$1, + cursor: cursor$1 +} = docBuilders; +/** @type {Record} */ + +let groupModeMap; +const MODE_BREAK = 1; +const MODE_FLAT = 2; + +function rootIndent() { + return { + value: "", + length: 0, + queue: [] + }; +} + +function makeIndent(ind, options) { + return generateInd(ind, { + type: "indent" + }, options); +} + +function makeAlign(indent, n, options) { + if (n === -Infinity) { + return indent.root || rootIndent(); + } + + if (n < 0) { + return generateInd(indent, { + type: "dedent" + }, options); + } + + if (!n) { + return indent; + } + + if (n.type === "root") { + return Object.assign({}, indent, { + root: indent + }); + } + + const alignType = typeof n === "string" ? "stringAlign" : "numberAlign"; + return generateInd(indent, { + type: alignType, + n + }, options); +} + +function generateInd(ind, newPart, options) { + const queue = newPart.type === "dedent" ? ind.queue.slice(0, -1) : ind.queue.concat(newPart); + let value = ""; + let length = 0; + let lastTabs = 0; + let lastSpaces = 0; + + for (const part of queue) { + switch (part.type) { + case "indent": + flush(); + + if (options.useTabs) { + addTabs(1); + } else { + addSpaces(options.tabWidth); + } + + break; + + case "stringAlign": + flush(); + value += part.n; + length += part.n.length; + break; + + case "numberAlign": + lastTabs += 1; + lastSpaces += part.n; + break; + + /* istanbul ignore next */ + + default: + throw new Error(`Unexpected type '${part.type}'`); + } + } + + flushSpaces(); + return Object.assign({}, ind, { + value, + length, + queue + }); + + function addTabs(count) { + value += "\t".repeat(count); + length += options.tabWidth * count; + } + + function addSpaces(count) { + value += " ".repeat(count); + length += count; + } + + function flush() { + if (options.useTabs) { + flushTabs(); + } else { + flushSpaces(); + } + } + + function flushTabs() { + if (lastTabs > 0) { + addTabs(lastTabs); + } + + resetLast(); + } + + function flushSpaces() { + if (lastSpaces > 0) { + addSpaces(lastSpaces); + } + + resetLast(); + } + + function resetLast() { + lastTabs = 0; + lastSpaces = 0; + } +} + +function trim$1(out) { + if (out.length === 0) { + return 0; + } + + let trimCount = 0; // Trim whitespace at the end of line + + while (out.length > 0 && typeof out[out.length - 1] === "string" && out[out.length - 1].match(/^[\t ]*$/)) { + trimCount += out.pop().length; + } + + if (out.length && typeof out[out.length - 1] === "string") { + const trimmed = out[out.length - 1].replace(/[\t ]*$/, ""); + trimCount += out[out.length - 1].length - trimmed.length; + out[out.length - 1] = trimmed; + } + + return trimCount; +} + +function fits(next, restCommands, width, options, mustBeFlat) { + let restIdx = restCommands.length; + const cmds = [next]; // `out` is only used for width counting because `trim` requires to look + // backwards for space characters. + + const out = []; + + while (width >= 0) { + if (cmds.length === 0) { + if (restIdx === 0) { + return true; + } + + cmds.push(restCommands[restIdx - 1]); + restIdx--; + continue; + } + + const [ind, mode, doc] = cmds.pop(); + + if (typeof doc === "string") { + out.push(doc); + width -= getStringWidth$1(doc); + } else { + switch (doc.type) { + case "concat": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "indent": + cmds.push([makeIndent(ind, options), mode, doc.contents]); + break; + + case "align": + cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); + break; + + case "trim": + width += trim$1(out); + break; + + case "group": + if (mustBeFlat && doc.break) { + return false; + } + + cmds.push([ind, doc.break ? MODE_BREAK : mode, doc.contents]); + + if (doc.id) { + groupModeMap[doc.id] = cmds[cmds.length - 1][1]; + } + + break; + + case "fill": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "if-break": + { + const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; + + if (groupMode === MODE_BREAK) { + if (doc.breakContents) { + cmds.push([ind, mode, doc.breakContents]); + } + } + + if (groupMode === MODE_FLAT) { + if (doc.flatContents) { + cmds.push([ind, mode, doc.flatContents]); + } + } + + break; + } + + case "line": + switch (mode) { + // fallthrough + case MODE_FLAT: + if (!doc.hard) { + if (!doc.soft) { + out.push(" "); + width -= 1; + } + + break; + } + + return true; + + case MODE_BREAK: + return true; + } + + break; + } + } + } + + return false; +} + +function printDocToString(doc, options) { + groupModeMap = {}; + const width = options.printWidth; + const newLine = convertEndOfLineToChars$1(options.endOfLine); + let pos = 0; // cmds is basically a stack. We've turned a recursive call into a + // while loop which is much faster. The while loop below adds new + // cmds to the array instead of recursively calling `print`. + + const cmds = [[rootIndent(), MODE_BREAK, doc]]; + const out = []; + let shouldRemeasure = false; + let lineSuffix = []; + + while (cmds.length !== 0) { + const [ind, mode, doc] = cmds.pop(); + + if (typeof doc === "string") { + const formatted = newLine !== "\n" && doc.includes("\n") ? doc.replace(/\n/g, newLine) : doc; + out.push(formatted); + pos += getStringWidth$1(formatted); + } else { + switch (doc.type) { + case "cursor": + out.push(cursor$1.placeholder); + break; + + case "concat": + for (let i = doc.parts.length - 1; i >= 0; i--) { + cmds.push([ind, mode, doc.parts[i]]); + } + + break; + + case "indent": + cmds.push([makeIndent(ind, options), mode, doc.contents]); + break; + + case "align": + cmds.push([makeAlign(ind, doc.n, options), mode, doc.contents]); + break; + + case "trim": + pos -= trim$1(out); + break; + + case "group": + switch (mode) { + case MODE_FLAT: + if (!shouldRemeasure) { + cmds.push([ind, doc.break ? MODE_BREAK : MODE_FLAT, doc.contents]); + break; + } + + // fallthrough + + case MODE_BREAK: + { + shouldRemeasure = false; + const next = [ind, MODE_FLAT, doc.contents]; + const rem = width - pos; + + if (!doc.break && fits(next, cmds, rem, options)) { + cmds.push(next); + } else { + // Expanded states are a rare case where a document + // can manually provide multiple representations of + // itself. It provides an array of documents + // going from the least expanded (most flattened) + // representation first to the most expanded. If a + // group has these, we need to manually go through + // these states and find the first one that fits. + if (doc.expandedStates) { + const mostExpanded = doc.expandedStates[doc.expandedStates.length - 1]; + + if (doc.break) { + cmds.push([ind, MODE_BREAK, mostExpanded]); + break; + } else { + for (let i = 1; i < doc.expandedStates.length + 1; i++) { + if (i >= doc.expandedStates.length) { + cmds.push([ind, MODE_BREAK, mostExpanded]); + break; + } else { + const state = doc.expandedStates[i]; + const cmd = [ind, MODE_FLAT, state]; + + if (fits(cmd, cmds, rem, options)) { + cmds.push(cmd); + break; + } + } + } + } + } else { + cmds.push([ind, MODE_BREAK, doc.contents]); + } + } + + break; + } + } + + if (doc.id) { + groupModeMap[doc.id] = cmds[cmds.length - 1][1]; + } + + break; + // Fills each line with as much code as possible before moving to a new + // line with the same indentation. + // + // Expects doc.parts to be an array of alternating content and + // whitespace. The whitespace contains the linebreaks. + // + // For example: + // ["I", line, "love", line, "monkeys"] + // or + // [{ type: group, ... }, softline, { type: group, ... }] + // + // It uses this parts structure to handle three main layout cases: + // * The first two content items fit on the same line without + // breaking + // -> output the first content item and the whitespace "flat". + // * Only the first content item fits on the line without breaking + // -> output the first content item "flat" and the whitespace with + // "break". + // * Neither content item fits on the line without breaking + // -> output the first content item and the whitespace with "break". + + case "fill": + { + const rem = width - pos; + const { + parts + } = doc; + + if (parts.length === 0) { + break; + } + + const [content, whitespace] = parts; + const contentFlatCmd = [ind, MODE_FLAT, content]; + const contentBreakCmd = [ind, MODE_BREAK, content]; + const contentFits = fits(contentFlatCmd, [], rem, options, true); + + if (parts.length === 1) { + if (contentFits) { + cmds.push(contentFlatCmd); + } else { + cmds.push(contentBreakCmd); + } + + break; + } + + const whitespaceFlatCmd = [ind, MODE_FLAT, whitespace]; + const whitespaceBreakCmd = [ind, MODE_BREAK, whitespace]; + + if (parts.length === 2) { + if (contentFits) { + cmds.push(whitespaceFlatCmd); + cmds.push(contentFlatCmd); + } else { + cmds.push(whitespaceBreakCmd); + cmds.push(contentBreakCmd); + } + + break; + } // At this point we've handled the first pair (context, separator) + // and will create a new fill doc for the rest of the content. + // Ideally we wouldn't mutate the array here but copying all the + // elements to a new array would make this algorithm quadratic, + // which is unusable for large arrays (e.g. large texts in JSX). + + + parts.splice(0, 2); + const remainingCmd = [ind, mode, fill$1(parts)]; + const secondContent = parts[0]; + const firstAndSecondContentFlatCmd = [ind, MODE_FLAT, concat$1([content, whitespace, secondContent])]; + const firstAndSecondContentFits = fits(firstAndSecondContentFlatCmd, [], rem, options, true); + + if (firstAndSecondContentFits) { + cmds.push(remainingCmd); + cmds.push(whitespaceFlatCmd); + cmds.push(contentFlatCmd); + } else if (contentFits) { + cmds.push(remainingCmd); + cmds.push(whitespaceBreakCmd); + cmds.push(contentFlatCmd); + } else { + cmds.push(remainingCmd); + cmds.push(whitespaceBreakCmd); + cmds.push(contentBreakCmd); + } + + break; + } + + case "if-break": + { + const groupMode = doc.groupId ? groupModeMap[doc.groupId] : mode; + + if (groupMode === MODE_BREAK) { + if (doc.breakContents) { + cmds.push([ind, mode, doc.breakContents]); + } + } + + if (groupMode === MODE_FLAT) { + if (doc.flatContents) { + cmds.push([ind, mode, doc.flatContents]); + } + } + + break; + } + + case "line-suffix": + lineSuffix.push([ind, mode, doc.contents]); + break; + + case "line-suffix-boundary": + if (lineSuffix.length > 0) { + cmds.push([ind, mode, { + type: "line", + hard: true + }]); + } + + break; + + case "line": + switch (mode) { + case MODE_FLAT: + if (!doc.hard) { + if (!doc.soft) { + out.push(" "); + pos += 1; + } + + break; + } else { + // This line was forced into the output even if we + // were in flattened mode, so we need to tell the next + // group that no matter what, it needs to remeasure + // because the previous measurement didn't accurately + // capture the entire expression (this is necessary + // for nested groups) + shouldRemeasure = true; + } + + // fallthrough + + case MODE_BREAK: + if (lineSuffix.length) { + cmds.push([ind, mode, doc]); + cmds.push(...lineSuffix.reverse()); + lineSuffix = []; + break; + } + + if (doc.literal) { + if (ind.root) { + out.push(newLine, ind.root.value); + pos = ind.root.length; + } else { + out.push(newLine); + pos = 0; + } + } else { + pos -= trim$1(out); + out.push(newLine + ind.value); + pos = ind.length; + } + + break; + } + + break; + } + } + } + + const cursorPlaceholderIndex = out.indexOf(cursor$1.placeholder); + + if (cursorPlaceholderIndex !== -1) { + const otherCursorPlaceholderIndex = out.indexOf(cursor$1.placeholder, cursorPlaceholderIndex + 1); + const beforeCursor = out.slice(0, cursorPlaceholderIndex).join(""); + const aroundCursor = out.slice(cursorPlaceholderIndex + 1, otherCursorPlaceholderIndex).join(""); + const afterCursor = out.slice(otherCursorPlaceholderIndex + 1).join(""); + return { + formatted: beforeCursor + aroundCursor + afterCursor, + cursorNodeStart: beforeCursor.length, + cursorNodeText: aroundCursor + }; + } + + return { + formatted: out.join("") + }; +} + +var docPrinter = { + printDocToString +}; + +const { + literalline: literalline$1, + concat: concat$2 +} = docBuilders; // Using a unique object to compare by reference. + +const traverseDocOnExitStackMarker = {}; + +function traverseDoc(doc, onEnter, onExit, shouldTraverseConditionalGroups) { + const docsStack = [doc]; + + while (docsStack.length !== 0) { + const doc = docsStack.pop(); + + if (doc === traverseDocOnExitStackMarker) { + onExit(docsStack.pop()); + continue; + } + + if (onExit) { + docsStack.push(doc, traverseDocOnExitStackMarker); + } + + if ( // Should Recurse + !onEnter || onEnter(doc) !== false) { + // When there are multiple parts to process, + // the parts need to be pushed onto the stack in reverse order, + // so that they are processed in the original order + // when the stack is popped. + if (doc.type === "concat" || doc.type === "fill") { + for (let ic = doc.parts.length, i = ic - 1; i >= 0; --i) { + docsStack.push(doc.parts[i]); + } + } else if (doc.type === "if-break") { + if (doc.flatContents) { + docsStack.push(doc.flatContents); + } + + if (doc.breakContents) { + docsStack.push(doc.breakContents); + } + } else if (doc.type === "group" && doc.expandedStates) { + if (shouldTraverseConditionalGroups) { + for (let ic = doc.expandedStates.length, i = ic - 1; i >= 0; --i) { + docsStack.push(doc.expandedStates[i]); + } + } else { + docsStack.push(doc.contents); + } + } else if (doc.contents) { + docsStack.push(doc.contents); + } + } + } +} + +function mapDoc(doc, cb) { + if (doc.type === "concat" || doc.type === "fill") { + const parts = doc.parts.map(part => mapDoc(part, cb)); + return cb(Object.assign({}, doc, { + parts + })); + } else if (doc.type === "if-break") { + const breakContents = doc.breakContents && mapDoc(doc.breakContents, cb); + const flatContents = doc.flatContents && mapDoc(doc.flatContents, cb); + return cb(Object.assign({}, doc, { + breakContents, + flatContents + })); + } else if (doc.contents) { + const contents = mapDoc(doc.contents, cb); + return cb(Object.assign({}, doc, { + contents + })); + } + + return cb(doc); +} + +function findInDoc(doc, fn, defaultValue) { + let result = defaultValue; + let hasStopped = false; + + function findInDocOnEnterFn(doc) { + const maybeResult = fn(doc); + + if (maybeResult !== undefined) { + hasStopped = true; + result = maybeResult; + } + + if (hasStopped) { + return false; + } + } + + traverseDoc(doc, findInDocOnEnterFn); + return result; +} + +function isEmpty(n) { + return typeof n === "string" && n.length === 0; +} + +function isLineNextFn(doc) { + if (typeof doc === "string") { + return false; + } + + if (doc.type === "line") { + return true; + } +} + +function isLineNext(doc) { + return findInDoc(doc, isLineNextFn, false); +} + +function willBreakFn(doc) { + if (doc.type === "group" && doc.break) { + return true; + } + + if (doc.type === "line" && doc.hard) { + return true; + } + + if (doc.type === "break-parent") { + return true; + } +} + +function willBreak(doc) { + return findInDoc(doc, willBreakFn, false); +} + +function breakParentGroup(groupStack) { + if (groupStack.length > 0) { + const parentGroup = groupStack[groupStack.length - 1]; // Breaks are not propagated through conditional groups because + // the user is expected to manually handle what breaks. + + if (!parentGroup.expandedStates) { + parentGroup.break = true; + } + } + + return null; +} + +function propagateBreaks(doc) { + const alreadyVisitedSet = new Set(); + const groupStack = []; + + function propagateBreaksOnEnterFn(doc) { + if (doc.type === "break-parent") { + breakParentGroup(groupStack); + } + + if (doc.type === "group") { + groupStack.push(doc); + + if (alreadyVisitedSet.has(doc)) { + return false; + } + + alreadyVisitedSet.add(doc); + } + } + + function propagateBreaksOnExitFn(doc) { + if (doc.type === "group") { + const group = groupStack.pop(); + + if (group.break) { + breakParentGroup(groupStack); + } + } + } + + traverseDoc(doc, propagateBreaksOnEnterFn, propagateBreaksOnExitFn, + /* shouldTraverseConditionalGroups */ + true); +} + +function removeLinesFn(doc) { + // Force this doc into flat mode by statically converting all + // lines into spaces (or soft lines into nothing). Hard lines + // should still output because there's too great of a chance + // of breaking existing assumptions otherwise. + if (doc.type === "line" && !doc.hard) { + return doc.soft ? "" : " "; + } else if (doc.type === "if-break") { + return doc.flatContents || ""; + } + + return doc; +} + +function removeLines(doc) { + return mapDoc(doc, removeLinesFn); +} + +function getInnerParts(doc) { + let { + parts + } = doc; + let lastPart; // Avoid a falsy element like "" + + for (let i = doc.parts.length; i > 0 && !lastPart; i--) { + lastPart = parts[i - 1]; + } + + if (lastPart.type === "group") { + parts = lastPart.contents.parts; + } + + return parts; +} + +function stripTrailingHardline(doc, withInnerParts = false) { + // HACK remove ending hardline, original PR: #1984 + if (doc.type === "concat" && doc.parts.length !== 0) { + const parts = withInnerParts ? getInnerParts(doc) : doc.parts; + const lastPart = parts[parts.length - 1]; + + if (lastPart.type === "concat") { + if (lastPart.parts.length === 2 && lastPart.parts[0].hard && lastPart.parts[1].type === "break-parent") { + return { + type: "concat", + parts: parts.slice(0, -1) + }; + } + + return { + type: "concat", + parts: doc.parts.slice(0, -1).concat(stripTrailingHardline(lastPart)) + }; + } + } + + return doc; +} + +function normalizeParts(parts) { + const newParts = []; + const restParts = parts.filter(Boolean); + + while (restParts.length !== 0) { + const part = restParts.shift(); + + if (!part) { + continue; + } + + if (part.type === "concat") { + restParts.unshift(...part.parts); + continue; + } + + if (newParts.length !== 0 && typeof newParts[newParts.length - 1] === "string" && typeof part === "string") { + newParts[newParts.length - 1] += part; + continue; + } + + newParts.push(part); + } + + return newParts; +} + +function normalizeDoc(doc) { + return mapDoc(doc, currentDoc => { + if (!currentDoc.parts) { + return currentDoc; + } + + return Object.assign({}, currentDoc, { + parts: normalizeParts(currentDoc.parts) + }); + }); +} + +function replaceNewlinesWithLiterallines(doc) { + return mapDoc(doc, currentDoc => typeof currentDoc === "string" && currentDoc.includes("\n") ? concat$2(currentDoc.split(/(\n)/g).map((v, i) => i % 2 === 0 ? v : literalline$1)) : currentDoc); +} + +var docUtils = { + isEmpty, + willBreak, + isLineNext, + traverseDoc, + findInDoc, + mapDoc, + propagateBreaks, + removeLines, + stripTrailingHardline, + normalizeParts, + normalizeDoc, + replaceNewlinesWithLiterallines +}; + +function flattenDoc(doc) { + if (doc.type === "concat") { + const res = []; + + for (let i = 0; i < doc.parts.length; ++i) { + const doc2 = doc.parts[i]; + + if (typeof doc2 !== "string" && doc2.type === "concat") { + res.push(...flattenDoc(doc2).parts); + } else { + const flattened = flattenDoc(doc2); + + if (flattened !== "") { + res.push(flattened); + } + } + } + + return Object.assign({}, doc, { + parts: res + }); + } else if (doc.type === "if-break") { + return Object.assign({}, doc, { + breakContents: doc.breakContents != null ? flattenDoc(doc.breakContents) : null, + flatContents: doc.flatContents != null ? flattenDoc(doc.flatContents) : null + }); + } else if (doc.type === "group") { + return Object.assign({}, doc, { + contents: flattenDoc(doc.contents), + expandedStates: doc.expandedStates ? doc.expandedStates.map(flattenDoc) : doc.expandedStates + }); + } else if (doc.contents) { + return Object.assign({}, doc, { + contents: flattenDoc(doc.contents) + }); + } + + return doc; +} + +function printDoc(doc) { + if (typeof doc === "string") { + return JSON.stringify(doc); + } + + if (doc.type === "line") { + if (doc.literal) { + return "literalline"; + } + + if (doc.hard) { + return "hardline"; + } + + if (doc.soft) { + return "softline"; + } + + return "line"; + } + + if (doc.type === "break-parent") { + return "breakParent"; + } + + if (doc.type === "trim") { + return "trim"; + } + + if (doc.type === "concat") { + return "[" + doc.parts.map(printDoc).join(", ") + "]"; + } + + if (doc.type === "indent") { + return "indent(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "align") { + return doc.n === -Infinity ? "dedentToRoot(" + printDoc(doc.contents) + ")" : doc.n < 0 ? "dedent(" + printDoc(doc.contents) + ")" : doc.n.type === "root" ? "markAsRoot(" + printDoc(doc.contents) + ")" : "align(" + JSON.stringify(doc.n) + ", " + printDoc(doc.contents) + ")"; + } + + if (doc.type === "if-break") { + return "ifBreak(" + printDoc(doc.breakContents) + (doc.flatContents ? ", " + printDoc(doc.flatContents) : "") + ")"; + } + + if (doc.type === "group") { + if (doc.expandedStates) { + return "conditionalGroup(" + "[" + doc.expandedStates.map(printDoc).join(",") + "])"; + } + + return (doc.break ? "wrappedGroup" : "group") + "(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "fill") { + return "fill" + "(" + doc.parts.map(printDoc).join(", ") + ")"; + } + + if (doc.type === "line-suffix") { + return "lineSuffix(" + printDoc(doc.contents) + ")"; + } + + if (doc.type === "line-suffix-boundary") { + return "lineSuffixBoundary"; + } + + throw new Error("Unknown doc type " + doc.type); +} + +var docDebug = { + printDocToDebug(doc) { + return printDoc(flattenDoc(doc)); + } + +}; + +/** + * @typedef {import("./doc-builders").Doc} Doc + */ + + +var document = { + builders: docBuilders, + printer: docPrinter, + utils: docUtils, + debug: docDebug +}; + +/** + * @class + */ + + +class LineByLine { + constructor(file, options) { + options = options || {}; + if (!options.readChunk) options.readChunk = 1024; + + if (!options.newLineCharacter) { + options.newLineCharacter = 0x0a; //linux line ending + } else { + options.newLineCharacter = options.newLineCharacter.charCodeAt(0); + } + + if (typeof file === 'number') { + this.fd = file; + } else { + this.fd = fs__default['default'].openSync(file, 'r'); + } + + this.options = options; + this.newLineCharacter = options.newLineCharacter; + this.reset(); + } + + _searchInBuffer(buffer, hexNeedle) { + let found = -1; + + for (let i = 0; i <= buffer.length; i++) { + let b_byte = buffer[i]; + + if (b_byte === hexNeedle) { + found = i; + break; + } + } + + return found; + } + + reset() { + this.eofReached = false; + this.linesCache = []; + this.fdPosition = 0; + } + + close() { + fs__default['default'].closeSync(this.fd); + this.fd = null; + } + + _extractLines(buffer) { + let line; + const lines = []; + let bufferPosition = 0; + let lastNewLineBufferPosition = 0; + + while (true) { + let bufferPositionValue = buffer[bufferPosition++]; + + if (bufferPositionValue === this.newLineCharacter) { + line = buffer.slice(lastNewLineBufferPosition, bufferPosition); + lines.push(line); + lastNewLineBufferPosition = bufferPosition; + } else if (!bufferPositionValue) { + break; + } + } + + let leftovers = buffer.slice(lastNewLineBufferPosition, bufferPosition); + + if (leftovers.length) { + lines.push(leftovers); + } + + return lines; + } + + _readChunk(lineLeftovers) { + let totalBytesRead = 0; + let bytesRead; + const buffers = []; + + do { + const readBuffer = new Buffer(this.options.readChunk); + bytesRead = fs__default['default'].readSync(this.fd, readBuffer, 0, this.options.readChunk, this.fdPosition); + totalBytesRead = totalBytesRead + bytesRead; + this.fdPosition = this.fdPosition + bytesRead; + buffers.push(readBuffer); + } while (bytesRead && this._searchInBuffer(buffers[buffers.length - 1], this.options.newLineCharacter) === -1); + + let bufferData = Buffer.concat(buffers); + + if (bytesRead < this.options.readChunk) { + this.eofReached = true; + bufferData = bufferData.slice(0, totalBytesRead); + } + + if (totalBytesRead) { + this.linesCache = this._extractLines(bufferData); + + if (lineLeftovers) { + this.linesCache[0] = Buffer.concat([lineLeftovers, this.linesCache[0]]); + } + } + + return totalBytesRead; + } + + next() { + if (!this.fd) return false; + let line = false; + + if (this.eofReached && this.linesCache.length === 0) { + return line; + } + + let bytesRead; + + if (!this.linesCache.length) { + bytesRead = this._readChunk(); + } + + if (this.linesCache.length) { + line = this.linesCache.shift(); + const lastLineCharacter = line[line.length - 1]; + + if (lastLineCharacter !== 0x0a) { + bytesRead = this._readChunk(line); + + if (bytesRead) { + line = this.linesCache.shift(); + } + } + } + + if (this.eofReached && this.linesCache.length === 0) { + this.close(); + } + + if (line && line[line.length - 1] === this.newLineCharacter) { + line = line.slice(0, line.length - 1); + } + + return line; + } + +} + +var readlines = LineByLine; + +/** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ +function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + + return result; +} + +var fromPairs_1 = fromPairs; + +class ConfigError extends Error {} + +class DebugError extends Error {} + +class UndefinedParserError extends Error {} + +var errors = { + ConfigError, + DebugError, + UndefinedParserError +}; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +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. +***************************************************************************** */ + +/* global Reflect, Promise */ +var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function (d, b) { + d.__proto__ = b; + } || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + }; + + return extendStatics(d, b); +}; + +function __extends(d, b) { + extendStatics(d, b); + + function __() { + this.constructor = d; + } + + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} +var __assign = function () { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + + return t; + }; + + return __assign.apply(this, arguments); +}; +function __rest(s, e) { + var t = {}; + + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; +} +function __decorate(decorators, target, key, desc) { + var c = arguments.length, + r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, + d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} +function __param(paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); + }; +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} +function __awaiter(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()); + }); +} +function __generator(thisArg, body) { + var _ = { + label: 0, + sent: function () { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, + f, + y, + t, + g; + return g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + + switch (op[0]) { + case 0: + case 1: + t = op; + break; + + case 4: + _.label++; + return { + value: op[1], + done: false + }; + + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + + case 7: + op = _.ops.pop(); + + _.trys.pop(); + + continue; + + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + + if (t && _.label < t[2]) { + _.label = t[2]; + + _.ops.push(op); + + break; + } + + if (t[2]) _.ops.pop(); + + _.trys.pop(); + + continue; + } + + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } +} +function __createBinding(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +} +function __exportStar(m, exports) { + for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; +} +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { + value: o && o[i++], + done: !o + }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), + r, + ar = [], + e; + + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error) { + e = { + error: error + }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + + return ar; +} +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + + return ar; +} +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + + for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) r[k] = a[j]; + + return r; +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i; + + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + + function fulfill(value) { + resume("next", value); + } + + function reject(value) { + resume("throw", value); + } + + function settle(f, v) { + if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); + } +} +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function () { + return this; + }, i; + + function verb(n, f) { + i[n] = o[n] ? function (v) { + return (p = !p) ? { + value: __await(o[n](v)), + done: n === "return" + } : f ? f(v) : v; + } : f; + } +} +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + + function verb(n) { + i[n] = o[n] && function (v) { + return new Promise(function (resolve, reject) { + v = o[n](v), settle(resolve, reject, v.done, v.value); + }); + }; + } + + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } +} +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw + }); + } else { + cooked.raw = raw; + } + + return cooked; +} +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result.default = mod; + return result; +} +function __importDefault(mod) { + return mod && mod.__esModule ? mod : { + default: mod + }; +} +function __classPrivateFieldGet(receiver, privateMap) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to get private field on non-instance"); + } + + return privateMap.get(receiver); +} +function __classPrivateFieldSet(receiver, privateMap, value) { + if (!privateMap.has(receiver)) { + throw new TypeError("attempted to set private field on non-instance"); + } + + privateMap.set(receiver, value); + return value; +} + +var tslib_es6 = /*#__PURE__*/Object.freeze({ + __proto__: null, + __extends: __extends, + get __assign () { return __assign; }, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __createBinding: __createBinding, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet +}); + +var api = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.apiDescriptor = { + key: key => /^[$_a-zA-Z][$_a-zA-Z0-9]*$/.test(key) ? key : JSON.stringify(key), + + value(value) { + if (value === null || typeof value !== 'object') { + return JSON.stringify(value); + } + + if (Array.isArray(value)) { + return `[${value.map(subValue => exports.apiDescriptor.value(subValue)).join(', ')}]`; + } + + const keys = Object.keys(value); + return keys.length === 0 ? '{}' : `{ ${keys.map(key => `${exports.apiDescriptor.key(key)}: ${exports.apiDescriptor.value(value[key])}`).join(', ')} }`; + }, + + pair: ({ + key, + value + }) => exports.apiDescriptor.value({ + [key]: value + }) + }; +}); + +var descriptors = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_es6.__exportStar(api, exports); +}); + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +var escapeStringRegexp$1 = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +var colorName = { + "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] +}; + +var conversions = createCommonjsModule(function (module) { + /* MIT license */ + // 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.) + var reverseKeywords = {}; + + for (var key in colorName) { + if (colorName.hasOwnProperty(key)) { + reverseKeywords[colorName[key]] = key; + } + } + + var convert = module.exports = { + 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'] + } + }; // hide .channels and .labels properties + + for (var model in convert) { + if (convert.hasOwnProperty(model)) { + 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); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + 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) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + 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; + } + + 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) { + var rdif; + var gdif; + var bdif; + var h; + var s; + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 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) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var 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) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; + }; + /** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ + + + function comparativeDistance(x, y) { + return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); + } + + convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in colorName) { + if (colorName.hasOwnProperty(keyword)) { + var value = colorName[keyword]; // Compute comparative distance + + var 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 colorName[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; // assume sRGB + + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + var x = r * 0.4124 + g * 0.3576 + b * 0.1805; + var y = r * 0.2126 + g * 0.7152 + b * 0.0722; + var z = r * 0.0193 + g * 0.1192 + b * 0.9505; + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var 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; + } + + t1 = 2 * l - t2; + rgb = [0, 0, 0]; + + for (var 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) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - s * f); + var 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) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + l = (2 - s) * v; + 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) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; // wh + bl cant be > 1 + + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + + 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; + } + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var 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 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; + g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; + b = b > 0.0031308 ? 1.055 * Math.pow(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) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(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) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var 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) { + var r = args[0]; + var g = args[1]; + var 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; + } + + var 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) { + var 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]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = (color & 1) * mult * 255; + var g = (color >> 1 & 1) * mult * 255; + var b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = rem % 6 / 5 * 255; + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = integer >> 16 & 0xFF; + var g = integer >> 8 & 0xFF; + var b = integer & 0xFF; + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = max - min; + var grayscale; + var 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 + 4; + } + + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = h % 1 * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + 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; + } + + 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) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var l = g * (1.0 - c) + 0.5 * c; + var 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) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var 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 = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; + }; + + 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) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; +}); + +/* + 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() { + var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + + var models = Object.keys(conversions); + + for (var 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) { + var graph = buildGraph(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var 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) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions[graph[toModel].parent][toModel]; + var 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; +} + +var route = function (fromModel) { + var graph = deriveBFS(fromModel); + var conversion = {}; + var models = Object.keys(graph); + + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var 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; +}; + +var convert = {}; +var models = Object.keys(conversions); + +function wrapRaw(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; // preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var 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 (var 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(function (fromModel) { + convert[fromModel] = {}; + Object.defineProperty(convert[fromModel], 'channels', { + value: conversions[fromModel].channels + }); + Object.defineProperty(convert[fromModel], 'labels', { + value: conversions[fromModel].labels + }); + var routes = route(fromModel); + var routeModels = Object.keys(routes); + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + convert[fromModel][toModel] = wrapRounded(fn); + convert[fromModel][toModel].raw = wrapRaw(fn); + }); +}); +var colorConvert = convert; + +var ansiStyles = createCommonjsModule(function (module) { + + const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + 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], + gray: [90, 39], + // Bright color + 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] + } + }; // Fix humans + + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + 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 + }); + } + + const ansi2ansi = n => n; + + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert)) { + if (typeof colorConvert[key] !== 'object') { + continue; + } + + const suite = colorConvert[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } // Make the export immutable + + + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); +}); + +var hasFlag = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; + +const env = process.env; +let forceColor; + +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { + forceColor = true; +} + +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 || parseInt(env.FORCE_COLOR, 10) !== 0; +} + +function translateLevel(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } + + const min = forceColor ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os__default['default'].release().split('.'); + + if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env) || env.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env) { + const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } + + if ('COLORTERM' in env) { + return 1; + } + + if (env.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel(stream) { + const level = supportsColor(stream); + return translateLevel(level); +} + +var supportsColor_1 = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr) +}; + +const TEMPLATE_REGEX = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; +const ESCAPES = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); + +function unescape(c) { + if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES.get(c) || c; +} + +function parseArguments(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if (matches = chunk.match(STRING_REGEX)) { + results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, chr) => escape ? unescape(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle(style) { + STYLE_REGEX.lastIndex = 0; + const results = []; + let matches; + + while ((matches = STYLE_REGEX.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; +} + +var templates = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; // eslint-disable-next-line max-params + + tmp.replace(TEMPLATE_REGEX, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle(chalk, styles)(str)); + styles.push({ + inverse, + styles: parseStyle(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + + return chunks.join(''); +}; + +var chalk = createCommonjsModule(function (module) { + + const stdoutColor = supportsColor_1.stdout; + const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping + + const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such + + const skipModels = new Set(['gray']); + const styles = Object.create(null); + + function applyOptions(obj, options) { + options = options || {}; // Detect level if not set manually + + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + } + + function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + chalk.template.constructor = Chalk; + return chalk.template; + } + + applyOptions(this, options); + } // Use bright blue on Windows as the normal blue color is illegible + + + if (isSimpleWindowsTerm) { + ansiStyles.blue.open = '\u001B[94m'; + } + + for (const key of Object.keys(ansiStyles)) { + ansiStyles[key].closeRe = new RegExp(escapeStringRegexp$1(ansiStyles[key].close), 'g'); + styles[key] = { + get() { + const codes = ansiStyles[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + + }; + } + + styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } + + }; + ansiStyles.color.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles.color.close), 'g'); + + for (const model of Object.keys(ansiStyles.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.color.close, + closeRe: ansiStyles.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + + }; + } + + ansiStyles.bgColor.closeRe = new RegExp(escapeStringRegexp$1(ansiStyles.bgColor.close), 'g'); + + for (const model of Object.keys(ansiStyles.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles.bgColor.close, + closeRe: ansiStyles.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + + }; + } + + const proto = Object.defineProperties(() => {}, styles); + + function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + const self = this; + Object.defineProperty(builder, 'level', { + enumerable: true, + + get() { + return self.level; + }, + + set(level) { + self.level = level; + } + + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + + get() { + return self.enabled; + }, + + set(enabled) { + self.enabled = enabled; + } + + }); // See below for fix regarding invisible grey/dim combination on Windows + + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; + } + + function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + + + const originalDim = ansiStyles.dim.open; + + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + + + ansiStyles.dim.open = originalDim; + return str; + } + + function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates(chalk, parts.join('')); + } + + Object.defineProperties(Chalk.prototype, styles); + module.exports = Chalk(); // eslint-disable-line new-cap + + module.exports.supportsColor = stdoutColor; + module.exports.default = module.exports; // For TypeScript +}); + +var common = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.commonDeprecatedHandler = (keyOrPair, redirectTo, { + descriptor + }) => { + const messages = [`${chalk.default.yellow(typeof keyOrPair === 'string' ? descriptor.key(keyOrPair) : descriptor.pair(keyOrPair))} is deprecated`]; + + if (redirectTo) { + messages.push(`we now treat it as ${chalk.default.blue(typeof redirectTo === 'string' ? descriptor.key(redirectTo) : descriptor.pair(redirectTo))}`); + } + + return messages.join('; ') + '.'; + }; +}); + +var deprecated = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_es6.__exportStar(common, exports); +}); + +var common$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.commonInvalidHandler = (key, value, utils) => [`Invalid ${chalk.default.red(utils.descriptor.key(key))} value.`, `Expected ${chalk.default.blue(utils.schemas[key].expected(utils))},`, `but received ${chalk.default.red(utils.descriptor.value(value))}.`].join(' '); +}); + +var invalid = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_es6.__exportStar(common$1, exports); +}); + +/* eslint-disable no-nested-ternary */ + +var arr = []; +var charCodeCache = []; + +var leven = function (a, b) { + if (a === b) { + return 0; + } + + var swap = a; // Swapping the strings if `a` is longer than `b` so we know which one is the + // shortest & which one is the longest + + if (a.length > b.length) { + a = b; + b = swap; + } + + var aLen = a.length; + var bLen = b.length; + + if (aLen === 0) { + return bLen; + } + + if (bLen === 0) { + return aLen; + } // Performing suffix trimming: + // We can linearly drop suffix common to both strings since they + // don't increase distance at all + // Note: `~-` is the bitwise way to perform a `- 1` operation + + + while (aLen > 0 && a.charCodeAt(~-aLen) === b.charCodeAt(~-bLen)) { + aLen--; + bLen--; + } + + if (aLen === 0) { + return bLen; + } // Performing prefix trimming + // We can linearly drop prefix common to both strings since they + // don't increase distance at all + + + var start = 0; + + while (start < aLen && a.charCodeAt(start) === b.charCodeAt(start)) { + start++; + } + + aLen -= start; + bLen -= start; + + if (aLen === 0) { + return bLen; + } + + var bCharCode; + var ret; + var tmp; + var tmp2; + var i = 0; + var j = 0; + + while (i < aLen) { + charCodeCache[start + i] = a.charCodeAt(start + i); + arr[i] = ++i; + } + + while (j < bLen) { + bCharCode = b.charCodeAt(start + j); + tmp = j++; + ret = j; + + for (i = 0; i < aLen; i++) { + tmp2 = bCharCode === charCodeCache[start + i] ? tmp : tmp + 1; + tmp = arr[i]; + ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2; + } + } + + return ret; +}; + +var leven_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.levenUnknownHandler = (key, value, { + descriptor, + logger, + schemas + }) => { + const messages = [`Ignored unknown option ${chalk.default.yellow(descriptor.pair({ + key, + value + }))}.`]; + const suggestion = Object.keys(schemas).sort().find(knownKey => leven(key, knownKey) < 3); + + if (suggestion) { + messages.push(`Did you mean ${chalk.default.blue(descriptor.key(suggestion))}?`); + } + + logger.warn(messages.join(' ')); + }; +}); + +var unknown = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_es6.__exportStar(leven_1, exports); +}); + +var handlers = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_es6.__exportStar(deprecated, exports); + + tslib_es6.__exportStar(invalid, exports); + + tslib_es6.__exportStar(unknown, exports); +}); + +var schema = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + const HANDLER_KEYS = ['default', 'expected', 'validate', 'deprecated', 'forward', 'redirect', 'overlap', 'preprocess', 'postprocess']; + + function createSchema(SchemaConstructor, parameters) { + const schema = new SchemaConstructor(parameters); + const subSchema = Object.create(schema); + + for (const handlerKey of HANDLER_KEYS) { + if (handlerKey in parameters) { + subSchema[handlerKey] = normalizeHandler(parameters[handlerKey], schema, Schema.prototype[handlerKey].length); + } + } + + return subSchema; + } + + exports.createSchema = createSchema; + + class Schema { + constructor(parameters) { + this.name = parameters.name; + } + + static create(parameters) { + // @ts-ignore: https://github.com/Microsoft/TypeScript/issues/5863 + return createSchema(this, parameters); + } + + default(_utils) { + return undefined; + } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` + + + expected(_utils) { + return 'nothing'; + } // istanbul ignore next: this is actually an abstract method but we need a placeholder to get `function.length` + + + validate(_value, _utils) { + return false; + } + + deprecated(_value, _utils) { + return false; + } + + forward(_value, _utils) { + return undefined; + } + + redirect(_value, _utils) { + return undefined; + } + + overlap(currentValue, _newValue, _utils) { + return currentValue; + } + + preprocess(value, _utils) { + return value; + } + + postprocess(value, _utils) { + return value; + } + + } + + exports.Schema = Schema; + + function normalizeHandler(handler, superSchema, handlerArgumentsLength) { + return typeof handler === 'function' ? (...args) => handler(...args.slice(0, handlerArgumentsLength - 1), superSchema, ...args.slice(handlerArgumentsLength - 1)) : () => handler; + } +}); + +var alias = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class AliasSchema extends schema.Schema { + constructor(parameters) { + super(parameters); + this._sourceName = parameters.sourceName; + } + + expected(utils) { + return utils.schemas[this._sourceName].expected(utils); + } + + validate(value, utils) { + return utils.schemas[this._sourceName].validate(value, utils); + } + + redirect(_value, _utils) { + return this._sourceName; + } + + } + + exports.AliasSchema = AliasSchema; +}); + +var any = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class AnySchema extends schema.Schema { + expected() { + return 'anything'; + } + + validate() { + return true; + } + + } + + exports.AnySchema = AnySchema; +}); + +var array = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ArraySchema extends schema.Schema { + constructor(_a) { + var { + valueSchema, + name = valueSchema.name + } = _a, + handlers = tslib_es6.__rest(_a, ["valueSchema", "name"]); + + super(Object.assign({}, handlers, { + name + })); + this._valueSchema = valueSchema; + } + + expected(utils) { + return `an array of ${this._valueSchema.expected(utils)}`; + } + + validate(value, utils) { + if (!Array.isArray(value)) { + return false; + } + + const invalidValues = []; + + for (const subValue of value) { + const subValidateResult = utils.normalizeValidateResult(this._valueSchema.validate(subValue, utils), subValue); + + if (subValidateResult !== true) { + invalidValues.push(subValidateResult.value); + } + } + + return invalidValues.length === 0 ? true : { + value: invalidValues + }; + } + + deprecated(value, utils) { + const deprecatedResult = []; + + for (const subValue of value) { + const subDeprecatedResult = utils.normalizeDeprecatedResult(this._valueSchema.deprecated(subValue, utils), subValue); + + if (subDeprecatedResult !== false) { + deprecatedResult.push(...subDeprecatedResult.map(({ + value: deprecatedValue + }) => ({ + value: [deprecatedValue] + }))); + } + } + + return deprecatedResult; + } + + forward(value, utils) { + const forwardResult = []; + + for (const subValue of value) { + const subForwardResult = utils.normalizeForwardResult(this._valueSchema.forward(subValue, utils), subValue); + forwardResult.push(...subForwardResult.map(wrapTransferResult)); + } + + return forwardResult; + } + + redirect(value, utils) { + const remain = []; + const redirect = []; + + for (const subValue of value) { + const subRedirectResult = utils.normalizeRedirectResult(this._valueSchema.redirect(subValue, utils), subValue); + + if ('remain' in subRedirectResult) { + remain.push(subRedirectResult.remain); + } + + redirect.push(...subRedirectResult.redirect.map(wrapTransferResult)); + } + + return remain.length === 0 ? { + redirect + } : { + redirect, + remain + }; + } + + overlap(currentValue, newValue) { + return currentValue.concat(newValue); + } + + } + + exports.ArraySchema = ArraySchema; + + function wrapTransferResult({ + from, + to + }) { + return { + from: [from], + to + }; + } +}); + +var boolean_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class BooleanSchema extends schema.Schema { + expected() { + return 'true or false'; + } + + validate(value) { + return typeof value === 'boolean'; + } + + } + + exports.BooleanSchema = BooleanSchema; +}); + +var utils = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function recordFromArray(array, mainKey) { + const record = Object.create(null); + + for (const value of array) { + const key = value[mainKey]; // istanbul ignore next + + if (record[key]) { + throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`); + } // @ts-ignore + + + record[key] = value; + } + + return record; + } + + exports.recordFromArray = recordFromArray; + + function mapFromArray(array, mainKey) { + const map = new Map(); + + for (const value of array) { + const key = value[mainKey]; // istanbul ignore next + + if (map.has(key)) { + throw new Error(`Duplicate ${mainKey} ${JSON.stringify(key)}`); + } + + map.set(key, value); + } + + return map; + } + + exports.mapFromArray = mapFromArray; + + function createAutoChecklist() { + const map = Object.create(null); + return id => { + const idString = JSON.stringify(id); + + if (map[idString]) { + return true; + } + + map[idString] = true; + return false; + }; + } + + exports.createAutoChecklist = createAutoChecklist; + + function partition(array, predicate) { + const trueArray = []; + const falseArray = []; + + for (const value of array) { + if (predicate(value)) { + trueArray.push(value); + } else { + falseArray.push(value); + } + } + + return [trueArray, falseArray]; + } + + exports.partition = partition; + + function isInt(value) { + return value === Math.floor(value); + } + + exports.isInt = isInt; + + function comparePrimitive(a, b) { + if (a === b) { + return 0; + } + + const typeofA = typeof a; + const typeofB = typeof b; + const orders = ['undefined', 'object', 'boolean', 'number', 'string']; + + if (typeofA !== typeofB) { + return orders.indexOf(typeofA) - orders.indexOf(typeofB); + } + + if (typeofA !== 'string') { + return Number(a) - Number(b); + } + + return a.localeCompare(b); + } + + exports.comparePrimitive = comparePrimitive; + + function normalizeDefaultResult(result) { + return result === undefined ? {} : result; + } + + exports.normalizeDefaultResult = normalizeDefaultResult; + + function normalizeValidateResult(result, value) { + return result === true ? true : result === false ? { + value + } : result; + } + + exports.normalizeValidateResult = normalizeValidateResult; + + function normalizeDeprecatedResult(result, value, doNotNormalizeTrue = false) { + return result === false ? false : result === true ? doNotNormalizeTrue ? true : [{ + value + }] : 'value' in result ? [result] : result.length === 0 ? false : result; + } + + exports.normalizeDeprecatedResult = normalizeDeprecatedResult; + + function normalizeTransferResult(result, value) { + return typeof result === 'string' || 'key' in result ? { + from: value, + to: result + } : 'from' in result ? { + from: result.from, + to: result.to + } : { + from: value, + to: result.to + }; + } + + exports.normalizeTransferResult = normalizeTransferResult; + + function normalizeForwardResult(result, value) { + return result === undefined ? [] : Array.isArray(result) ? result.map(transferResult => normalizeTransferResult(transferResult, value)) : [normalizeTransferResult(result, value)]; + } + + exports.normalizeForwardResult = normalizeForwardResult; + + function normalizeRedirectResult(result, value) { + const redirect = normalizeForwardResult(typeof result === 'object' && 'redirect' in result ? result.redirect : result, value); + return redirect.length === 0 ? { + remain: value, + redirect + } : typeof result === 'object' && 'remain' in result ? { + remain: result.remain, + redirect + } : { + redirect + }; + } + + exports.normalizeRedirectResult = normalizeRedirectResult; +}); + +var choice = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ChoiceSchema extends schema.Schema { + constructor(parameters) { + super(parameters); + this._choices = utils.mapFromArray(parameters.choices.map(choice => choice && typeof choice === 'object' ? choice : { + value: choice + }), 'value'); + } + + expected({ + descriptor + }) { + const choiceValues = Array.from(this._choices.keys()).map(value => this._choices.get(value)).filter(choiceInfo => !choiceInfo.deprecated).map(choiceInfo => choiceInfo.value).sort(utils.comparePrimitive).map(descriptor.value); + const head = choiceValues.slice(0, -2); + const tail = choiceValues.slice(-2); + return head.concat(tail.join(' or ')).join(', '); + } + + validate(value) { + return this._choices.has(value); + } + + deprecated(value) { + const choiceInfo = this._choices.get(value); + + return choiceInfo && choiceInfo.deprecated ? { + value + } : false; + } + + forward(value) { + const choiceInfo = this._choices.get(value); + + return choiceInfo ? choiceInfo.forward : undefined; + } + + redirect(value) { + const choiceInfo = this._choices.get(value); + + return choiceInfo ? choiceInfo.redirect : undefined; + } + + } + + exports.ChoiceSchema = ChoiceSchema; +}); + +var number = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class NumberSchema extends schema.Schema { + expected() { + return 'a number'; + } + + validate(value, _utils) { + return typeof value === 'number'; + } + + } + + exports.NumberSchema = NumberSchema; +}); + +var integer = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class IntegerSchema extends number.NumberSchema { + expected() { + return 'an integer'; + } + + validate(value, utils$1) { + return utils$1.normalizeValidateResult(super.validate(value, utils$1), value) === true && utils.isInt(value); + } + + } + + exports.IntegerSchema = IntegerSchema; +}); + +var string = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class StringSchema extends schema.Schema { + expected() { + return 'a string'; + } + + validate(value) { + return typeof value === 'string'; + } + + } + + exports.StringSchema = StringSchema; +}); + +var schemas = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_es6.__exportStar(alias, exports); + + tslib_es6.__exportStar(any, exports); + + tslib_es6.__exportStar(array, exports); + + tslib_es6.__exportStar(boolean_1, exports); + + tslib_es6.__exportStar(choice, exports); + + tslib_es6.__exportStar(integer, exports); + + tslib_es6.__exportStar(number, exports); + + tslib_es6.__exportStar(string, exports); +}); + +var defaults = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.defaultDescriptor = api.apiDescriptor; + exports.defaultUnknownHandler = leven_1.levenUnknownHandler; + exports.defaultInvalidHandler = invalid.commonInvalidHandler; + exports.defaultDeprecatedHandler = common.commonDeprecatedHandler; +}); + +var normalize = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + exports.normalize = (options, schemas, opts) => new Normalizer(schemas, opts).normalize(options); + + class Normalizer { + constructor(schemas, opts) { + // istanbul ignore next + const { + logger = console, + descriptor = defaults.defaultDescriptor, + unknown = defaults.defaultUnknownHandler, + invalid = defaults.defaultInvalidHandler, + deprecated = defaults.defaultDeprecatedHandler + } = opts || {}; + this._utils = { + descriptor, + logger: + /* istanbul ignore next */ + logger || { + warn: () => {} + }, + schemas: utils.recordFromArray(schemas, 'name'), + normalizeDefaultResult: utils.normalizeDefaultResult, + normalizeDeprecatedResult: utils.normalizeDeprecatedResult, + normalizeForwardResult: utils.normalizeForwardResult, + normalizeRedirectResult: utils.normalizeRedirectResult, + normalizeValidateResult: utils.normalizeValidateResult + }; + this._unknownHandler = unknown; + this._invalidHandler = invalid; + this._deprecatedHandler = deprecated; + this.cleanHistory(); + } + + cleanHistory() { + this._hasDeprecationWarned = utils.createAutoChecklist(); + } + + normalize(options) { + const normalized = {}; + const restOptionsArray = [options]; + + const applyNormalization = () => { + while (restOptionsArray.length !== 0) { + const currentOptions = restOptionsArray.shift(); + + const transferredOptionsArray = this._applyNormalization(currentOptions, normalized); + + restOptionsArray.push(...transferredOptionsArray); + } + }; + + applyNormalization(); + + for (const key of Object.keys(this._utils.schemas)) { + const schema = this._utils.schemas[key]; + + if (!(key in normalized)) { + const defaultResult = utils.normalizeDefaultResult(schema.default(this._utils)); + + if ('value' in defaultResult) { + restOptionsArray.push({ + [key]: defaultResult.value + }); + } + } + } + + applyNormalization(); + + for (const key of Object.keys(this._utils.schemas)) { + const schema = this._utils.schemas[key]; + + if (key in normalized) { + normalized[key] = schema.postprocess(normalized[key], this._utils); + } + } + + return normalized; + } + + _applyNormalization(options, normalized) { + const transferredOptionsArray = []; + const [knownOptionNames, unknownOptionNames] = utils.partition(Object.keys(options), key => key in this._utils.schemas); + + for (const key of knownOptionNames) { + const schema = this._utils.schemas[key]; + const value = schema.preprocess(options[key], this._utils); + const validateResult = utils.normalizeValidateResult(schema.validate(value, this._utils), value); + + if (validateResult !== true) { + const { + value: invalidValue + } = validateResult; + + const errorMessageOrError = this._invalidHandler(key, invalidValue, this._utils); + + throw typeof errorMessageOrError === 'string' ? new Error(errorMessageOrError) : + /* istanbul ignore next*/ + errorMessageOrError; + } + + const appendTransferredOptions = ({ + from, + to + }) => { + transferredOptionsArray.push(typeof to === 'string' ? { + [to]: from + } : { + [to.key]: to.value + }); + }; + + const warnDeprecated = ({ + value: currentValue, + redirectTo + }) => { + const deprecatedResult = utils.normalizeDeprecatedResult(schema.deprecated(currentValue, this._utils), value, + /* doNotNormalizeTrue */ + true); + + if (deprecatedResult === false) { + return; + } + + if (deprecatedResult === true) { + if (!this._hasDeprecationWarned(key)) { + this._utils.logger.warn(this._deprecatedHandler(key, redirectTo, this._utils)); + } + } else { + for (const { + value: deprecatedValue + } of deprecatedResult) { + const pair = { + key, + value: deprecatedValue + }; + + if (!this._hasDeprecationWarned(pair)) { + const redirectToPair = typeof redirectTo === 'string' ? { + key: redirectTo, + value: deprecatedValue + } : redirectTo; + + this._utils.logger.warn(this._deprecatedHandler(pair, redirectToPair, this._utils)); + } + } + } + }; + + const forwardResult = utils.normalizeForwardResult(schema.forward(value, this._utils), value); + forwardResult.forEach(appendTransferredOptions); + const redirectResult = utils.normalizeRedirectResult(schema.redirect(value, this._utils), value); + redirectResult.redirect.forEach(appendTransferredOptions); + + if ('remain' in redirectResult) { + const remainingValue = redirectResult.remain; + normalized[key] = key in normalized ? schema.overlap(normalized[key], remainingValue, this._utils) : remainingValue; + warnDeprecated({ + value: remainingValue + }); + } + + for (const { + from, + to + } of redirectResult.redirect) { + warnDeprecated({ + value: from, + redirectTo: to + }); + } + } + + for (const key of unknownOptionNames) { + const value = options[key]; + + const unknownResult = this._unknownHandler(key, value, this._utils); + + if (unknownResult) { + for (const unknownKey of Object.keys(unknownResult)) { + const unknownOption = { + [unknownKey]: unknownResult[unknownKey] + }; + + if (unknownKey in this._utils.schemas) { + transferredOptionsArray.push(unknownOption); + } else { + Object.assign(normalized, unknownOption); + } + } + } + } + + return transferredOptionsArray; + } + + } + + exports.Normalizer = Normalizer; +}); + +var lib$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + tslib_es6.__exportStar(descriptors, exports); + + tslib_es6.__exportStar(handlers, exports); + + tslib_es6.__exportStar(schemas, exports); + + tslib_es6.__exportStar(normalize, exports); + + tslib_es6.__exportStar(schema, exports); +}); + +const array$1 = []; +const charCodeCache$1 = []; + +const leven$1 = (left, right) => { + if (left === right) { + return 0; + } + + const swap = left; // Swapping the strings if `a` is longer than `b` so we know which one is the + // shortest & which one is the longest + + if (left.length > right.length) { + left = right; + right = swap; + } + + let leftLength = left.length; + let rightLength = right.length; // Performing suffix trimming: + // We can linearly drop suffix common to both strings since they + // don't increase distance at all + // Note: `~-` is the bitwise way to perform a `- 1` operation + + while (leftLength > 0 && left.charCodeAt(~-leftLength) === right.charCodeAt(~-rightLength)) { + leftLength--; + rightLength--; + } // Performing prefix trimming + // We can linearly drop prefix common to both strings since they + // don't increase distance at all + + + let start = 0; + + while (start < leftLength && left.charCodeAt(start) === right.charCodeAt(start)) { + start++; + } + + leftLength -= start; + rightLength -= start; + + if (leftLength === 0) { + return rightLength; + } + + let bCharCode; + let result; + let temp; + let temp2; + let i = 0; + let j = 0; + + while (i < leftLength) { + charCodeCache$1[i] = left.charCodeAt(start + i); + array$1[i] = ++i; + } + + while (j < rightLength) { + bCharCode = right.charCodeAt(start + j); + temp = j++; + result = j; + + for (i = 0; i < leftLength; i++) { + temp2 = bCharCode === charCodeCache$1[i] ? temp : temp + 1; + temp = array$1[i]; // eslint-disable-next-line no-multi-assign + + result = array$1[i] = temp > result ? temp2 > result ? result + 1 : temp2 : temp2 > temp ? temp + 1 : temp2; + } + } + + return result; +}; + +var leven_1$1 = leven$1; // TODO: Remove this for the next major release + +var _default$2 = leven$1; +leven_1$1.default = _default$2; + +var colorName$1 = { + "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] +}; + +/* MIT license */ + +/* eslint-disable no-mixed-operators */ +// 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(colorName$1)) { + reverseKeywords[colorName$1[key]] = key; +} + +const convert$1 = { + 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'] + } +}; +var conversions$1 = convert$1; // Hide .channels and .labels properties + +for (const model of Object.keys(convert$1)) { + if (!('channels' in convert$1[model])) { + throw new Error('missing channels property: ' + model); + } + + if (!('labels' in convert$1[model])) { + throw new Error('missing channel labels property: ' + model); + } + + if (convert$1[model].labels.length !== convert$1[model].channels) { + throw new Error('channel and label counts mismatch: ' + model); + } + + const { + channels, + labels + } = convert$1[model]; + delete convert$1[model].channels; + delete convert$1[model].labels; + Object.defineProperty(convert$1[model], 'channels', { + value: channels + }); + Object.defineProperty(convert$1[model], 'labels', { + value: labels + }); +} + +convert$1.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$1.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$1.rgb.hwb = function (rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert$1.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$1.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$1.rgb.keyword = function (rgb) { + const reversed = reverseKeywords[rgb]; + + if (reversed) { + return reversed; + } + + let currentClosestDistance = Infinity; + let currentClosestKeyword; + + for (const keyword of Object.keys(colorName$1)) { + const value = colorName$1[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$1.keyword.rgb = function (keyword) { + return colorName$1[keyword]; +}; + +convert$1.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$1.rgb.lab = function (rgb) { + const xyz = convert$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.rgb.ansi16 = function (args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert$1.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$1.hsv.ansi16 = function (args) { + // Optimization here; we already know the value and don't need to get + // it converted for us. + return convert$1.rgb.ansi16(convert$1.hsv.rgb(args), args[2]); +}; + +convert$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.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$1.apple.rgb = function (apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; +}; + +convert$1.rgb.apple = function (rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; +}; + +convert$1.gray.rgb = function (args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; + +convert$1.gray.hsl = function (args) { + return [0, 0, args[0]]; +}; + +convert$1.gray.hsv = convert$1.gray.hsl; + +convert$1.gray.hwb = function (gray) { + return [0, 100, gray[0]]; +}; + +convert$1.gray.cmyk = function (gray) { + return [0, 0, 0, gray[0]]; +}; + +convert$1.gray.lab = function (gray) { + return [gray[0], 0, 0]; +}; + +convert$1.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$1.rgb.gray = function (rgb) { + const val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; +}; + +/* + 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$1() { + const graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + + const models = Object.keys(conversions$1); + + 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$1(fromModel) { + const graph = buildGraph$1(); + const queue = [fromModel]; // Unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + const current = queue.pop(); + const adjacents = Object.keys(conversions$1[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$1(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion$1(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions$1[graph[toModel].parent][toModel]; + let cur = graph[toModel].parent; + + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link$1(conversions$1[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +var route$1 = function (fromModel) { + const graph = deriveBFS$1(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$1(toModel, graph); + } + + return conversion; +}; + +const convert$2 = {}; +const models$1 = Object.keys(conversions$1); + +function wrapRaw$1(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$1(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$1.forEach(fromModel => { + convert$2[fromModel] = {}; + Object.defineProperty(convert$2[fromModel], 'channels', { + value: conversions$1[fromModel].channels + }); + Object.defineProperty(convert$2[fromModel], 'labels', { + value: conversions$1[fromModel].labels + }); + const routes = route$1(fromModel); + const routeModels = Object.keys(routes); + routeModels.forEach(toModel => { + const fn = routes[toModel]; + convert$2[fromModel][toModel] = wrapRounded$1(fn); + convert$2[fromModel][toModel].raw = wrapRaw$1(fn); + }); +}); +var colorConvert$1 = convert$2; + +var ansiStyles$1 = createCommonjsModule(function (module) { + + 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 = colorConvert$1; + } + + 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 + }); +}); + +var hasFlag$1 = (flag, argv = process.argv) => { + const prefix = flag.startsWith('-') ? '' : flag.length === 1 ? '-' : '--'; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf('--'); + return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); +}; + +const { + env: env$1 +} = process; +let forceColor$1; + +if (hasFlag$1('no-color') || hasFlag$1('no-colors') || hasFlag$1('color=false') || hasFlag$1('color=never')) { + forceColor$1 = 0; +} else if (hasFlag$1('color') || hasFlag$1('colors') || hasFlag$1('color=true') || hasFlag$1('color=always')) { + forceColor$1 = 1; +} + +if ('FORCE_COLOR' in env$1) { + if (env$1.FORCE_COLOR === 'true') { + forceColor$1 = 1; + } else if (env$1.FORCE_COLOR === 'false') { + forceColor$1 = 0; + } else { + forceColor$1 = env$1.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env$1.FORCE_COLOR, 10), 3); + } +} + +function translateLevel$1(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor$1(haveStream, streamIsTTY) { + if (forceColor$1 === 0) { + return 0; + } + + if (hasFlag$1('color=16m') || hasFlag$1('color=full') || hasFlag$1('color=truecolor')) { + return 3; + } + + if (hasFlag$1('color=256')) { + return 2; + } + + if (haveStream && !streamIsTTY && forceColor$1 === undefined) { + return 0; + } + + const min = forceColor$1 || 0; + + if (env$1.TERM === 'dumb') { + return min; + } + + if (process.platform === 'win32') { + // Windows 10 build 10586 is the first Windows release that supports 256 colors. + // Windows 10 build 14931 is the first release that supports 16m/TrueColor. + const osRelease = os__default['default'].release().split('.'); + + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$1) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$1) || env$1.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$1) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$1.TEAMCITY_VERSION) ? 1 : 0; + } + + if ('GITHUB_ACTIONS' in env$1) { + return 1; + } + + if (env$1.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$1) { + const version = parseInt((env$1.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$1.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$1.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$1.TERM)) { + return 1; + } + + if ('COLORTERM' in env$1) { + return 1; + } + + return min; +} + +function getSupportLevel$1(stream) { + const level = supportsColor$1(stream, stream && stream.isTTY); + return translateLevel$1(level); +} + +var supportsColor_1$1 = { + supportsColor: getSupportLevel$1, + stdout: translateLevel$1(supportsColor$1(true, tty__default['default'].isatty(1))), + stderr: translateLevel$1(supportsColor$1(true, tty__default['default'].isatty(2))) +}; + +const stringReplaceAll = (string, substring, replacer) => { + let index = string.indexOf(substring); + + if (index === -1) { + return string; + } + + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ''; + + do { + returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { + let endIndex = 0; + let returnValue = ''; + + do { + const gotCR = string[index - 1] === '\r'; + returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; + endIndex = index + 1; + index = string.indexOf('\n', endIndex); + } while (index !== -1); + + returnValue += string.substr(endIndex); + return returnValue; +}; + +var util$1 = { + stringReplaceAll, + stringEncaseCRLFWithFirstIndex +}; + +const TEMPLATE_REGEX$1 = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX$1 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX$1 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX$1 = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; +const ESCAPES$1 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); + +function unescape$1(c) { + const u = c[0] === 'u'; + const bracket = c[1] === '{'; + + if (u && !bracket && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + if (u && bracket) { + return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); + } + + return ESCAPES$1.get(c) || c; +} + +function parseArguments$1(name, arguments_) { + const results = []; + const chunks = arguments_.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + const number = Number(chunk); + + if (!Number.isNaN(number)) { + results.push(number); + } else if (matches = chunk.match(STRING_REGEX$1)) { + results.push(matches[2].replace(ESCAPE_REGEX$1, (m, escape, character) => escape ? unescape$1(escape) : character)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle$1(style) { + STYLE_REGEX$1.lastIndex = 0; + const results = []; + let matches; + + while ((matches = STYLE_REGEX$1.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments$1(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle$1(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + + for (const [styleName, styles] of Object.entries(enabled)) { + if (!Array.isArray(styles)) { + continue; + } + + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; + } + + return current; +} + +var templates$1 = (chalk, temporary) => { + const styles = []; + const chunks = []; + let chunk = []; // eslint-disable-next-line max-params + + temporary.replace(TEMPLATE_REGEX$1, (m, escapeCharacter, inverse, style, close, character) => { + if (escapeCharacter) { + chunk.push(unescape$1(escapeCharacter)); + } else if (style) { + const string = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? string : buildStyle$1(chalk, styles)(string)); + styles.push({ + inverse, + styles: parseStyle$1(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle$1(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(character); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMessage); + } + + return chunks.join(''); +}; + +const { + stdout: stdoutColor, + stderr: stderrColor +} = supportsColor_1$1; +const { + stringReplaceAll: stringReplaceAll$1, + stringEncaseCRLFWithFirstIndex: stringEncaseCRLFWithFirstIndex$1 +} = util$1; +const { + isArray +} = Array; // `supportsColor.level` → `ansiStyles.color[name]` mapping + +const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; +const styles = Object.create(null); + +const applyOptions = (object, options = {}) => { + if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { + throw new Error('The `level` option should be an integer from 0 to 3'); + } // Detect level if not set manually + + + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === undefined ? colorLevel : options.level; +}; + +class ChalkClass { + constructor(options) { + // eslint-disable-next-line no-constructor-return + return chalkFactory(options); + } + +} + +const chalkFactory = options => { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + + chalk.template.constructor = () => { + throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); + }; + + chalk.template.Instance = ChalkClass; + return chalk.template; +}; + +function Chalk(options) { + return chalkFactory(options); +} + +for (const [styleName, style] of Object.entries(ansiStyles$1)) { + styles[styleName] = { + get() { + const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); + Object.defineProperty(this, styleName, { + value: builder + }); + return builder; + } + + }; +} + +styles.visible = { + get() { + const builder = createBuilder(this, this._styler, true); + Object.defineProperty(this, 'visible', { + value: builder + }); + return builder; + } + +}; +const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + +for (const model of usedModels) { + styles[model] = { + get() { + const { + level + } = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles$1.color[levelMapping[level]][model](...arguments_), ansiStyles$1.color.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + + }; +} + +for (const model of usedModels) { + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const { + level + } = this; + return function (...arguments_) { + const styler = createStyler(ansiStyles$1.bgColor[levelMapping[level]][model](...arguments_), ansiStyles$1.bgColor.close, this._styler); + return createBuilder(this, styler, this._isEmpty); + }; + } + + }; +} + +const proto = Object.defineProperties(() => {}, Object.assign({}, styles, { + level: { + enumerable: true, + + get() { + return this._generator.level; + }, + + set(level) { + this._generator.level = level; + } + + } +})); + +const createStyler = (open, close, parent) => { + let openAll; + let closeAll; + + if (parent === undefined) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + + return { + open, + close, + openAll, + closeAll, + parent + }; +}; + +const createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => { + if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { + // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` + return applyStyle(builder, chalkTag(builder, ...arguments_)); + } // Single argument is hot path, implicit coercion is faster than anything + // eslint-disable-next-line no-implicit-coercion + + + return applyStyle(builder, arguments_.length === 1 ? '' + arguments_[0] : arguments_.join(' ')); + }; // We alter the prototype because we must return a function, but there is + // no way to create a function with a different prototype + + + Object.setPrototypeOf(builder, proto); + builder._generator = self; + builder._styler = _styler; + builder._isEmpty = _isEmpty; + return builder; +}; + +const applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self._isEmpty ? '' : string; + } + + let styler = self._styler; + + if (styler === undefined) { + return string; + } + + const { + openAll, + closeAll + } = styler; + + if (string.indexOf('\u001B') !== -1) { + while (styler !== undefined) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + string = stringReplaceAll$1(string, styler.close, styler.open); + styler = styler.parent; + } + } // We can move both next actions out of loop, because remaining actions in loop won't have + // any/visible effect on parts we add here. Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 + + + const lfIndex = string.indexOf('\n'); + + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex$1(string, closeAll, openAll, lfIndex); + } + + return openAll + string + closeAll; +}; + +let template; + +const chalkTag = (chalk, ...strings) => { + const [firstString] = strings; + + if (!isArray(firstString) || !isArray(firstString.raw)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return strings.join(' '); + } + + const arguments_ = strings.slice(1); + const parts = [firstString.raw[0]]; + + for (let i = 1; i < firstString.length; i++) { + parts.push(String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), String(firstString.raw[i])); + } + + if (template === undefined) { + template = templates$1; + } + + return template(chalk, parts.join('')); +}; + +Object.defineProperties(Chalk.prototype, styles); +const chalk$1 = Chalk(); // eslint-disable-line new-cap + +chalk$1.supportsColor = stdoutColor; +chalk$1.stderr = Chalk({ + level: stderrColor ? stderrColor.level : 0 +}); // eslint-disable-line new-cap + +chalk$1.stderr.supportsColor = stderrColor; +var source = chalk$1; + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + + return array; +} + +var _arrayPush = arrayPush; + +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +var _freeGlobal = freeGlobal; + +/** Detect free variable `self`. */ + +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +/** Used as a reference to the global object. */ + +var root = _freeGlobal || freeSelf || Function('return this')(); +var _root = root; + +/** Built-in value references. */ + +var Symbol$1 = _root.Symbol; +var _Symbol = Symbol$1; + +/** Used for built-in method references. */ + +var objectProto = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty = objectProto.hasOwnProperty; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + +var nativeObjectToString = objectProto.toString; +/** Built-in value references. */ + +var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ + +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + + return result; +} + +var _getRawTag = getRawTag; + +/** Used for built-in method references. */ +var objectProto$1 = Object.prototype; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ + +var nativeObjectToString$1 = objectProto$1.toString; +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ + +function objectToString(value) { + return nativeObjectToString$1.call(value); +} + +var _objectToString = objectToString; + +/** `Object#toString` result references. */ + +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; +/** Built-in value references. */ + +var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + + return symToStringTag$1 && symToStringTag$1 in Object(value) ? _getRawTag(value) : _objectToString(value); +} + +var _baseGetTag = baseGetTag; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +var isObjectLike_1 = isObjectLike; + +/** `Object#toString` result references. */ + +var argsTag = '[object Arguments]'; +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ + +function baseIsArguments(value) { + return isObjectLike_1(value) && _baseGetTag(value) == argsTag; +} + +var _baseIsArguments = baseIsArguments; + +/** Used for built-in method references. */ + +var objectProto$2 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$1 = objectProto$2.hasOwnProperty; +/** Built-in value references. */ + +var propertyIsEnumerable = objectProto$2.propertyIsEnumerable; +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ + +var isArguments = _baseIsArguments(function () { + return arguments; +}()) ? _baseIsArguments : function (value) { + return isObjectLike_1(value) && hasOwnProperty$1.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); +}; +var isArguments_1 = isArguments; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray$1 = Array.isArray; +var isArray_1 = isArray$1; + +/** Built-in value references. */ + +var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ + +function isFlattenable(value) { + return isArray_1(value) || isArguments_1(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +var _isFlattenable = isFlattenable; + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ + +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + predicate || (predicate = _isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + _arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + + return result; +} + +var _baseFlatten = baseFlatten; + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ + +function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? _baseFlatten(array, 1) : []; +} + +var flatten_1 = flatten; + +const cliDescriptor = { + key: key => key.length === 1 ? `-${key}` : `--${key}`, + value: value => lib$1.apiDescriptor.value(value), + pair: ({ + key, + value + }) => value === false ? `--no-${key}` : value === true ? cliDescriptor.key(key) : value === "" ? `${cliDescriptor.key(key)} without an argument` : `${cliDescriptor.key(key)}=${value}` +}; + +class FlagSchema extends lib$1.ChoiceSchema { + constructor({ + name, + flags + }) { + super({ + name, + choices: flags + }); + this._flags = flags.slice().sort(); + } + + preprocess(value, utils) { + if (typeof value === "string" && value.length !== 0 && !this._flags.includes(value)) { + const suggestion = this._flags.find(flag => leven_1$1(flag, value) < 3); + + if (suggestion) { + utils.logger.warn([`Unknown flag ${source.yellow(utils.descriptor.value(value))},`, `did you mean ${source.blue(utils.descriptor.value(suggestion))}?`].join(" ")); + return suggestion; + } + } + + return value; + } + + expected() { + return "a flag"; + } + +} + +let hasDeprecationWarned; + +function normalizeOptions(options, optionInfos, { + logger, + isCLI = false, + passThrough = false +} = {}) { + const unknown = !passThrough ? (key, value, options) => { + // Don't suggest `_` for unknown flags + const _options$schemas = options.schemas, + schemas = _objectWithoutPropertiesLoose(_options$schemas, ["_"]); + + return lib$1.levenUnknownHandler(key, value, Object.assign({}, options, { + schemas + })); + } : Array.isArray(passThrough) ? (key, value) => !passThrough.includes(key) ? undefined : { + [key]: value + } : (key, value) => ({ + [key]: value + }); + const descriptor = isCLI ? cliDescriptor : lib$1.apiDescriptor; + const schemas = optionInfosToSchemas(optionInfos, { + isCLI + }); + const normalizer = new lib$1.Normalizer(schemas, { + logger, + unknown, + descriptor + }); + const shouldSuppressDuplicateDeprecationWarnings = logger !== false; + + if (shouldSuppressDuplicateDeprecationWarnings && hasDeprecationWarned) { + normalizer._hasDeprecationWarned = hasDeprecationWarned; + } + + const normalized = normalizer.normalize(options); + + if (shouldSuppressDuplicateDeprecationWarnings) { + hasDeprecationWarned = normalizer._hasDeprecationWarned; + } + + return normalized; +} + +function optionInfosToSchemas(optionInfos, { + isCLI +}) { + const schemas = []; + + if (isCLI) { + schemas.push(lib$1.AnySchema.create({ + name: "_" + })); + } + + for (const optionInfo of optionInfos) { + schemas.push(optionInfoToSchema(optionInfo, { + isCLI, + optionInfos + })); + + if (optionInfo.alias && isCLI) { + schemas.push(lib$1.AliasSchema.create({ + name: optionInfo.alias, + sourceName: optionInfo.name + })); + } + } + + return schemas; +} + +function optionInfoToSchema(optionInfo, { + isCLI, + optionInfos +}) { + let SchemaConstructor; + const parameters = { + name: optionInfo.name + }; + const handlers = {}; + + switch (optionInfo.type) { + case "int": + SchemaConstructor = lib$1.IntegerSchema; + + if (isCLI) { + parameters.preprocess = value => Number(value); + } + + break; + + case "string": + SchemaConstructor = lib$1.StringSchema; + break; + + case "choice": + SchemaConstructor = lib$1.ChoiceSchema; + parameters.choices = optionInfo.choices.map(choiceInfo => typeof choiceInfo === "object" && choiceInfo.redirect ? Object.assign({}, choiceInfo, { + redirect: { + to: { + key: optionInfo.name, + value: choiceInfo.redirect + } + } + }) : choiceInfo); + break; + + case "boolean": + SchemaConstructor = lib$1.BooleanSchema; + break; + + case "flag": + SchemaConstructor = FlagSchema; + parameters.flags = flatten_1(optionInfos.map(optionInfo => [optionInfo.alias, optionInfo.description && optionInfo.name, optionInfo.oppositeDescription && `no-${optionInfo.name}`].filter(Boolean))); + break; + + case "path": + SchemaConstructor = lib$1.StringSchema; + break; + + default: + /* istanbul ignore next */ + throw new Error(`Unexpected type ${optionInfo.type}`); + } + + if (optionInfo.exception) { + parameters.validate = (value, schema, utils) => { + return optionInfo.exception(value) || schema.validate(value, utils); + }; + } else { + parameters.validate = (value, schema, utils) => { + return value === undefined || schema.validate(value, utils); + }; + } + /* istanbul ignore next */ + + + if (optionInfo.redirect) { + handlers.redirect = value => !value ? undefined : { + to: { + key: optionInfo.redirect.option, + value: optionInfo.redirect.value + } + }; + } + /* istanbul ignore next */ + + + if (optionInfo.deprecated) { + handlers.deprecated = true; + } // allow CLI overriding, e.g., prettier package.json --tab-width 1 --tab-width 2 + + + if (isCLI && !optionInfo.array) { + const originalPreprocess = parameters.preprocess || (x => x); + + parameters.preprocess = (value, schema, utils) => schema.preprocess(originalPreprocess(Array.isArray(value) ? value[value.length - 1] : value), utils); + } + + return optionInfo.array ? lib$1.ArraySchema.create(Object.assign({}, isCLI ? { + preprocess: v => [].concat(v) + } : {}, handlers, { + valueSchema: SchemaConstructor.create(parameters) + })) : SchemaConstructor.create(Object.assign({}, parameters, handlers)); +} + +function normalizeApiOptions(options, optionInfos, opts) { + return normalizeOptions(options, optionInfos, opts); +} + +function normalizeCliOptions(options, optionInfos, opts) { + return normalizeOptions(options, optionInfos, Object.assign({ + isCLI: true + }, opts)); +} + +var optionsNormalizer = { + normalizeApiOptions, + normalizeCliOptions +}; + +function locStart(node, opts) { + const { + ignoreDecorators + } = opts || {}; // Handle nodes with decorators. They should start at the first decorator + + if (!ignoreDecorators) { + const decorators = node.declaration && node.declaration.decorators || node.decorators; + + if (decorators && decorators.length > 0) { + return locStart(decorators[0]); + } + } + + return node.range ? node.range[0] : node.start; +} + +function locEnd(node) { + const end = node.range ? node.range[1] : node.end; + return node.typeAnnotation ? Math.max(end, locEnd(node.typeAnnotation)) : end; +} + +function composeLoc(startNode, endNodeOrLength = startNode) { + const start = locStart(startNode); + const end = typeof endNodeOrLength === "number" ? start + endNodeOrLength : locEnd(endNodeOrLength); + return [start, end]; +} + +var loc = { + locStart, + locEnd, + composeLoc +}; + +var jsTokens = createCommonjsModule(function (module, exports) { + // Copyright 2014, 2015, 2016, 2017, 2018 Simon Lydell + // License: MIT. (See LICENSE.) + Object.defineProperty(exports, "__esModule", { + value: true + }); // This regex comes from regex.coffee, and is inserted here by generate-index.js + // (run `npm run build`). + + exports.default = /((['"])(?:(?!\2|\\).|\\(?:\r\n|[\s\S]))*(\2)?|`(?:[^`\\$]|\\[\s\S]|\$(?!\{)|\$\{(?:[^{}]|\{[^}]*\}?)*\}?)*(`)?)|(\/\/.*)|(\/\*(?:[^*]|\*(?!\/))*(\*\/)?)|(\/(?!\*)(?:\[(?:(?![\]\\]).|\\.)*\]|(?![\/\]\\]).|\\.)+\/(?:(?!\s*(?:\b|[\u0080-\uFFFF$\\'"~({]|[+\-!](?!=)|\.?\d))|[gmiyus]{1,6}\b(?![\u0080-\uFFFF$\\]|\s*(?:[+\-*%&|^<>!=?({]|\/(?![\/*])))))|(0[xX][\da-fA-F]+|0[oO][0-7]+|0[bB][01]+|(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?)|((?!\d)(?:(?!\s)[$\w\u0080-\uFFFF]|\\u[\da-fA-F]{4}|\\u\{[\da-fA-F]+\})+)|(--|\+\+|&&|\|\||=>|\.{3}|(?:[+\-\/%&|^]|\*{1,2}|<{1,2}|>{1,3}|!=?|={1,2})=?|[?~.,:;[\](){}])|(\s+)|(^$|[\s\S])/g; + + exports.matchToToken = function (match) { + var token = { + type: "invalid", + value: match[0], + closed: undefined + }; + if (match[1]) token.type = "string", token.closed = !!(match[3] || match[4]);else if (match[5]) token.type = "comment";else if (match[6]) token.type = "comment", token.closed = !!match[7];else if (match[8]) token.type = "regex";else if (match[9]) token.type = "number";else if (match[10]) token.type = "name";else if (match[11]) token.type = "punctuator";else if (match[12]) token.type = "whitespace"; + return token; + }; +}); + +var identifier = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isIdentifierStart = isIdentifierStart; + exports.isIdentifierChar = isIdentifierChar; + exports.isIdentifierName = isIdentifierName; + let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc"; + let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f"; + const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]"); + const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]"); + nonASCIIidentifierStartChars = nonASCIIidentifierChars = null; + const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938]; + const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239]; + + function isInAstralSet(code, set) { + let pos = 0x10000; + + for (let i = 0, length = set.length; i < length; i += 2) { + pos += set[i]; + if (pos > code) return false; + pos += set[i + 1]; + if (pos >= code) return true; + } + + return false; + } + + function isIdentifierStart(code) { + if (code < 65) return code === 36; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes); + } + + function isIdentifierChar(code) { + if (code < 48) return code === 36; + if (code < 58) return true; + if (code < 65) return false; + if (code <= 90) return true; + if (code < 97) return code === 95; + if (code <= 122) return true; + + if (code <= 0xffff) { + return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)); + } + + return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes); + } + + function isIdentifierName(name) { + let isFirst = true; + + for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) { + const char = _Array$from[_i]; + const cp = char.codePointAt(0); + + if (isFirst) { + if (!isIdentifierStart(cp)) { + return false; + } + + isFirst = false; + } else if (!isIdentifierChar(cp)) { + return false; + } + } + + return !isFirst; + } +}); + +var keyword = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isReservedWord = isReservedWord; + exports.isStrictReservedWord = isStrictReservedWord; + exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord; + exports.isStrictBindReservedWord = isStrictBindReservedWord; + exports.isKeyword = isKeyword; + const reservedWords = { + keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"], + strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"], + strictBind: ["eval", "arguments"] + }; + const keywords = new Set(reservedWords.keyword); + const reservedWordsStrictSet = new Set(reservedWords.strict); + const reservedWordsStrictBindSet = new Set(reservedWords.strictBind); + + function isReservedWord(word, inModule) { + return inModule && word === "await" || word === "enum"; + } + + function isStrictReservedWord(word, inModule) { + return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word); + } + + function isStrictBindOnlyReservedWord(word) { + return reservedWordsStrictBindSet.has(word); + } + + function isStrictBindReservedWord(word, inModule) { + return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word); + } + + function isKeyword(word) { + return keywords.has(word); + } +}); + +var lib$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "isIdentifierName", { + enumerable: true, + get: function () { + return identifier.isIdentifierName; + } + }); + Object.defineProperty(exports, "isIdentifierChar", { + enumerable: true, + get: function () { + return identifier.isIdentifierChar; + } + }); + Object.defineProperty(exports, "isIdentifierStart", { + enumerable: true, + get: function () { + return identifier.isIdentifierStart; + } + }); + Object.defineProperty(exports, "isReservedWord", { + enumerable: true, + get: function () { + return keyword.isReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindOnlyReservedWord", { + enumerable: true, + get: function () { + return keyword.isStrictBindOnlyReservedWord; + } + }); + Object.defineProperty(exports, "isStrictBindReservedWord", { + enumerable: true, + get: function () { + return keyword.isStrictBindReservedWord; + } + }); + Object.defineProperty(exports, "isStrictReservedWord", { + enumerable: true, + get: function () { + return keyword.isStrictReservedWord; + } + }); + Object.defineProperty(exports, "isKeyword", { + enumerable: true, + get: function () { + return keyword.isKeyword; + } + }); +}); + +var matchOperatorsRe$1 = /[|\\{}()[\]^$+*?.]/g; + +var escapeStringRegexp$2 = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe$1, '\\$&'); +}; + +var colorName$2 = { + "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] +}; + +var conversions$2 = createCommonjsModule(function (module) { + /* MIT license */ + // 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.) + var reverseKeywords = {}; + + for (var key in colorName$2) { + if (colorName$2.hasOwnProperty(key)) { + reverseKeywords[colorName$2[key]] = key; + } + } + + var convert = module.exports = { + 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'] + } + }; // hide .channels and .labels properties + + for (var model in convert) { + if (convert.hasOwnProperty(model)) { + 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); + } + + var channels = convert[model].channels; + var labels = convert[model].labels; + 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) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var min = Math.min(r, g, b); + var max = Math.max(r, g, b); + var delta = max - min; + var h; + var s; + var l; + + 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; + } + + 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) { + var rdif; + var gdif; + var bdif; + var h; + var s; + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var v = Math.max(r, g, b); + var diff = v - Math.min(r, g, b); + + var diffc = function (c) { + return (v - c) / 6 / diff + 1 / 2; + }; + + if (diff === 0) { + h = 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) { + var r = rgb[0]; + var g = rgb[1]; + var b = rgb[2]; + var h = convert.rgb.hsl(rgb)[0]; + var 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) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var c; + var m; + var y; + var k; + k = Math.min(1 - r, 1 - g, 1 - b); + c = (1 - r - k) / (1 - k) || 0; + m = (1 - g - k) / (1 - k) || 0; + y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; + }; + /** + * See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance + * */ + + + function comparativeDistance(x, y) { + return Math.pow(x[0] - y[0], 2) + Math.pow(x[1] - y[1], 2) + Math.pow(x[2] - y[2], 2); + } + + convert.rgb.keyword = function (rgb) { + var reversed = reverseKeywords[rgb]; + + if (reversed) { + return reversed; + } + + var currentClosestDistance = Infinity; + var currentClosestKeyword; + + for (var keyword in colorName$2) { + if (colorName$2.hasOwnProperty(keyword)) { + var value = colorName$2[keyword]; // Compute comparative distance + + var 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 colorName$2[keyword]; + }; + + convert.rgb.xyz = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; // assume sRGB + + r = r > 0.04045 ? Math.pow((r + 0.055) / 1.055, 2.4) : r / 12.92; + g = g > 0.04045 ? Math.pow((g + 0.055) / 1.055, 2.4) : g / 12.92; + b = b > 0.04045 ? Math.pow((b + 0.055) / 1.055, 2.4) : b / 12.92; + var x = r * 0.4124 + g * 0.3576 + b * 0.1805; + var y = r * 0.2126 + g * 0.7152 + b * 0.0722; + var z = r * 0.0193 + g * 0.1192 + b * 0.9505; + return [x * 100, y * 100, z * 100]; + }; + + convert.rgb.lab = function (rgb) { + var xyz = convert.rgb.xyz(rgb); + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.hsl.rgb = function (hsl) { + var h = hsl[0] / 360; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var t1; + var t2; + var t3; + var rgb; + var 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; + } + + t1 = 2 * l - t2; + rgb = [0, 0, 0]; + + for (var 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) { + var h = hsl[0]; + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var smin = s; + var lmin = Math.max(l, 0.01); + var sv; + var v; + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + v = (l + s) / 2; + sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; + }; + + convert.hsv.rgb = function (hsv) { + var h = hsv[0] / 60; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var hi = Math.floor(h) % 6; + var f = h - Math.floor(h); + var p = 255 * v * (1 - s); + var q = 255 * v * (1 - s * f); + var 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) { + var h = hsv[0]; + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var vmin = Math.max(v, 0.01); + var lmin; + var sl; + var l; + l = (2 - s) * v; + 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) { + var h = hwb[0] / 360; + var wh = hwb[1] / 100; + var bl = hwb[2] / 100; + var ratio = wh + bl; + var i; + var v; + var f; + var n; // wh + bl cant be > 1 + + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + + i = Math.floor(6 * h); + v = 1 - bl; + f = 6 * h - i; + + if ((i & 0x01) !== 0) { + f = 1 - f; + } + + n = wh + f * (v - wh); // linear interpolation + + var r; + var g; + var b; + + 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; + } + + return [r * 255, g * 255, b * 255]; + }; + + convert.cmyk.rgb = function (cmyk) { + var c = cmyk[0] / 100; + var m = cmyk[1] / 100; + var y = cmyk[2] / 100; + var k = cmyk[3] / 100; + var r; + var g; + var b; + r = 1 - Math.min(1, c * (1 - k) + k); + g = 1 - Math.min(1, m * (1 - k) + k); + b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; + }; + + convert.xyz.rgb = function (xyz) { + var x = xyz[0] / 100; + var y = xyz[1] / 100; + var z = xyz[2] / 100; + var r; + var g; + var 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 * Math.pow(r, 1.0 / 2.4) - 0.055 : r * 12.92; + g = g > 0.0031308 ? 1.055 * Math.pow(g, 1.0 / 2.4) - 0.055 : g * 12.92; + b = b > 0.0031308 ? 1.055 * Math.pow(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) { + var x = xyz[0]; + var y = xyz[1]; + var z = xyz[2]; + var l; + var a; + var b; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787 * x + 16 / 116; + y = y > 0.008856 ? Math.pow(y, 1 / 3) : 7.787 * y + 16 / 116; + z = z > 0.008856 ? Math.pow(z, 1 / 3) : 7.787 * z + 16 / 116; + l = 116 * y - 16; + a = 500 * (x - y); + b = 200 * (y - z); + return [l, a, b]; + }; + + convert.lab.xyz = function (lab) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var x; + var y; + var z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + var y2 = Math.pow(y, 3); + var x2 = Math.pow(x, 3); + var z2 = Math.pow(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) { + var l = lab[0]; + var a = lab[1]; + var b = lab[2]; + var hr; + var h; + var c; + hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + + if (h < 0) { + h += 360; + } + + c = Math.sqrt(a * a + b * b); + return [l, c, h]; + }; + + convert.lch.lab = function (lch) { + var l = lch[0]; + var c = lch[1]; + var h = lch[2]; + var a; + var b; + var hr; + hr = h / 360 * 2 * Math.PI; + a = c * Math.cos(hr); + b = c * Math.sin(hr); + return [l, a, b]; + }; + + convert.rgb.ansi16 = function (args) { + var r = args[0]; + var g = args[1]; + var b = args[2]; + var value = 1 in arguments ? arguments[1] : convert.rgb.hsv(args)[2]; // hsv -> ansi16 optimization + + value = Math.round(value / 50); + + if (value === 0) { + return 30; + } + + var 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) { + var r = args[0]; + var g = args[1]; + var 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; + } + + var 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) { + var 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]; + } + + var mult = (~~(args > 50) + 1) * 0.5; + var r = (color & 1) * mult * 255; + var g = (color >> 1 & 1) * mult * 255; + var b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; + }; + + convert.ansi256.rgb = function (args) { + // handle greyscale + if (args >= 232) { + var c = (args - 232) * 10 + 8; + return [c, c, c]; + } + + args -= 16; + var rem; + var r = Math.floor(args / 36) / 5 * 255; + var g = Math.floor((rem = args % 36) / 6) / 5 * 255; + var b = rem % 6 / 5 * 255; + return [r, g, b]; + }; + + convert.rgb.hex = function (args) { + var integer = ((Math.round(args[0]) & 0xFF) << 16) + ((Math.round(args[1]) & 0xFF) << 8) + (Math.round(args[2]) & 0xFF); + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.hex.rgb = function (args) { + var match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); + + if (!match) { + return [0, 0, 0]; + } + + var colorString = match[0]; + + if (match[0].length === 3) { + colorString = colorString.split('').map(function (char) { + return char + char; + }).join(''); + } + + var integer = parseInt(colorString, 16); + var r = integer >> 16 & 0xFF; + var g = integer >> 8 & 0xFF; + var b = integer & 0xFF; + return [r, g, b]; + }; + + convert.rgb.hcg = function (rgb) { + var r = rgb[0] / 255; + var g = rgb[1] / 255; + var b = rgb[2] / 255; + var max = Math.max(Math.max(r, g), b); + var min = Math.min(Math.min(r, g), b); + var chroma = max - min; + var grayscale; + var 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 + 4; + } + + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; + }; + + convert.hsl.hcg = function (hsl) { + var s = hsl[1] / 100; + var l = hsl[2] / 100; + var c = 1; + var f = 0; + + if (l < 0.5) { + c = 2.0 * s * l; + } else { + c = 2.0 * s * (1.0 - l); + } + + if (c < 1.0) { + f = (l - 0.5 * c) / (1.0 - c); + } + + return [hsl[0], c * 100, f * 100]; + }; + + convert.hsv.hcg = function (hsv) { + var s = hsv[1] / 100; + var v = hsv[2] / 100; + var c = s * v; + var f = 0; + + if (c < 1.0) { + f = (v - c) / (1 - c); + } + + return [hsv[0], c * 100, f * 100]; + }; + + convert.hcg.rgb = function (hcg) { + var h = hcg[0] / 360; + var c = hcg[1] / 100; + var g = hcg[2] / 100; + + if (c === 0.0) { + return [g * 255, g * 255, g * 255]; + } + + var pure = [0, 0, 0]; + var hi = h % 1 * 6; + var v = hi % 1; + var w = 1 - v; + var mg = 0; + + 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; + } + + 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) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + var f = 0; + + if (v > 0.0) { + f = c / v; + } + + return [hcg[0], f * 100, v * 100]; + }; + + convert.hcg.hsl = function (hcg) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var l = g * (1.0 - c) + 0.5 * c; + var 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) { + var c = hcg[1] / 100; + var g = hcg[2] / 100; + var v = c + g * (1.0 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; + }; + + convert.hwb.hcg = function (hwb) { + var w = hwb[1] / 100; + var b = hwb[2] / 100; + var v = 1 - b; + var c = v - w; + var 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 = convert.gray.hsv = function (args) { + return [0, 0, args[0]]; + }; + + 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) { + var val = Math.round(gray[0] / 100 * 255) & 0xFF; + var integer = (val << 16) + (val << 8) + val; + var string = integer.toString(16).toUpperCase(); + return '000000'.substring(string.length) + string; + }; + + convert.rgb.gray = function (rgb) { + var val = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [val / 255 * 100]; + }; +}); + +/* + 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$2() { + var graph = {}; // https://jsperf.com/object-keys-vs-for-in-with-closure/3 + + var models = Object.keys(conversions$2); + + for (var 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$2(fromModel) { + var graph = buildGraph$2(); + var queue = [fromModel]; // unshift -> queue -> pop + + graph[fromModel].distance = 0; + + while (queue.length) { + var current = queue.pop(); + var adjacents = Object.keys(conversions$2[current]); + + for (var len = adjacents.length, i = 0; i < len; i++) { + var adjacent = adjacents[i]; + var node = graph[adjacent]; + + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + + return graph; +} + +function link$2(from, to) { + return function (args) { + return to(from(args)); + }; +} + +function wrapConversion$2(toModel, graph) { + var path = [graph[toModel].parent, toModel]; + var fn = conversions$2[graph[toModel].parent][toModel]; + var cur = graph[toModel].parent; + + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link$2(conversions$2[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + + fn.conversion = path; + return fn; +} + +var route$2 = function (fromModel) { + var graph = deriveBFS$2(fromModel); + var conversion = {}; + var models = Object.keys(graph); + + for (var len = models.length, i = 0; i < len; i++) { + var toModel = models[i]; + var node = graph[toModel]; + + if (node.parent === null) { + // no possible conversion, or this node is the source model. + continue; + } + + conversion[toModel] = wrapConversion$2(toModel, graph); + } + + return conversion; +}; + +var convert$3 = {}; +var models$2 = Object.keys(conversions$2); + +function wrapRaw$2(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + return fn(args); + }; // preserve .conversion property if there is one + + + if ('conversion' in fn) { + wrappedFn.conversion = fn.conversion; + } + + return wrappedFn; +} + +function wrapRounded$2(fn) { + var wrappedFn = function (args) { + if (args === undefined || args === null) { + return args; + } + + if (arguments.length > 1) { + args = Array.prototype.slice.call(arguments); + } + + var 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 (var 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$2.forEach(function (fromModel) { + convert$3[fromModel] = {}; + Object.defineProperty(convert$3[fromModel], 'channels', { + value: conversions$2[fromModel].channels + }); + Object.defineProperty(convert$3[fromModel], 'labels', { + value: conversions$2[fromModel].labels + }); + var routes = route$2(fromModel); + var routeModels = Object.keys(routes); + routeModels.forEach(function (toModel) { + var fn = routes[toModel]; + convert$3[fromModel][toModel] = wrapRounded$2(fn); + convert$3[fromModel][toModel].raw = wrapRaw$2(fn); + }); +}); +var colorConvert$2 = convert$3; + +var ansiStyles$2 = createCommonjsModule(function (module) { + + const wrapAnsi16 = (fn, offset) => function () { + const code = fn.apply(colorConvert$2, arguments); + return `\u001B[${code + offset}m`; + }; + + const wrapAnsi256 = (fn, offset) => function () { + const code = fn.apply(colorConvert$2, arguments); + return `\u001B[${38 + offset};5;${code}m`; + }; + + const wrapAnsi16m = (fn, offset) => function () { + const rgb = fn.apply(colorConvert$2, arguments); + return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; + }; + + 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], + gray: [90, 39], + // Bright color + 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] + } + }; // Fix humans + + styles.color.grey = styles.color.gray; + + for (const groupName of Object.keys(styles)) { + const group = styles[groupName]; + + for (const styleName of Object.keys(group)) { + const style = group[styleName]; + 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 + }); + } + + const ansi2ansi = n => n; + + const rgb2rgb = (r, g, b) => [r, g, b]; + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + styles.color.ansi = { + ansi: wrapAnsi16(ansi2ansi, 0) + }; + styles.color.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 0) + }; + styles.color.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 0) + }; + styles.bgColor.ansi = { + ansi: wrapAnsi16(ansi2ansi, 10) + }; + styles.bgColor.ansi256 = { + ansi256: wrapAnsi256(ansi2ansi, 10) + }; + styles.bgColor.ansi16m = { + rgb: wrapAnsi16m(rgb2rgb, 10) + }; + + for (let key of Object.keys(colorConvert$2)) { + if (typeof colorConvert$2[key] !== 'object') { + continue; + } + + const suite = colorConvert$2[key]; + + if (key === 'ansi16') { + key = 'ansi'; + } + + if ('ansi16' in suite) { + styles.color.ansi[key] = wrapAnsi16(suite.ansi16, 0); + styles.bgColor.ansi[key] = wrapAnsi16(suite.ansi16, 10); + } + + if ('ansi256' in suite) { + styles.color.ansi256[key] = wrapAnsi256(suite.ansi256, 0); + styles.bgColor.ansi256[key] = wrapAnsi256(suite.ansi256, 10); + } + + if ('rgb' in suite) { + styles.color.ansi16m[key] = wrapAnsi16m(suite.rgb, 0); + styles.bgColor.ansi16m[key] = wrapAnsi16m(suite.rgb, 10); + } + } + + return styles; + } // Make the export immutable + + + Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles + }); +}); + +const env$2 = process.env; +let forceColor$2; + +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor$2 = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { + forceColor$2 = true; +} + +if ('FORCE_COLOR' in env$2) { + forceColor$2 = env$2.FORCE_COLOR.length === 0 || parseInt(env$2.FORCE_COLOR, 10) !== 0; +} + +function translateLevel$2(level) { + if (level === 0) { + return false; + } + + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3 + }; +} + +function supportsColor$2(stream) { + if (forceColor$2 === false) { + return 0; + } + + if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { + return 3; + } + + if (hasFlag('color=256')) { + return 2; + } + + if (stream && !stream.isTTY && forceColor$2 !== true) { + return 0; + } + + const min = forceColor$2 ? 1 : 0; + + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first Windows + // release that supports 256 colors. Windows 10 build 14931 is the first release + // that supports 16m/TrueColor. + const osRelease = os__default['default'].release().split('.'); + + if (Number(process.versions.node.split('.')[0]) >= 8 && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + + return 1; + } + + if ('CI' in env$2) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(sign => sign in env$2) || env$2.CI_NAME === 'codeship') { + return 1; + } + + return min; + } + + if ('TEAMCITY_VERSION' in env$2) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env$2.TEAMCITY_VERSION) ? 1 : 0; + } + + if (env$2.COLORTERM === 'truecolor') { + return 3; + } + + if ('TERM_PROGRAM' in env$2) { + const version = parseInt((env$2.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + + switch (env$2.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + + case 'Apple_Terminal': + return 2; + // No default + } + } + + if (/-256(color)?$/i.test(env$2.TERM)) { + return 2; + } + + if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env$2.TERM)) { + return 1; + } + + if ('COLORTERM' in env$2) { + return 1; + } + + if (env$2.TERM === 'dumb') { + return min; + } + + return min; +} + +function getSupportLevel$2(stream) { + const level = supportsColor$2(stream); + return translateLevel$2(level); +} + +var supportsColor_1$2 = { + supportsColor: getSupportLevel$2, + stdout: getSupportLevel$2(process.stdout), + stderr: getSupportLevel$2(process.stderr) +}; + +const TEMPLATE_REGEX$2 = /(?:\\(u[a-f\d]{4}|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; +const STYLE_REGEX$2 = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; +const STRING_REGEX$2 = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; +const ESCAPE_REGEX$2 = /\\(u[a-f\d]{4}|x[a-f\d]{2}|.)|([^\\])/gi; +const ESCAPES$2 = new Map([['n', '\n'], ['r', '\r'], ['t', '\t'], ['b', '\b'], ['f', '\f'], ['v', '\v'], ['0', '\0'], ['\\', '\\'], ['e', '\u001B'], ['a', '\u0007']]); + +function unescape$2(c) { + if (c[0] === 'u' && c.length === 5 || c[0] === 'x' && c.length === 3) { + return String.fromCharCode(parseInt(c.slice(1), 16)); + } + + return ESCAPES$2.get(c) || c; +} + +function parseArguments$2(name, args) { + const results = []; + const chunks = args.trim().split(/\s*,\s*/g); + let matches; + + for (const chunk of chunks) { + if (!isNaN(chunk)) { + results.push(Number(chunk)); + } else if (matches = chunk.match(STRING_REGEX$2)) { + results.push(matches[2].replace(ESCAPE_REGEX$2, (m, escape, chr) => escape ? unescape$2(escape) : chr)); + } else { + throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); + } + } + + return results; +} + +function parseStyle$2(style) { + STYLE_REGEX$2.lastIndex = 0; + const results = []; + let matches; + + while ((matches = STYLE_REGEX$2.exec(style)) !== null) { + const name = matches[1]; + + if (matches[2]) { + const args = parseArguments$2(name, matches[2]); + results.push([name].concat(args)); + } else { + results.push([name]); + } + } + + return results; +} + +function buildStyle$2(chalk, styles) { + const enabled = {}; + + for (const layer of styles) { + for (const style of layer.styles) { + enabled[style[0]] = layer.inverse ? null : style.slice(1); + } + } + + let current = chalk; + + for (const styleName of Object.keys(enabled)) { + if (Array.isArray(enabled[styleName])) { + if (!(styleName in current)) { + throw new Error(`Unknown Chalk style: ${styleName}`); + } + + if (enabled[styleName].length > 0) { + current = current[styleName].apply(current, enabled[styleName]); + } else { + current = current[styleName]; + } + } + } + + return current; +} + +var templates$2 = (chalk, tmp) => { + const styles = []; + const chunks = []; + let chunk = []; // eslint-disable-next-line max-params + + tmp.replace(TEMPLATE_REGEX$2, (m, escapeChar, inverse, style, close, chr) => { + if (escapeChar) { + chunk.push(unescape$2(escapeChar)); + } else if (style) { + const str = chunk.join(''); + chunk = []; + chunks.push(styles.length === 0 ? str : buildStyle$2(chalk, styles)(str)); + styles.push({ + inverse, + styles: parseStyle$2(style) + }); + } else if (close) { + if (styles.length === 0) { + throw new Error('Found extraneous } in Chalk template literal'); + } + + chunks.push(buildStyle$2(chalk, styles)(chunk.join(''))); + chunk = []; + styles.pop(); + } else { + chunk.push(chr); + } + }); + chunks.push(chunk.join('')); + + if (styles.length > 0) { + const errMsg = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; + throw new Error(errMsg); + } + + return chunks.join(''); +}; + +var chalk$2 = createCommonjsModule(function (module) { + + const stdoutColor = supportsColor_1$2.stdout; + const isSimpleWindowsTerm = process.platform === 'win32' && !(process.env.TERM || '').toLowerCase().startsWith('xterm'); // `supportsColor.level` → `ansiStyles.color[name]` mapping + + const levelMapping = ['ansi', 'ansi', 'ansi256', 'ansi16m']; // `color-convert` models to exclude from the Chalk API due to conflicts and such + + const skipModels = new Set(['gray']); + const styles = Object.create(null); + + function applyOptions(obj, options) { + options = options || {}; // Detect level if not set manually + + const scLevel = stdoutColor ? stdoutColor.level : 0; + obj.level = options.level === undefined ? scLevel : options.level; + obj.enabled = 'enabled' in options ? options.enabled : obj.level > 0; + } + + function Chalk(options) { + // We check for this.template here since calling `chalk.constructor()` + // by itself will have a `this` of a previously constructed chalk object + if (!this || !(this instanceof Chalk) || this.template) { + const chalk = {}; + applyOptions(chalk, options); + + chalk.template = function () { + const args = [].slice.call(arguments); + return chalkTag.apply(null, [chalk.template].concat(args)); + }; + + Object.setPrototypeOf(chalk, Chalk.prototype); + Object.setPrototypeOf(chalk.template, chalk); + chalk.template.constructor = Chalk; + return chalk.template; + } + + applyOptions(this, options); + } // Use bright blue on Windows as the normal blue color is illegible + + + if (isSimpleWindowsTerm) { + ansiStyles$2.blue.open = '\u001B[94m'; + } + + for (const key of Object.keys(ansiStyles$2)) { + ansiStyles$2[key].closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2[key].close), 'g'); + styles[key] = { + get() { + const codes = ansiStyles$2[key]; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, key); + } + + }; + } + + styles.visible = { + get() { + return build.call(this, this._styles || [], true, 'visible'); + } + + }; + ansiStyles$2.color.closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2.color.close), 'g'); + + for (const model of Object.keys(ansiStyles$2.color.ansi)) { + if (skipModels.has(model)) { + continue; + } + + styles[model] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles$2.color[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles$2.color.close, + closeRe: ansiStyles$2.color.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + + }; + } + + ansiStyles$2.bgColor.closeRe = new RegExp(escapeStringRegexp$2(ansiStyles$2.bgColor.close), 'g'); + + for (const model of Object.keys(ansiStyles$2.bgColor.ansi)) { + if (skipModels.has(model)) { + continue; + } + + const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); + styles[bgModel] = { + get() { + const level = this.level; + return function () { + const open = ansiStyles$2.bgColor[levelMapping[level]][model].apply(null, arguments); + const codes = { + open, + close: ansiStyles$2.bgColor.close, + closeRe: ansiStyles$2.bgColor.closeRe + }; + return build.call(this, this._styles ? this._styles.concat(codes) : [codes], this._empty, model); + }; + } + + }; + } + + const proto = Object.defineProperties(() => {}, styles); + + function build(_styles, _empty, key) { + const builder = function () { + return applyStyle.apply(builder, arguments); + }; + + builder._styles = _styles; + builder._empty = _empty; + const self = this; + Object.defineProperty(builder, 'level', { + enumerable: true, + + get() { + return self.level; + }, + + set(level) { + self.level = level; + } + + }); + Object.defineProperty(builder, 'enabled', { + enumerable: true, + + get() { + return self.enabled; + }, + + set(enabled) { + self.enabled = enabled; + } + + }); // See below for fix regarding invisible grey/dim combination on Windows + + builder.hasGrey = this.hasGrey || key === 'gray' || key === 'grey'; // `__proto__` is used because we must return a function, but there is + // no way to create a function with a different prototype + + builder.__proto__ = proto; // eslint-disable-line no-proto + + return builder; + } + + function applyStyle() { + // Support varags, but simply cast to string in case there's only one arg + const args = arguments; + const argsLen = args.length; + let str = String(arguments[0]); + + if (argsLen === 0) { + return ''; + } + + if (argsLen > 1) { + // Don't slice `arguments`, it prevents V8 optimizations + for (let a = 1; a < argsLen; a++) { + str += ' ' + args[a]; + } + } + + if (!this.enabled || this.level <= 0 || !str) { + return this._empty ? '' : str; + } // Turns out that on Windows dimmed gray text becomes invisible in cmd.exe, + // see https://github.com/chalk/chalk/issues/58 + // If we're on Windows and we're dealing with a gray color, temporarily make 'dim' a noop. + + + const originalDim = ansiStyles$2.dim.open; + + if (isSimpleWindowsTerm && this.hasGrey) { + ansiStyles$2.dim.open = ''; + } + + for (const code of this._styles.slice().reverse()) { + // Replace any instances already present with a re-opening code + // otherwise only the part of the string until said closing code + // will be colored, and the rest will simply be 'plain'. + str = code.open + str.replace(code.closeRe, code.open) + code.close; // Close the styling before a linebreak and reopen + // after next line to fix a bleed issue on macOS + // https://github.com/chalk/chalk/pull/92 + + str = str.replace(/\r?\n/g, `${code.close}$&${code.open}`); + } // Reset the original `dim` if we changed it to work around the Windows dimmed gray issue + + + ansiStyles$2.dim.open = originalDim; + return str; + } + + function chalkTag(chalk, strings) { + if (!Array.isArray(strings)) { + // If chalk() was called by itself or with a string, + // return the string itself as a string. + return [].slice.call(arguments, 1).join(' '); + } + + const args = [].slice.call(arguments, 2); + const parts = [strings.raw[0]]; + + for (let i = 1; i < strings.length; i++) { + parts.push(String(args[i - 1]).replace(/[{}\\]/g, '\\$&')); + parts.push(String(strings.raw[i])); + } + + return templates$2(chalk, parts.join('')); + } + + Object.defineProperties(Chalk.prototype, styles); + module.exports = Chalk(); // eslint-disable-line new-cap + + module.exports.supportsColor = stdoutColor; + module.exports.default = module.exports; // For TypeScript +}); + +var lib$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.shouldHighlight = shouldHighlight; + exports.getChalk = getChalk; + exports.default = highlight; + + var _jsTokens = _interopRequireWildcard(jsTokens); + + var _chalk = _interopRequireDefault(chalk$2); + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + + function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); + + _getRequireWildcardCache = function () { + return cache; + }; + + return cache; + } + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + + newObj.default = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; + } + + function getDefs(chalk) { + return { + keyword: chalk.cyan, + capitalized: chalk.yellow, + jsx_tag: chalk.yellow, + punctuator: chalk.yellow, + number: chalk.magenta, + string: chalk.green, + regex: chalk.magenta, + comment: chalk.grey, + invalid: chalk.white.bgRed.bold + }; + } + + const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + const JSX_TAG = /^[a-z][\w-]*$/i; + const BRACKET = /^[()[\]{}]$/; + + function getTokenType(match) { + const [offset, text] = match.slice(-2); + const token = (0, _jsTokens.matchToToken)(match); + + if (token.type === "name") { + if ((0, lib$2.isKeyword)(token.value) || (0, lib$2.isReservedWord)(token.value)) { + return "keyword"; + } + + if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == " colorize(str)).join("\n"); + } else { + return args[0]; + } + }); + } + + function shouldHighlight(options) { + return _chalk.default.supportsColor || options.forceColor; + } + + function getChalk(options) { + let chalk = _chalk.default; + + if (options.forceColor) { + chalk = new _chalk.default.constructor({ + enabled: true, + level: 1 + }); + } + + return chalk; + } + + function highlight(code, options = {}) { + if (shouldHighlight(options)) { + const chalk = getChalk(options); + const defs = getDefs(chalk); + return highlightTokens(defs, code); + } else { + return code; + } + } +}); + +var lib$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.codeFrameColumns = codeFrameColumns; + exports.default = _default; + + var _highlight = _interopRequireWildcard(lib$3); + + function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); + + _getRequireWildcardCache = function () { + return cache; + }; + + return cache; + } + + function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + + if (obj === null || typeof obj !== "object" && typeof obj !== "function") { + return { + default: obj + }; + } + + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + + newObj.default = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; + } + + let deprecationWarningShown = false; + + function getDefs(chalk) { + return { + gutter: chalk.grey, + marker: chalk.red.bold, + message: chalk.red.bold + }; + } + + const NEWLINE = /\r\n|[\n\r\u2028\u2029]/; + + function getMarkerLines(loc, source, opts) { + const startLoc = Object.assign({ + column: 0, + line: -1 + }, loc.start); + const endLoc = Object.assign({}, startLoc, loc.end); + const { + linesAbove = 2, + linesBelow = 3 + } = opts || {}; + const startLine = startLoc.line; + const startColumn = startLoc.column; + const endLine = endLoc.line; + const endColumn = endLoc.column; + let start = Math.max(startLine - (linesAbove + 1), 0); + let end = Math.min(source.length, endLine + linesBelow); + + if (startLine === -1) { + start = 0; + } + + if (endLine === -1) { + end = source.length; + } + + const lineDiff = endLine - startLine; + const markerLines = {}; + + if (lineDiff) { + for (let i = 0; i <= lineDiff; i++) { + const lineNumber = i + startLine; + + if (!startColumn) { + markerLines[lineNumber] = true; + } else if (i === 0) { + const sourceLength = source[lineNumber - 1].length; + markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1]; + } else if (i === lineDiff) { + markerLines[lineNumber] = [0, endColumn]; + } else { + const sourceLength = source[lineNumber - i].length; + markerLines[lineNumber] = [0, sourceLength]; + } + } + } else { + if (startColumn === endColumn) { + if (startColumn) { + markerLines[startLine] = [startColumn, 0]; + } else { + markerLines[startLine] = true; + } + } else { + markerLines[startLine] = [startColumn, endColumn - startColumn]; + } + } + + return { + start, + end, + markerLines + }; + } + + function codeFrameColumns(rawLines, loc, opts = {}) { + const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts); + const chalk = (0, _highlight.getChalk)(opts); + const defs = getDefs(chalk); + + const maybeHighlight = (chalkFn, string) => { + return highlighted ? chalkFn(string) : string; + }; + + const lines = rawLines.split(NEWLINE); + const { + start, + end, + markerLines + } = getMarkerLines(loc, lines, opts); + const hasColumns = loc.start && typeof loc.start.column === "number"; + const numberMaxWidth = String(end).length; + const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines; + let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => { + const number = start + 1 + index; + const paddedNumber = ` ${number}`.slice(-numberMaxWidth); + const gutter = ` ${paddedNumber} | `; + const hasMarker = markerLines[number]; + const lastMarkerLine = !markerLines[number + 1]; + + if (hasMarker) { + let markerLine = ""; + + if (Array.isArray(hasMarker)) { + const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " "); + const numberOfMarkers = hasMarker[1] || 1; + markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join(""); + + if (lastMarkerLine && opts.message) { + markerLine += " " + maybeHighlight(defs.message, opts.message); + } + } + + return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join(""); + } else { + return ` ${maybeHighlight(defs.gutter, gutter)}${line}`; + } + }).join("\n"); + + if (opts.message && !hasColumns) { + frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`; + } + + if (highlighted) { + return chalk.reset(frame); + } else { + return frame; + } + } + + function _default(rawLines, lineNumber, colNumber, opts = {}) { + if (!deprecationWarningShown) { + deprecationWarningShown = true; + const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`."; + + if (process.emitWarning) { + process.emitWarning(message, "DeprecationWarning"); + } else { + const deprecationError = new Error(message); + deprecationError.name = "DeprecationWarning"; + console.warn(new Error(message)); + } + } + + colNumber = Math.max(colNumber, 0); + const location = { + start: { + column: colNumber, + line: lineNumber + } + }; + return codeFrameColumns(rawLines, location, opts); + } +}); + +const { + ConfigError: ConfigError$1 +} = errors; +const { + locStart: locStart$1, + locEnd: locEnd$1 +} = loc; // Use defineProperties()/getOwnPropertyDescriptor() to prevent +// triggering the parsers getters. + +const ownNames = Object.getOwnPropertyNames; +const ownDescriptor = Object.getOwnPropertyDescriptor; + +function getParsers(options) { + const parsers = {}; + + for (const plugin of options.plugins) { + // TODO: test this with plugins + + /* istanbul ignore next */ + if (!plugin.parsers) { + continue; + } + + for (const name of ownNames(plugin.parsers)) { + Object.defineProperty(parsers, name, ownDescriptor(plugin.parsers, name)); + } + } + + return parsers; +} + +function resolveParser(opts, parsers) { + parsers = parsers || getParsers(opts); + + if (typeof opts.parser === "function") { + // Custom parser API always works with JavaScript. + return { + parse: opts.parser, + astFormat: "estree", + locStart: locStart$1, + locEnd: locEnd$1 + }; + } + + if (typeof opts.parser === "string") { + if (Object.prototype.hasOwnProperty.call(parsers, opts.parser)) { + return parsers[opts.parser]; + } + + try { + return { + parse: require(path__default['default'].resolve(process.cwd(), opts.parser)), + astFormat: "estree", + locStart: locStart$1, + locEnd: locEnd$1 + }; + } catch (err) { + /* istanbul ignore next */ + throw new ConfigError$1(`Couldn't resolve parser "${opts.parser}"`); + } + } +} + +function parse(text, opts) { + const parsers = getParsers(opts); // Create a new object {parserName: parseFn}. Uses defineProperty() to only call + // the parsers getters when actually calling the parser `parse` function. + + const parsersForCustomParserApi = Object.keys(parsers).reduce((object, parserName) => Object.defineProperty(object, parserName, { + enumerable: true, + + get() { + return parsers[parserName].parse; + } + + }), {}); + const parser = resolveParser(opts, parsers); + + try { + if (parser.preprocess) { + text = parser.preprocess(text, opts); + } + + return { + text, + ast: parser.parse(text, parsersForCustomParserApi, opts) + }; + } catch (error) { + const { + loc + } = error; + + if (loc) { + const codeFrame = lib$4; + error.codeFrame = codeFrame.codeFrameColumns(text, loc, { + highlightCode: true + }); + error.message += "\n" + error.codeFrame; + throw error; + } + /* istanbul ignore next */ + + + throw error.stack; + } +} + +var parser = { + parse, + resolveParser +}; + +const { + UndefinedParserError: UndefinedParserError$1 +} = errors; +const { + getSupportInfo: getSupportInfo$1 +} = support; +const { + resolveParser: resolveParser$1 +} = parser; +const hiddenDefaults = { + astFormat: "estree", + printer: {}, + originalText: undefined, + locStart: null, + locEnd: null +}; // Copy options and fill in default values. + +function normalize$1(options, opts) { + opts = opts || {}; + const rawOptions = Object.assign({}, options); + const supportOptions = getSupportInfo$1({ + plugins: options.plugins, + showUnreleased: true, + showDeprecated: true + }).options; + const defaults = Object.assign({}, hiddenDefaults, fromPairs_1(supportOptions.filter(optionInfo => optionInfo.default !== undefined).map(option => [option.name, option.default]))); + + if (!rawOptions.parser) { + if (!rawOptions.filepath) { + const logger = opts.logger || console; + logger.warn("No parser and no filepath given, using 'babel' the parser now " + "but this will throw an error in the future. " + "Please specify a parser or a filepath so one can be inferred."); + rawOptions.parser = "babel"; + } else { + rawOptions.parser = inferParser(rawOptions.filepath, rawOptions.plugins); + + if (!rawOptions.parser) { + throw new UndefinedParserError$1(`No parser could be inferred for file: ${rawOptions.filepath}`); + } + } + } + + const parser = resolveParser$1(optionsNormalizer.normalizeApiOptions(rawOptions, [supportOptions.find(x => x.name === "parser")], { + passThrough: true, + logger: false + })); + rawOptions.astFormat = parser.astFormat; + rawOptions.locEnd = parser.locEnd; + rawOptions.locStart = parser.locStart; + const plugin = getPlugin(rawOptions); + rawOptions.printer = plugin.printers[rawOptions.astFormat]; + const pluginDefaults = supportOptions.filter(optionInfo => optionInfo.pluginDefaults && optionInfo.pluginDefaults[plugin.name] !== undefined).reduce((reduced, optionInfo) => Object.assign(reduced, { + [optionInfo.name]: optionInfo.pluginDefaults[plugin.name] + }), {}); + const mixedDefaults = Object.assign({}, defaults, pluginDefaults); + Object.keys(mixedDefaults).forEach(k => { + if (rawOptions[k] == null) { + rawOptions[k] = mixedDefaults[k]; + } + }); + + if (rawOptions.parser === "json") { + rawOptions.trailingComma = "none"; + } + + return optionsNormalizer.normalizeApiOptions(rawOptions, supportOptions, Object.assign({ + passThrough: Object.keys(hiddenDefaults) + }, opts)); +} + +function getPlugin(options) { + const { + astFormat + } = options; // TODO: test this with plugins + + /* istanbul ignore next */ + + if (!astFormat) { + throw new Error("getPlugin() requires astFormat to be set"); + } + + const printerPlugin = options.plugins.find(plugin => plugin.printers && plugin.printers[astFormat]); // TODO: test this with plugins + + /* istanbul ignore next */ + + if (!printerPlugin) { + throw new Error(`Couldn't find plugin for AST format "${astFormat}"`); + } + + return printerPlugin; +} + +function getInterpreter(filepath) { + /* istanbul ignore next */ + if (typeof filepath !== "string") { + return ""; + } + + let fd; + + try { + fd = fs__default['default'].openSync(filepath, "r"); + } catch (err) { + // istanbul ignore next + return ""; + } + + try { + const liner = new readlines(fd); + const firstLine = liner.next().toString("utf8"); // #!/bin/env node, #!/usr/bin/env node + + const m1 = firstLine.match(/^#!\/(?:usr\/)?bin\/env\s+(\S+)/); + + if (m1) { + return m1[1]; + } // #!/bin/node, #!/usr/bin/node, #!/usr/local/bin/node + + + const m2 = firstLine.match(/^#!\/(?:usr\/(?:local\/)?)?bin\/(\S+)/); + + if (m2) { + return m2[1]; + } + + return ""; + } catch (err) { + // There are some weird cases where paths are missing, causing Jest + // failures. It's unclear what these correspond to in the real world. + + /* istanbul ignore next */ + return ""; + } finally { + try { + // There are some weird cases where paths are missing, causing Jest + // failures. It's unclear what these correspond to in the real world. + fs__default['default'].closeSync(fd); + } catch (err) {// nop + } + } +} + +function inferParser(filepath, plugins) { + const filename = path__default['default'].basename(filepath).toLowerCase(); + const languages = getSupportInfo$1({ + plugins + }).languages.filter(language => language.since !== null); // If the file has no extension, we can try to infer the language from the + // interpreter in the shebang line, if any; but since this requires FS access, + // do it last. + + let language = languages.find(language => language.extensions && language.extensions.some(extension => filename.endsWith(extension)) || language.filenames && language.filenames.some(name => name.toLowerCase() === filename)); + + if (!language && !filename.includes(".")) { + const interpreter = getInterpreter(filepath); + language = languages.find(language => language.interpreters && language.interpreters.includes(interpreter)); + } + + return language && language.parsers[0]; +} + +var options$1 = { + normalize: normalize$1, + hiddenDefaults, + inferParser +}; + +function massageAST(ast, options, parent) { + if (Array.isArray(ast)) { + return ast.map(e => massageAST(e, options, parent)).filter(Boolean); + } + + if (!ast || typeof ast !== "object") { + return ast; + } + + const newObj = {}; + + for (const key of Object.keys(ast)) { + if (typeof ast[key] !== "function") { + newObj[key] = massageAST(ast[key], options, ast); + } + } + + if (options.printer.massageAstNode) { + const result = options.printer.massageAstNode(ast, newObj, parent); + + if (result === null) { + return; + } + + if (result) { + return result; + } + } + + return newObj; +} + +var massageAst = massageAST; + +/** @type {import("assert")} */ + + +const { + concat: concat$3, + line: line$1, + hardline: hardline$1, + breakParent: breakParent$1, + indent: indent$1, + lineSuffix: lineSuffix$1, + join: join$1, + cursor: cursor$2 +} = document.builders; +const { + hasNewline: hasNewline$1, + skipNewline: skipNewline$1, + skipSpaces: skipSpaces$1, + isPreviousLineEmpty: isPreviousLineEmpty$1, + addLeadingComment: addLeadingComment$1, + addDanglingComment: addDanglingComment$1, + addTrailingComment: addTrailingComment$1 +} = util; +const childNodesCacheKey = Symbol("child-nodes"); + +function getSortedChildNodes(node, options, resultArray) { + if (!node) { + return; + } + + const { + printer, + locStart, + locEnd + } = options; + + if (resultArray) { + if (printer.canAttachComment && printer.canAttachComment(node)) { + // This reverse insertion sort almost always takes constant + // time because we almost always (maybe always?) append the + // nodes in order anyway. + let i; + + for (i = resultArray.length - 1; i >= 0; --i) { + if (locStart(resultArray[i]) <= locStart(node) && locEnd(resultArray[i]) <= locEnd(node)) { + break; + } + } + + resultArray.splice(i + 1, 0, node); + return; + } + } else if (node[childNodesCacheKey]) { + return node[childNodesCacheKey]; + } + + const childNodes = printer.getCommentChildNodes && printer.getCommentChildNodes(node, options) || typeof node === "object" && Object.keys(node).filter(n => n !== "enclosingNode" && n !== "precedingNode" && n !== "followingNode" && n !== "tokens" && n !== "comments").map(n => node[n]); + + if (!childNodes) { + return; + } + + if (!resultArray) { + Object.defineProperty(node, childNodesCacheKey, { + value: resultArray = [], + enumerable: false + }); + } + + childNodes.forEach(childNode => { + getSortedChildNodes(childNode, options, resultArray); + }); + return resultArray; +} // As efficiently as possible, decorate the comment object with +// .precedingNode, .enclosingNode, and/or .followingNode properties, at +// least one of which is guaranteed to be defined. + + +function decorateComment(node, comment, options) { + const { + locStart, + locEnd + } = options; + const childNodes = getSortedChildNodes(node, options); + let precedingNode; + let followingNode; // Time to dust off the old binary search robes and wizard hat. + + let left = 0; + let right = childNodes.length; + + while (left < right) { + const middle = left + right >> 1; + const child = childNodes[middle]; + + if (locStart(child) - locStart(comment) <= 0 && locEnd(comment) - locEnd(child) <= 0) { + // The comment is completely contained by this child node. + comment.enclosingNode = child; + decorateComment(child, comment, options); + return; // Abandon the binary search at this level. + } + + if (locEnd(child) - locStart(comment) <= 0) { + // This child node falls completely before the comment. + // Because we will never consider this node or any nodes + // before it again, this node must be the closest preceding + // node we have encountered so far. + precedingNode = child; + left = middle + 1; + continue; + } + + if (locEnd(comment) - locStart(child) <= 0) { + // This child node falls completely after the comment. + // Because we will never consider this node or any nodes after + // it again, this node must be the closest following node we + // have encountered so far. + followingNode = child; + right = middle; + continue; + } + /* istanbul ignore next */ + + + throw new Error("Comment location overlaps with node location"); + } // We don't want comments inside of different expressions inside of the same + // template literal to move to another expression. + + + if (comment.enclosingNode && comment.enclosingNode.type === "TemplateLiteral") { + const { + quasis + } = comment.enclosingNode; + const commentIndex = findExpressionIndexForComment(quasis, comment, options); + + if (precedingNode && findExpressionIndexForComment(quasis, precedingNode, options) !== commentIndex) { + precedingNode = null; + } + + if (followingNode && findExpressionIndexForComment(quasis, followingNode, options) !== commentIndex) { + followingNode = null; + } + } + + if (precedingNode) { + comment.precedingNode = precedingNode; + } + + if (followingNode) { + comment.followingNode = followingNode; + } +} + +function attach(comments, ast, text, options) { + if (!Array.isArray(comments)) { + return; + } + + const tiesToBreak = []; + const { + locStart, + locEnd + } = options; + comments.forEach((comment, i) => { + if (options.parser === "json" || options.parser === "json5" || options.parser === "__js_expression" || options.parser === "__vue_expression") { + if (locStart(comment) - locStart(ast) <= 0) { + addLeadingComment$1(ast, comment); + return; + } + + if (locEnd(comment) - locEnd(ast) >= 0) { + addTrailingComment$1(ast, comment); + return; + } + } + + decorateComment(ast, comment, options); + const { + precedingNode, + enclosingNode, + followingNode + } = comment; + const pluginHandleOwnLineComment = options.printer.handleComments && options.printer.handleComments.ownLine ? options.printer.handleComments.ownLine : () => false; + const pluginHandleEndOfLineComment = options.printer.handleComments && options.printer.handleComments.endOfLine ? options.printer.handleComments.endOfLine : () => false; + const pluginHandleRemainingComment = options.printer.handleComments && options.printer.handleComments.remaining ? options.printer.handleComments.remaining : () => false; + const isLastComment = comments.length - 1 === i; + + if (hasNewline$1(text, locStart(comment), { + backwards: true + })) { + // If a comment exists on its own line, prefer a leading comment. + // We also need to check if it's the first line of the file. + if (pluginHandleOwnLineComment(comment, text, options, ast, isLastComment)) ; else if (followingNode) { + // Always a leading comment. + addLeadingComment$1(followingNode, comment); + } else if (precedingNode) { + addTrailingComment$1(precedingNode, comment); + } else if (enclosingNode) { + addDanglingComment$1(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment$1(ast, comment); + } + } else if (hasNewline$1(text, locEnd(comment))) { + if (pluginHandleEndOfLineComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode) { + // There is content before this comment on the same line, but + // none after it, so prefer a trailing comment of the previous node. + addTrailingComment$1(precedingNode, comment); + } else if (followingNode) { + addLeadingComment$1(followingNode, comment); + } else if (enclosingNode) { + addDanglingComment$1(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment$1(ast, comment); + } + } else { + if (pluginHandleRemainingComment(comment, text, options, ast, isLastComment)) ; else if (precedingNode && followingNode) { + // Otherwise, text exists both before and after the comment on + // the same line. If there is both a preceding and following + // node, use a tie-breaking algorithm to determine if it should + // be attached to the next or previous node. In the last case, + // simply attach the right node; + const tieCount = tiesToBreak.length; + + if (tieCount > 0) { + const lastTie = tiesToBreak[tieCount - 1]; + + if (lastTie.followingNode !== comment.followingNode) { + breakTies(tiesToBreak, text, options); + } + } + + tiesToBreak.push(comment); + } else if (precedingNode) { + addTrailingComment$1(precedingNode, comment); + } else if (followingNode) { + addLeadingComment$1(followingNode, comment); + } else if (enclosingNode) { + addDanglingComment$1(enclosingNode, comment); + } else { + // There are no nodes, let's attach it to the root of the ast + + /* istanbul ignore next */ + addDanglingComment$1(ast, comment); + } + } + }); + breakTies(tiesToBreak, text, options); + comments.forEach(comment => { + // These node references were useful for breaking ties, but we + // don't need them anymore, and they create cycles in the AST that + // may lead to infinite recursion if we don't delete them here. + delete comment.precedingNode; + delete comment.enclosingNode; + delete comment.followingNode; + }); +} + +function breakTies(tiesToBreak, text, options) { + const tieCount = tiesToBreak.length; + + if (tieCount === 0) { + return; + } + + const { + precedingNode, + followingNode, + enclosingNode + } = tiesToBreak[0]; + const gapRegExp = options.printer.getGapRegex && options.printer.getGapRegex(enclosingNode) || /^[\s(]*$/; + let gapEndPos = options.locStart(followingNode); // Iterate backwards through tiesToBreak, examining the gaps + // between the tied comments. In order to qualify as leading, a + // comment must be separated from followingNode by an unbroken series of + // gaps (or other comments). Gaps should only contain whitespace or open + // parentheses. + + let indexOfFirstLeadingComment; + + for (indexOfFirstLeadingComment = tieCount; indexOfFirstLeadingComment > 0; --indexOfFirstLeadingComment) { + const comment = tiesToBreak[indexOfFirstLeadingComment - 1]; + assert__default['default'].strictEqual(comment.precedingNode, precedingNode); + assert__default['default'].strictEqual(comment.followingNode, followingNode); + const gap = text.slice(options.locEnd(comment), gapEndPos); + + if (gapRegExp.test(gap)) { + gapEndPos = options.locStart(comment); + } else { + // The gap string contained something other than whitespace or open + // parentheses. + break; + } + } + + tiesToBreak.forEach((comment, i) => { + if (i < indexOfFirstLeadingComment) { + addTrailingComment$1(precedingNode, comment); + } else { + addLeadingComment$1(followingNode, comment); + } + }); + + for (const node of [precedingNode, followingNode]) { + if (node.comments && node.comments.length > 1) { + node.comments.sort((a, b) => options.locStart(a) - options.locStart(b)); + } + } + + tiesToBreak.length = 0; +} + +function printComment(commentPath, options) { + const comment = commentPath.getValue(); + comment.printed = true; + return options.printer.printComment(commentPath, options); +} + +function findExpressionIndexForComment(quasis, comment, options) { + const startPos = options.locStart(comment) - 1; + + for (let i = 1; i < quasis.length; ++i) { + if (startPos < options.locStart(quasis[i])) { + return i - 1; + } + } // We haven't found it, it probably means that some of the locations are off. + // Let's just return the first one. + + /* istanbul ignore next */ + + + return 0; +} + +function printLeadingComment(commentPath, options) { + const comment = commentPath.getValue(); + const contents = printComment(commentPath, options); + /* istanbul ignore next */ + + if (!contents) { + return ""; + } + + const isBlock = options.printer.isBlockComment && options.printer.isBlockComment(comment); // Leading block comments should see if they need to stay on the + // same line or not. + + if (isBlock) { + const lineBreak = hasNewline$1(options.originalText, options.locEnd(comment)) ? hasNewline$1(options.originalText, options.locStart(comment), { + backwards: true + }) ? hardline$1 : line$1 : " "; + return concat$3([contents, lineBreak]); + } + + return concat$3([contents, hardline$1]); +} + +function printTrailingComment(commentPath, options) { + const comment = commentPath.getValue(); + const contents = printComment(commentPath, options); + /* istanbul ignore next */ + + if (!contents) { + return ""; + } + + const { + printer, + originalText, + locStart + } = options; + const isBlock = printer.isBlockComment && printer.isBlockComment(comment); + + if (hasNewline$1(originalText, locStart(comment), { + backwards: true + })) { + // This allows comments at the end of nested structures: + // { + // x: 1, + // y: 2 + // // A comment + // } + // Those kinds of comments are almost always leading comments, but + // here it doesn't go "outside" the block and turns it into a + // trailing comment for `2`. We can simulate the above by checking + // if this a comment on its own line; normal trailing comments are + // always at the end of another expression. + const isLineBeforeEmpty = isPreviousLineEmpty$1(originalText, comment, locStart); + return lineSuffix$1(concat$3([hardline$1, isLineBeforeEmpty ? hardline$1 : "", contents])); + } + + let printed = concat$3([" ", contents]); // Trailing block comments never need a newline + + if (!isBlock) { + printed = concat$3([lineSuffix$1(printed), breakParent$1]); + } + + return printed; +} + +function printDanglingComments(path, options, sameIndent, filter) { + const parts = []; + const node = path.getValue(); + + if (!node || !node.comments) { + return ""; + } + + path.each(commentPath => { + const comment = commentPath.getValue(); + + if (comment && !comment.leading && !comment.trailing && (!filter || filter(comment))) { + parts.push(printComment(commentPath, options)); + } + }, "comments"); + + if (parts.length === 0) { + return ""; + } + + if (sameIndent) { + return join$1(hardline$1, parts); + } + + return indent$1(concat$3([hardline$1, join$1(hardline$1, parts)])); +} + +function prependCursorPlaceholder(path, options, printed) { + if (path.getNode() === options.cursorNode && path.getValue()) { + return concat$3([cursor$2, printed, cursor$2]); + } + + return printed; +} + +function printComments(path, print, options, needsSemi) { + const value = path.getValue(); + const printed = print(path); + const comments = value && value.comments; + + if (!comments || comments.length === 0) { + return prependCursorPlaceholder(path, options, printed); + } + + const leadingParts = []; + const trailingParts = [needsSemi ? ";" : "", printed]; + path.each(commentPath => { + const comment = commentPath.getValue(); + const { + leading, + trailing + } = comment; + + if (leading) { + const contents = printLeadingComment(commentPath, options); + /* istanbul ignore next */ + + if (!contents) { + return; + } + + leadingParts.push(contents); + const text = options.originalText; + const index = skipNewline$1(text, skipSpaces$1(text, options.locEnd(comment))); + + if (index !== false && hasNewline$1(text, index)) { + leadingParts.push(hardline$1); + } + } else if (trailing) { + trailingParts.push(printTrailingComment(commentPath, options)); + } + }, "comments"); + return prependCursorPlaceholder(path, options, concat$3(leadingParts.concat(trailingParts))); +} + +function ensureAllCommentsPrinted(astComments) { + if (!astComments) { + return; + } + + astComments.forEach(comment => { + if (!comment.printed) { + throw new Error('Comment "' + comment.value.trim() + '" was not printed. Please report this error!'); + } + + delete comment.printed; + }); +} + +var comments = { + attach, + printComments, + printDanglingComments, + getSortedChildNodes, + ensureAllCommentsPrinted +}; + +function getNodeHelper(path, count) { + const stackIndex = getNodeStackIndexHelper(path.stack, count); + return stackIndex === -1 ? null : path.stack[stackIndex]; +} + +function getNodeStackIndexHelper(stack, count) { + for (let i = stack.length - 1; i >= 0; i -= 2) { + const value = stack[i]; + + if (value && !Array.isArray(value) && --count < 0) { + return i; + } + } + + return -1; +} + +class FastPath { + constructor(value) { + this.stack = [value]; + } // The name of the current property is always the penultimate element of + // this.stack, and always a String. + + + getName() { + const { + stack + } = this; + const { + length + } = stack; + + if (length > 1) { + return stack[length - 2]; + } // Since the name is always a string, null is a safe sentinel value to + // return if we do not know the name of the (root) value. + + /* istanbul ignore next */ + + + return null; + } // The value of the current property is always the final element of + // this.stack. + + + getValue() { + return getLast(this.stack); + } + + getNode(count = 0) { + return getNodeHelper(this, count); + } + + getParentNode(count = 0) { + return getNodeHelper(this, count + 1); + } // Temporarily push properties named by string arguments given after the + // callback function onto this.stack, then call the callback with a + // reference to this (modified) FastPath object. Note that the stack will + // be restored to its original state after the callback is finished, so it + // is probably a mistake to retain a reference to the path. + + + call(callback, ...names) { + const { + stack + } = this; + const { + length + } = stack; + let value = getLast(stack); + + for (const name of names) { + value = value[name]; + stack.push(name, value); + } + + const result = callback(this); + stack.length = length; + return result; + } + + callParent(callback, count = 0) { + const stackIndex = getNodeStackIndexHelper(this.stack, count + 1); + const parentValues = this.stack.splice(stackIndex + 1); + const result = callback(this); + this.stack.push(...parentValues); + return result; + } // Similar to FastPath.prototype.call, except that the value obtained by + // accessing this.getValue()[name1][name2]... should be array-like. The + // callback will be called with a reference to this path object for each + // element of the array. + + + each(callback, ...names) { + const { + stack + } = this; + const { + length + } = stack; + let value = getLast(stack); + + for (const name of names) { + value = value[name]; + stack.push(name, value); + } + + for (let i = 0; i < value.length; ++i) { + if (i in value) { + stack.push(i, value[i]); // If the callback needs to know the value of i, call + // path.getName(), assuming path is the parameter name. + + callback(this); + stack.length -= 2; + } + } + + stack.length = length; + } // Similar to FastPath.prototype.each, except that the results of the + // callback function invocations are stored in an array and returned at + // the end of the iteration. + + + map(callback, ...names) { + const { + stack + } = this; + const { + length + } = stack; + let value = getLast(stack); + + for (const name of names) { + value = value[name]; + stack.push(name, value); + } + + const result = new Array(value.length); + + for (let i = 0; i < value.length; ++i) { + if (i in value) { + stack.push(i, value[i]); + result[i] = callback(this, i); + stack.length -= 2; + } + } + + stack.length = length; + return result; + } + /** + * @param {...( + * | ((node: any, name: string | null, number: number | null) => boolean) + * | undefined + * )} predicates + */ + + + match(...predicates) { + let stackPointer = this.stack.length - 1; + let name = null; + let node = this.stack[stackPointer--]; + + for (const predicate of predicates) { + /* istanbul ignore next */ + if (node === undefined) { + return false; + } // skip index/array + + + let number = null; + + if (typeof name === "number") { + number = name; + name = this.stack[stackPointer--]; + node = this.stack[stackPointer--]; + } + + if (predicate && !predicate(node, name, number)) { + return false; + } + + name = this.stack[stackPointer--]; + node = this.stack[stackPointer--]; + } + + return true; + } + +} + +var fastPath = FastPath; + +const { + utils: { + stripTrailingHardline: stripTrailingHardline$1 + } +} = document; +const { + normalize: normalize$2 +} = options$1; + +function printSubtree(path, print, options, printAstToDoc) { + if (options.printer.embed && options.embeddedLanguageFormatting === "auto") { + return options.printer.embed(path, print, (text, partialNextOptions, textToDocOptions) => textToDoc(text, partialNextOptions, options, printAstToDoc, textToDocOptions), options); + } +} + +function textToDoc(text, partialNextOptions, parentOptions, printAstToDoc, // TODO: remove `stripTrailingHardline` in v3.0.0 +{ + stripTrailingHardline: shouldStripTrailingHardline = false +} = {}) { + const nextOptions = normalize$2(Object.assign({}, parentOptions, partialNextOptions, { + parentParser: parentOptions.parser, + embeddedInHtml: !!(parentOptions.embeddedInHtml || parentOptions.parser === "html" || parentOptions.parser === "vue" || parentOptions.parser === "angular" || parentOptions.parser === "lwc"), + originalText: text + }), { + passThrough: true + }); + const result = parser.parse(text, nextOptions); + const { + ast + } = result; + text = result.text; + const astComments = ast.comments; + delete ast.comments; + comments.attach(astComments, ast, text, nextOptions); + nextOptions[Symbol.for("comments")] = astComments || []; + nextOptions[Symbol.for("tokens")] = ast.tokens || []; + const doc = printAstToDoc(ast, nextOptions); + comments.ensureAllCommentsPrinted(astComments); + + if (shouldStripTrailingHardline) { + // TODO: move this to `stripTrailingHardline` function in `/src/document/doc-utils.js` + if (typeof doc === "string") { + return doc.replace(/(?:\r?\n)*$/, ""); + } + + return stripTrailingHardline$1(doc, true); + } + /* istanbul ignore next */ + + + return doc; +} + +var multiparser = { + printSubtree +}; + +const doc = document; +const docBuilders$1 = doc.builders; +const { + concat: concat$4, + hardline: hardline$2, + addAlignmentToDoc: addAlignmentToDoc$1 +} = docBuilders$1; +const docUtils$1 = doc.utils; +/** + * Takes an abstract syntax tree (AST) and recursively converts it to a + * document (series of printing primitives). + * + * This is done by descending down the AST recursively. The recursion + * involves two functions that call each other: + * + * 1. printGenerically(), which is defined as an inner function here. + * It basically takes care of node caching. + * 2. callPluginPrintFunction(), which checks for some options, and + * ultimately calls the print() function provided by the plugin. + * + * The plugin function will call printGenerically() again for child nodes + * of the current node, which will do its housekeeping, then call the + * plugin function again, and so on. + * + * All the while, these functions pass a "path" variable around, which + * is a stack-like data structure (FastPath) that maintains the current + * state of the recursion. It is called "path", because it represents + * the path to the current node through the Abstract Syntax Tree. + */ + +function printAstToDoc(ast, options, alignmentSize = 0) { + const { + printer + } = options; + + if (printer.preprocess) { + ast = printer.preprocess(ast, options); + } + + const cache = new Map(); + + function printGenerically(path, args) { + const node = path.getValue(); + const shouldCache = node && typeof node === "object" && args === undefined; + + if (shouldCache && cache.has(node)) { + return cache.get(node); + } // We let JSXElement print its comments itself because it adds () around + // UnionTypeAnnotation has to align the child without the comments + + + let res; + + if (printer.willPrintOwnComments && printer.willPrintOwnComments(path, options)) { + res = callPluginPrintFunction(path, options, printGenerically, args); + } else { + // printComments will call the plugin print function and check for + // comments to print + res = comments.printComments(path, p => callPluginPrintFunction(p, options, printGenerically, args), options, args && args.needsSemi); + } + + if (shouldCache) { + cache.set(node, res); + } + + return res; + } + + let doc = printGenerically(new fastPath(ast)); + + if (alignmentSize > 0) { + // Add a hardline to make the indents take effect + // It should be removed in index.js format() + doc = addAlignmentToDoc$1(concat$4([hardline$2, doc]), alignmentSize, options.tabWidth); + } + + docUtils$1.propagateBreaks(doc); + return doc; +} + +function printPrettierIgnoredNode(node, options) { + const { + originalText, + [Symbol.for("comments")]: comments, + locStart, + locEnd + } = options; + const start = locStart(node); + const end = locEnd(node); + + for (const comment of comments) { + if (locStart(comment) >= start && locEnd(comment) <= end) { + comment.printed = true; + } + } + + return originalText.slice(start, end); +} + +function callPluginPrintFunction(path, options, printPath, args) { + assert__default['default'].ok(path instanceof fastPath); + const node = path.getValue(); + const { + printer + } = options; // Escape hatch + + if (printer.hasPrettierIgnore && printer.hasPrettierIgnore(path)) { + return printPrettierIgnoredNode(node, options); + } + + if (node) { + try { + // Potentially switch to a different parser + const sub = multiparser.printSubtree(path, printPath, options, printAstToDoc); + + if (sub) { + return sub; + } + } catch (error) { + /* istanbul ignore if */ + if (process.env.PRETTIER_DEBUG) { + throw error; + } // Continue with current parser + + } + } + + return printer.print(path, options, printPath, args); +} + +var astToDoc = printAstToDoc; + +function findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts) { + let resultStartNode = startNodeAndParents.node; + let resultEndNode = endNodeAndParents.node; + + if (resultStartNode === resultEndNode) { + return { + startNode: resultStartNode, + endNode: resultEndNode + }; + } + + for (const endParent of endNodeAndParents.parentNodes) { + if (endParent.type !== "Program" && endParent.type !== "File" && opts.locStart(endParent) >= opts.locStart(startNodeAndParents.node)) { + resultEndNode = endParent; + } else { + break; + } + } + + for (const startParent of startNodeAndParents.parentNodes) { + if (startParent.type !== "Program" && startParent.type !== "File" && opts.locEnd(startParent) <= opts.locEnd(endNodeAndParents.node)) { + resultStartNode = startParent; + } else { + break; + } + } + + return { + startNode: resultStartNode, + endNode: resultEndNode + }; +} + +function findNodeAtOffset(node, offset, options, predicate, parentNodes = []) { + if (offset < options.locStart(node) || offset > options.locEnd(node)) { + return; + } + + for (const childNode of comments.getSortedChildNodes(node, options)) { + const childResult = findNodeAtOffset(childNode, offset, options, predicate, [node, ...parentNodes]); + + if (childResult) { + return childResult; + } + } + + if (!predicate || predicate(node)) { + return { + node, + parentNodes + }; + } +} // See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 + + +function isJsSourceElement(type) { + return type === "Directive" || type === "TypeAlias" || type === "TSExportAssignment" || type.startsWith("Declare") || type.startsWith("TSDeclare") || type.endsWith("Statement") || type.endsWith("Declaration"); +} + +const jsonSourceElements = new Set(["ObjectExpression", "ArrayExpression", "StringLiteral", "NumericLiteral", "BooleanLiteral", "NullLiteral"]); +const graphqlSourceElements = new Set(["OperationDefinition", "FragmentDefinition", "VariableDefinition", "TypeExtensionDefinition", "ObjectTypeDefinition", "FieldDefinition", "DirectiveDefinition", "EnumTypeDefinition", "EnumValueDefinition", "InputValueDefinition", "InputObjectTypeDefinition", "SchemaDefinition", "OperationTypeDefinition", "InterfaceTypeDefinition", "UnionTypeDefinition", "ScalarTypeDefinition"]); + +function isSourceElement(opts, node) { + /* istanbul ignore next */ + if (node == null) { + return false; + } + + switch (opts.parser) { + case "flow": + case "babel": + case "babel-flow": + case "babel-ts": + case "typescript": + return isJsSourceElement(node.type); + + case "json": + return jsonSourceElements.has(node.type); + + case "graphql": + return graphqlSourceElements.has(node.kind); + + case "vue": + return node.tag !== "root"; + } + + return false; +} + +function calculateRange(text, opts, ast) { + // Contract the range so that it has non-whitespace characters at its endpoints. + // This ensures we can format a range that doesn't end on a node. + const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd); + const startNonWhitespace = Math.max(opts.rangeStart + rangeStringOrig.search(/\S/), opts.rangeStart); + let endNonWhitespace; + + for (endNonWhitespace = opts.rangeEnd; endNonWhitespace > opts.rangeStart; --endNonWhitespace) { + if (/\S/.test(text[endNonWhitespace - 1])) { + break; + } + } + + const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace, opts, node => isSourceElement(opts, node)); + const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace, opts, node => isSourceElement(opts, node)); + + if (!startNodeAndParents || !endNodeAndParents) { + return { + rangeStart: 0, + rangeEnd: 0 + }; + } + + const { + startNode, + endNode + } = findSiblingAncestors(startNodeAndParents, endNodeAndParents, opts); + return { + rangeStart: Math.min(opts.locStart(startNode), opts.locStart(endNode)), + rangeEnd: Math.max(opts.locEnd(startNode), opts.locEnd(endNode)) + }; +} + +var rangeUtil = { + calculateRange, + findNodeAtOffset +}; + +const { + printer: { + printDocToString: printDocToString$1 + }, + debug: { + printDocToDebug + } +} = document; +const { + getAlignmentSize: getAlignmentSize$1 +} = util; +const { + guessEndOfLine: guessEndOfLine$1, + convertEndOfLineToChars: convertEndOfLineToChars$2, + countEndOfLineChars: countEndOfLineChars$1, + normalizeEndOfLine: normalizeEndOfLine$1 +} = endOfLine; +const normalizeOptions$1 = options$1.normalize; +const BOM = "\uFEFF"; +const CURSOR = Symbol("cursor"); + +function attachComments(text, ast, opts) { + const astComments = ast.comments; + + if (astComments) { + delete ast.comments; + comments.attach(astComments, ast, text, opts); + } + + opts[Symbol.for("comments")] = astComments || []; + opts[Symbol.for("tokens")] = ast.tokens || []; + opts.originalText = text; + return astComments; +} + +function coreFormat(text, opts, addAlignmentSize) { + if (!text || !text.trim().length) { + return { + formatted: "", + cursorOffset: -1 + }; + } + + addAlignmentSize = addAlignmentSize || 0; + const parsed = parser.parse(text, opts); + const { + ast + } = parsed; + text = parsed.text; + + if (opts.cursorOffset >= 0) { + const nodeResult = rangeUtil.findNodeAtOffset(ast, opts.cursorOffset, opts); + + if (nodeResult && nodeResult.node) { + opts.cursorNode = nodeResult.node; + } + } + + const astComments = attachComments(text, ast, opts); + const doc = astToDoc(ast, opts, addAlignmentSize); + const result = printDocToString$1(doc, opts); + comments.ensureAllCommentsPrinted(astComments); // Remove extra leading indentation as well as the added indentation after last newline + + if (addAlignmentSize > 0) { + const trimmed = result.formatted.trim(); + + if (result.cursorNodeStart !== undefined) { + result.cursorNodeStart -= result.formatted.indexOf(trimmed); + } + + result.formatted = trimmed + convertEndOfLineToChars$2(opts.endOfLine); + } + + if (opts.cursorOffset >= 0) { + let oldCursorNodeStart; + let oldCursorNodeText; + let cursorOffsetRelativeToOldCursorNode; + let newCursorNodeStart; + let newCursorNodeText; + + if (opts.cursorNode && result.cursorNodeText) { + oldCursorNodeStart = opts.locStart(opts.cursorNode); + oldCursorNodeText = text.slice(oldCursorNodeStart, opts.locEnd(opts.cursorNode)); + cursorOffsetRelativeToOldCursorNode = opts.cursorOffset - oldCursorNodeStart; + newCursorNodeStart = result.cursorNodeStart; + newCursorNodeText = result.cursorNodeText; + } else { + oldCursorNodeStart = 0; + oldCursorNodeText = text; + cursorOffsetRelativeToOldCursorNode = opts.cursorOffset; + newCursorNodeStart = 0; + newCursorNodeText = result.formatted; + } + + if (oldCursorNodeText === newCursorNodeText) { + return { + formatted: result.formatted, + cursorOffset: newCursorNodeStart + cursorOffsetRelativeToOldCursorNode + }; + } // diff old and new cursor node texts, with a special cursor + // symbol inserted to find out where it moves to + + + const oldCursorNodeCharArray = oldCursorNodeText.split(""); + oldCursorNodeCharArray.splice(cursorOffsetRelativeToOldCursorNode, 0, CURSOR); + const newCursorNodeCharArray = newCursorNodeText.split(""); + const cursorNodeDiff = index_es6.diffArrays(oldCursorNodeCharArray, newCursorNodeCharArray); + let cursorOffset = newCursorNodeStart; + + for (const entry of cursorNodeDiff) { + if (entry.removed) { + if (entry.value.includes(CURSOR)) { + break; + } + } else { + cursorOffset += entry.count; + } + } + + return { + formatted: result.formatted, + cursorOffset + }; + } + + return { + formatted: result.formatted, + cursorOffset: -1 + }; +} + +function formatRange(text, opts) { + const parsed = parser.parse(text, opts); + const { + ast + } = parsed; + text = parsed.text; + const { + rangeStart, + rangeEnd + } = rangeUtil.calculateRange(text, opts, ast); + const rangeString = text.slice(rangeStart, rangeEnd); // Try to extend the range backwards to the beginning of the line. + // This is so we can detect indentation correctly and restore it. + // Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0 + + const rangeStart2 = Math.min(rangeStart, text.lastIndexOf("\n", rangeStart) + 1); + const indentString = text.slice(rangeStart2, rangeStart).match(/^\s*/)[0]; + const alignmentSize = getAlignmentSize$1(indentString, opts.tabWidth); + const rangeResult = coreFormat(rangeString, Object.assign({}, opts, { + rangeStart: 0, + rangeEnd: Infinity, + // Track the cursor offset only if it's within our range + cursorOffset: opts.cursorOffset > rangeStart && opts.cursorOffset < rangeEnd ? opts.cursorOffset - rangeStart : -1, + // Always use `lf` to format, we'll replace it later + endOfLine: "lf" + }), alignmentSize); // Since the range contracts to avoid trailing whitespace, + // we need to remove the newline that was inserted by the `format` call. + + const rangeTrimmed = rangeResult.formatted.trimEnd(); + let { + cursorOffset + } = opts; + + if (cursorOffset >= rangeEnd) { + // handle the case where the cursor was past the end of the range + cursorOffset = opts.cursorOffset + (rangeTrimmed.length - rangeString.length); + } else if (rangeResult.cursorOffset >= 0) { + // handle the case where the cursor was in the range + cursorOffset = rangeResult.cursorOffset + rangeStart; + } // keep the cursor as it was if it was before the start of the range + + + let formatted = text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd); + + if (opts.endOfLine !== "lf") { + const eol = convertEndOfLineToChars$2(opts.endOfLine); + + if (cursorOffset >= 0 && eol === "\r\n") { + cursorOffset += countEndOfLineChars$1(formatted.slice(0, cursorOffset), "\n"); + } + + formatted = formatted.replace(/\n/g, eol); + } + + return { + formatted, + cursorOffset + }; +} + +function format(originalText, opts) { + const selectedParser = parser.resolveParser(opts); + const hasBOM = originalText.charAt(0) === BOM; + let text = hasBOM ? originalText.slice(1) : originalText; + const hasCursor = opts.cursorOffset >= 0; + + if (!hasCursor) { + opts.cursorOffset = -1; + } + + const hasPragma = !selectedParser.hasPragma || selectedParser.hasPragma(text); + + if (opts.requirePragma && !hasPragma) { + return { + formatted: originalText, + cursorOffset: opts.cursorOffset + }; + } + + if (opts.endOfLine === "auto") { + opts.endOfLine = guessEndOfLine$1(text); + } + + const hasRangeStart = opts.rangeStart > 0; + const hasRangeEnd = opts.rangeEnd < text.length; + + if (hasBOM) { + if (hasCursor) { + opts.cursorOffset--; + } + + if (hasRangeStart) { + opts.rangeStart--; + } + + if (hasRangeEnd) { + opts.rangeEnd--; + } + } // get rid of CR/CRLF parsing + + + if (text.includes("\r")) { + const countCrlfBefore = position => countEndOfLineChars$1(text.slice(0, position), "\r\n"); + + if (hasCursor) { + opts.cursorOffset -= countCrlfBefore(opts.cursorOffset); + } + + if (hasRangeStart) { + opts.rangeStart -= countCrlfBefore(opts.rangeStart); + } + + if (hasRangeEnd) { + opts.rangeEnd -= countCrlfBefore(opts.rangeEnd); + } + + text = normalizeEndOfLine$1(text); + } + + if (opts.rangeStart < 0) { + opts.rangeStart = 0; + } + + if (opts.rangeEnd > text.length) { + opts.rangeEnd = text.length; + } + + let result; + + if (hasRangeStart || hasRangeEnd) { + result = formatRange(text, opts); + } else { + if (!hasPragma && opts.insertPragma && opts.printer.insertPragma) { + text = opts.printer.insertPragma(text); + } + + result = coreFormat(text, opts); + } + + if (hasBOM) { + result.formatted = BOM + result.formatted; + + if (hasCursor && result.cursorOffset >= 0) { + result.cursorOffset++; + } + } + + return result; +} + +var core = { + formatWithCursor(text, opts) { + opts = normalizeOptions$1(opts); + return format(text, opts); + }, + + parse(text, opts, massage) { + opts = normalizeOptions$1(opts); + text = normalizeEndOfLine$1(text.charAt(0) === BOM ? text.slice(1) : text); + const parsed = parser.parse(text, opts); + + if (massage) { + parsed.ast = massageAst(parsed.ast, opts); + } + + return parsed; + }, + + formatAST(ast, opts) { + opts = normalizeOptions$1(opts); + const doc = astToDoc(ast, opts); + return printDocToString$1(doc, opts); + }, + + // Doesn't handle shebang for now + formatDoc(doc, opts) { + opts = normalizeOptions$1(Object.assign({}, opts, { + parser: "babel" + })); + const debug = printDocToDebug(doc); + return format(debug, opts).formatted; + }, + + printToDoc(originalText, opts) { + opts = normalizeOptions$1(opts); + const parsed = parser.parse(originalText, opts); + const { + ast, + text + } = parsed; + attachComments(text, ast, opts); + return astToDoc(ast, opts); + }, + + printDocToString(doc, opts) { + return printDocToString$1(doc, normalizeOptions$1(opts)); + } + +}; + +var concatMap = function (xs, fn) { + var res = []; + + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray$2(x)) res.push.apply(res, x);else res.push(x); + } + + return res; +}; + +var isArray$2 = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; + +var balancedMatch = balanced; + +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); + var r = range(a, b, str); + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; +} + +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; +} + +balanced.range = range; + +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; + + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; + + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [begs.pop(), bi]; + } else { + beg = begs.pop(); + + if (beg < left) { + left = beg; + right = bi; + } + + bi = str.indexOf(b, i + 1); + } + + i = ai < bi && ai >= 0 ? ai : bi; + } + + if (begs.length) { + result = [left, right]; + } + } + + return result; +} + +var braceExpansion = expandTop; +var escSlash = '\0SLASH' + Math.random() + '\0'; +var escOpen = '\0OPEN' + Math.random() + '\0'; +var escClose = '\0CLOSE' + Math.random() + '\0'; +var escComma = '\0COMMA' + Math.random() + '\0'; +var escPeriod = '\0PERIOD' + Math.random() + '\0'; + +function numeric$1(str) { + return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash).split('\\{').join(escOpen).split('\\}').join(escClose).split('\\,').join(escComma).split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\').split(escOpen).join('{').split(escClose).join('}').split(escComma).join(',').split(escPeriod).join('.'); +} // Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} + + +function parseCommaParts(str) { + if (!str) return ['']; + var parts = []; + var m = balancedMatch('{', '}', str); + if (!m) return str.split(','); + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + p[p.length - 1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + + if (post.length) { + p[p.length - 1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + return parts; +} + +function expandTop(str) { + if (!str) return []; // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} + +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} + +function gte$1(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + var m = balancedMatch('{', '}', str); + if (!m || /\$$/.test(m.pre)) return [str]; + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + + return [str]; + } + + var n; + + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + + if (n.length === 1) { + var post = m.post.length ? expand(m.post, false) : ['']; + return post.map(function (p) { + return m.pre + n[0] + p; + }); + } + } + } // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + // no need to expand pre, since it is guaranteed to be free of brace-sets + + + var pre = m.pre; + var post = m.post.length ? expand(m.post, false) : ['']; + var N; + + if (isSequence) { + var x = numeric$1(n[0]); + var y = numeric$1(n[1]); + var width = Math.max(n[0].length, n[1].length); + var incr = n.length == 3 ? Math.abs(numeric$1(n[2])) : 1; + var test = lte; + var reverse = y < x; + + if (reverse) { + incr *= -1; + test = gte$1; + } + + var pad = n.some(isPadded); + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') c = ''; + } else { + c = String(i); + + if (pad) { + var need = width - c.length; + + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) c = '-' + z + c.slice(1);else c = z + c; + } + } + } + + N.push(c); + } + } else { + N = concatMap(n, function (el) { + return expand(el, false); + }); + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) expansions.push(expansion); + } + } + + return expansions; +} + +var minimatch_1 = minimatch; +minimatch.Minimatch = Minimatch; +var path = { + sep: '/' +}; + +try { + path = path__default['default']; +} catch (er) {} + +var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; +var plTypes = { + '!': { + open: '(?:(?!(?:', + close: '))[^/]*?)' + }, + '?': { + open: '(?:', + close: ')?' + }, + '+': { + open: '(?:', + close: ')+' + }, + '*': { + open: '(?:', + close: ')*' + }, + '@': { + open: '(?:', + close: ')' + } +}; // any single thing other than / +// don't need to escape / when using new RegExp() + +var qmark = '[^/]'; // * => any number of characters + +var star = qmark + '*?'; // ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. + +var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'; // not a ^ or / followed by a dot, +// followed by anything, any number of times. + +var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'; // characters that need to be escaped in RegExp. + +var reSpecials = charSet('().*{}+?[]^$\\!'); // "abc" -> { a:true, b:true, c:true } + +function charSet(s) { + return s.split('').reduce(function (set, c) { + set[c] = true; + return set; + }, {}); +} // normalizes slashes. + + +var slashSplit = /\/+/; +minimatch.filter = filter; + +function filter(pattern, options) { + options = options || {}; + return function (p, i, list) { + return minimatch(p, pattern, options); + }; +} + +function ext(a, b) { + a = a || {}; + b = b || {}; + var t = {}; + Object.keys(b).forEach(function (k) { + t[k] = b[k]; + }); + Object.keys(a).forEach(function (k) { + t[k] = a[k]; + }); + return t; +} + +minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch; + var orig = minimatch; + + var m = function minimatch(p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)); + }; + + m.Minimatch = function Minimatch(pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)); + }; + + return m; +}; + +Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch; + return minimatch.defaults(def).Minimatch; +}; + +function minimatch(p, pattern, options) { + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required'); + } + + if (!options) options = {}; // shortcut: comments match nothing. + + if (!options.nocomment && pattern.charAt(0) === '#') { + return false; + } // "" only matches "" + + + if (pattern.trim() === '') return p === ''; + return new Minimatch(pattern, options).match(p); +} + +function Minimatch(pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options); + } + + if (typeof pattern !== 'string') { + throw new TypeError('glob pattern string required'); + } + + if (!options) options = {}; + pattern = pattern.trim(); // windows support: need to use /, not \ + + if (path.sep !== '/') { + pattern = pattern.split(path.sep).join('/'); + } + + this.options = options; + this.set = []; + this.pattern = pattern; + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; // make the set of regexps etc. + + this.make(); +} + +Minimatch.prototype.debug = function () {}; + +Minimatch.prototype.make = make; + +function make() { + // don't do it more than once. + if (this._made) return; + var pattern = this.pattern; + var options = this.options; // empty patterns and comments match nothing. + + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true; + return; + } + + if (!pattern) { + this.empty = true; + return; + } // step 1: figure out negation, etc. + + + this.parseNegate(); // step 2: expand braces + + var set = this.globSet = this.braceExpand(); + if (options.debug) this.debug = console.error; + this.debug(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + + set = this.globParts = set.map(function (s) { + return s.split(slashSplit); + }); + this.debug(this.pattern, set); // glob --> regexps + + set = set.map(function (s, si, set) { + return s.map(this.parse, this); + }, this); + this.debug(this.pattern, set); // filter out everything that didn't compile properly. + + set = set.filter(function (s) { + return s.indexOf(false) === -1; + }); + this.debug(this.pattern, set); + this.set = set; +} + +Minimatch.prototype.parseNegate = parseNegate; + +function parseNegate() { + var pattern = this.pattern; + var negate = false; + var options = this.options; + var negateOffset = 0; + if (options.nonegate) return; + + for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === '!'; i++) { + negate = !negate; + negateOffset++; + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset); + this.negate = negate; +} // Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c + + +minimatch.braceExpand = function (pattern, options) { + return braceExpand(pattern, options); +}; + +Minimatch.prototype.braceExpand = braceExpand; + +function braceExpand(pattern, options) { + if (!options) { + if (this instanceof Minimatch) { + options = this.options; + } else { + options = {}; + } + } + + pattern = typeof pattern === 'undefined' ? this.pattern : pattern; + + if (typeof pattern === 'undefined') { + throw new TypeError('undefined pattern'); + } + + if (options.nobrace || !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern]; + } + + return braceExpansion(pattern); +} // parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. + + +Minimatch.prototype.parse = parse$1; +var SUBPARSE = {}; + +function parse$1(pattern, isSub) { + if (pattern.length > 1024 * 64) { + throw new TypeError('pattern is too long'); + } + + var options = this.options; // shortcuts + + if (!options.noglobstar && pattern === '**') return GLOBSTAR; + if (pattern === '') return ''; + var re = ''; + var hasMagic = !!options.nocase; + var escaping = false; // ? => one single character + + var patternListStack = []; + var negativeLists = []; + var stateChar; + var inClass = false; + var reClassStart = -1; + var classStart = -1; // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + + var patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' : '(?!\\.)'; + var self = this; + + function clearStateChar() { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star; + hasMagic = true; + break; + + case '?': + re += qmark; + hasMagic = true; + break; + + default: + re += '\\' + stateChar; + break; + } + + self.debug('clearStateChar %j %j', stateChar, re); + stateChar = false; + } + } + + for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c); // skip over any that are escaped. + + if (escaping && reSpecials[c]) { + re += '\\' + c; + escaping = false; + continue; + } + + switch (c) { + case '/': + // completely not allowed, even escaped. + // Should already be path-split by now. + return false; + + case '\\': + clearStateChar(); + escaping = true; + continue; + // the various stateChar values + // for the "extglob" stuff. + + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c); // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + + if (inClass) { + this.debug(' in class'); + if (c === '!' && i === classStart + 1) c = '^'; + re += c; + continue; + } // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + + + self.debug('call clearStateChar %j', stateChar); + clearStateChar(); + stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + + if (options.noext) clearStateChar(); + continue; + + case '(': + if (inClass) { + re += '('; + continue; + } + + if (!stateChar) { + re += '\\('; + continue; + } + + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }); // negation is (?:(?!js)[^/]*) + + re += stateChar === '!' ? '(?:(?!(?:' : '(?:'; + this.debug('plType %j %j', stateChar, re); + stateChar = false; + continue; + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)'; + continue; + } + + clearStateChar(); + hasMagic = true; + var pl = patternListStack.pop(); // negation is (?:(?!js)[^/]*) + // The others are (?:) + + re += pl.close; + + if (pl.type === '!') { + negativeLists.push(pl); + } + + pl.reEnd = re.length; + continue; + + case '|': + if (inClass || !patternListStack.length || escaping) { + re += '\\|'; + escaping = false; + continue; + } + + clearStateChar(); + re += '|'; + continue; + // these are mostly the same in regexp and glob + + case '[': + // swallow any state-tracking char before the [ + clearStateChar(); + + if (inClass) { + re += '\\' + c; + continue; + } + + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue; + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c; + escaping = false; + continue; + } // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" + + + if (inClass) { + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + var cs = pattern.substring(classStart + 1, i); + + try { + RegExp('[' + cs + ']'); + } catch (er) { + // not a valid class! + var sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'; + hasMagic = hasMagic || sp[1]; + inClass = false; + continue; + } + } // finish up the class. + + + hasMagic = true; + inClass = false; + re += c; + continue; + + default: + // swallow any state char that wasn't consumed + clearStateChar(); + + if (escaping) { + // no need + escaping = false; + } else if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\'; + } + + re += c; + } // switch + + } // for + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + + + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1); + sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + '\\[' + sp[0]; + hasMagic = hasMagic || sp[1]; + } // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + + + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + pl.open.length); + this.debug('setting tail', re, pl); // maybe some even number of \, then maybe 1 \, followed by a | + + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\'; + } // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + + + return $1 + $1 + $2 + '|'; + }); + this.debug('tail=%j\n %s', tail, tail, pl, re); + var t = pl.type === '*' ? star : pl.type === '?' ? qmark : '\\' + pl.type; + hasMagic = true; + re = re.slice(0, pl.reStart) + t + '\\(' + tail; + } // handle trailing things that only matter at the very end. + + + clearStateChar(); + + if (escaping) { + // trailing \\ + re += '\\\\'; + } // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + + + var addPatternStart = false; + + switch (re.charAt(0)) { + case '.': + case '[': + case '(': + addPatternStart = true; + } // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + + + for (var n = negativeLists.length - 1; n > -1; n--) { + var nl = negativeLists[n]; + var nlBefore = re.slice(0, nl.reStart); + var nlFirst = re.slice(nl.reStart, nl.reEnd - 8); + var nlLast = re.slice(nl.reEnd - 8, nl.reEnd); + var nlAfter = re.slice(nl.reEnd); + nlLast += nlAfter; // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + + var openParensBefore = nlBefore.split('(').length - 1; + var cleanAfter = nlAfter; + + for (i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, ''); + } + + nlAfter = cleanAfter; + var dollar = ''; + + if (nlAfter === '' && isSub !== SUBPARSE) { + dollar = '$'; + } + + var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast; + re = newRe; + } // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + + + if (re !== '' && hasMagic) { + re = '(?=.)' + re; + } + + if (addPatternStart) { + re = patternStart + re; + } // parsing just a piece of a larger pattern. + + + if (isSub === SUBPARSE) { + return [re, hasMagic]; + } // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + + + if (!hasMagic) { + return globUnescape(pattern); + } + + var flags = options.nocase ? 'i' : ''; + + try { + var regExp = new RegExp('^' + re + '$', flags); + } catch (er) { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.'); + } + + regExp._glob = pattern; + regExp._src = re; + return regExp; +} + +minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe(); +}; + +Minimatch.prototype.makeRe = makeRe; + +function makeRe() { + if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + + var set = this.set; + + if (!set.length) { + this.regexp = false; + return this.regexp; + } + + var options = this.options; + var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot; + var flags = options.nocase ? 'i' : ''; + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return p === GLOBSTAR ? twoStar : typeof p === 'string' ? regExpEscape(p) : p._src; + }).join('\\\/'); + }).join('|'); // must match entire pattern + // ending in a * or ** will make it less strict. + + re = '^(?:' + re + ')$'; // can match anything, as long as it's not this. + + if (this.negate) re = '^(?!' + re + ').*$'; + + try { + this.regexp = new RegExp(re, flags); + } catch (ex) { + this.regexp = false; + } + + return this.regexp; +} + +minimatch.match = function (list, pattern, options) { + options = options || {}; + var mm = new Minimatch(pattern, options); + list = list.filter(function (f) { + return mm.match(f); + }); + + if (mm.options.nonull && !list.length) { + list.push(pattern); + } + + return list; +}; + +Minimatch.prototype.match = match; + +function match(f, partial) { + this.debug('match', f, this.pattern); // short-circuit in the case of busted things. + // comments, etc. + + if (this.comment) return false; + if (this.empty) return f === ''; + if (f === '/' && partial) return true; + var options = this.options; // windows: need to use /, not \ + + if (path.sep !== '/') { + f = f.split(path.sep).join('/'); + } // treat the test path as a set of pathparts. + + + f = f.split(slashSplit); + this.debug(this.pattern, 'split', f); // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + var set = this.set; + this.debug(this.pattern, 'set', set); // Find the basename of the path by looking for the last non-empty segment + + var filename; + var i; + + for (i = f.length - 1; i >= 0; i--) { + filename = f[i]; + if (filename) break; + } + + for (i = 0; i < set.length; i++) { + var pattern = set[i]; + var file = f; + + if (options.matchBase && pattern.length === 1) { + file = [filename]; + } + + var hit = this.matchOne(file, pattern, partial); + + if (hit) { + if (options.flipNegate) return true; + return !this.negate; + } + } // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + + + if (options.flipNegate) return false; + return this.negate; +} // set partial to true to test if, for example, +// "/a/b" matches the start of "/*/b/*/d" +// Partial means, if you run out of file before you run +// out of pattern, then that's fine, as long as all +// the parts match. + + +Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options; + this.debug('matchOne', { + 'this': this, + file: file, + pattern: pattern + }); + this.debug('matchOne', file.length, pattern.length); + + for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { + this.debug('matchOne loop'); + var p = pattern[pi]; + var f = file[fi]; + this.debug(pattern, p, f); // should be impossible. + // some invalid regexp stuff in the set. + + if (p === false) return false; + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]); // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + + var fr = fi; + var pr = pi + 1; + + if (pr === pl) { + this.debug('** at the end'); // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || !options.dot && file[fi].charAt(0) === '.') return false; + } + + return true; + } // ok, let's see if we can swallow whatever we can. + + + while (fr < fl) { + var swallowee = file[fr]; + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee); // XXX remove this slice. Just pass the start index. + + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee); // found a match. + + return true; + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || !options.dot && swallowee.charAt(0) === '.') { + this.debug('dot detected!', file, fr, pattern, pr); + break; + } // ** swallows a segment, and continue. + + + this.debug('globstar swallow a segment, and continue'); + fr++; + } + } // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + + + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr); + if (fr === fl) return true; + } + + return false; + } // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + + + var hit; + + if (typeof p === 'string') { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase(); + } else { + hit = f === p; + } + + this.debug('string match', p, f, hit); + } else { + hit = f.match(p); + this.debug('pattern match', p, f, hit); + } + + if (!hit) return false; + } // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + // now either we fell off the end of the pattern, or we're done. + + + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true; + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial; + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = fi === fl - 1 && file[fi] === ''; + return emptyFileEnd; + } // should be unreachable. + + + throw new Error('wtf?'); +}; // replace stuff like \* with * + + +function globUnescape(s) { + return s.replace(/\\(.)/g, '$1'); +} + +function regExpEscape(s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); +} + +const copyProperty = (to, from, property, ignoreNonConfigurable) => { + // `Function#length` should reflect the parameters of `to` not `from` since we keep its body. + // `Function#prototype` is non-writable and non-configurable so can never be modified. + if (property === 'length' || property === 'prototype') { + return; + } + + const toDescriptor = Object.getOwnPropertyDescriptor(to, property); + const fromDescriptor = Object.getOwnPropertyDescriptor(from, property); + + if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) { + return; + } + + Object.defineProperty(to, property, fromDescriptor); +}; // `Object.defineProperty()` throws if the property exists, is not configurable and either: +// - one its descriptors is changed +// - it is non-writable and its value is changed + + +const canCopyProperty = function (toDescriptor, fromDescriptor) { + return toDescriptor === undefined || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value); +}; + +const changePrototype = (to, from) => { + const fromPrototype = Object.getPrototypeOf(from); + + if (fromPrototype === Object.getPrototypeOf(to)) { + return; + } + + Object.setPrototypeOf(to, fromPrototype); +}; + +const wrappedToString = (withName, fromBody) => `/* Wrapped ${withName}*/\n${fromBody}`; + +const toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, 'toString'); +const toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, 'name'); // We call `from.toString()` early (not lazily) to ensure `from` can be garbage collected. +// We use `bind()` instead of a closure for the same reason. +// Calling `from.toString()` early also allows caching it in case `to.toString()` is called several times. + +const changeToString = (to, from, name) => { + const withName = name === '' ? '' : `with ${name.trim()}() `; + const newToString = wrappedToString.bind(null, withName, from.toString()); // Ensure `to.toString.toString` is non-enumerable and has the same `same` + + Object.defineProperty(newToString, 'name', toStringName); + Object.defineProperty(to, 'toString', Object.assign({}, toStringDescriptor, { + value: newToString + })); +}; + +const mimicFn = (to, from, { + ignoreNonConfigurable = false +} = {}) => { + const { + name + } = to; + + for (const property of Reflect.ownKeys(from)) { + copyProperty(to, from, property, ignoreNonConfigurable); + } + + changePrototype(to, from); + changeToString(to, from, name); + return to; +}; + +var mimicFn_1 = mimicFn; + +var pDefer = () => { + const ret = {}; + ret.promise = new Promise((resolve, reject) => { + ret.resolve = resolve; + ret.reject = reject; + }); + return ret; +}; + +var dist = createCommonjsModule(function (module, exports) { + + var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) { + 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) : new P(function (resolve) { + resolve(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 p_defer_1 = __importDefault(pDefer); + + function mapAgeCleaner(map, property = 'maxAge') { + let processingKey; + let processingTimer; + let processingDeferred; + + const cleanup = () => __awaiter(this, void 0, void 0, function* () { + if (processingKey !== undefined) { + // If we are already processing an item, we can safely exit + return; + } + + const setupTimer = item => __awaiter(this, void 0, void 0, function* () { + processingDeferred = p_defer_1.default(); + const delay = item[1][property] - Date.now(); + + if (delay <= 0) { + // Remove the item immediately if the delay is equal to or below 0 + map.delete(item[0]); + processingDeferred.resolve(); + return; + } // Keep track of the current processed key + + + processingKey = item[0]; + processingTimer = setTimeout(() => { + // Remove the item when the timeout fires + map.delete(item[0]); + + if (processingDeferred) { + processingDeferred.resolve(); + } + }, delay); // tslint:disable-next-line:strict-type-predicates + + if (typeof processingTimer.unref === 'function') { + // Don't hold up the process from exiting + processingTimer.unref(); + } + + return processingDeferred.promise; + }); + + try { + for (const entry of map) { + yield setupTimer(entry); + } + } catch (_a) {// Do nothing if an error occurs, this means the timer was cleaned up and we should stop processing + } + + processingKey = undefined; + }); + + const reset = () => { + processingKey = undefined; + + if (processingTimer !== undefined) { + clearTimeout(processingTimer); + processingTimer = undefined; + } + + if (processingDeferred !== undefined) { + // tslint:disable-line:early-exit + processingDeferred.reject(undefined); + processingDeferred = undefined; + } + }; + + const originalSet = map.set.bind(map); + + map.set = (key, value) => { + if (map.has(key)) { + // If the key already exist, remove it so we can add it back at the end of the map. + map.delete(key); + } // Call the original `map.set` + + + const result = originalSet(key, value); // If we are already processing a key and the key added is the current processed key, stop processing it + + if (processingKey && processingKey === key) { + reset(); + } // Always run the cleanup method in case it wasn't started yet + + + cleanup(); // tslint:disable-line:no-floating-promises + + return result; + }; + + cleanup(); // tslint:disable-line:no-floating-promises + + return map; + } + + exports.default = mapAgeCleaner; // Add support for CJS + + module.exports = mapAgeCleaner; + module.exports.default = mapAgeCleaner; +}); + +const cacheStore = new WeakMap(); + +const mem = (fn, options = {}) => { + // Automatically use WeakMap unless the user provided their own cache + const weakCache = options.cache || new WeakMap(); + const { + cacheKey = ([firstArgument]) => firstArgument, + cache = new Map(), + maxAge + } = options; + + if (typeof maxAge === 'number') { + dist(cache); + } + + const memoized = function (...arguments_) { + const key = cacheKey(arguments_); // Prefer WeakMap if the key allows it + + const bestCache = key && (typeof key === 'object' || typeof key === 'function') ? weakCache : cache; + + if (bestCache.has(key)) { + return bestCache.get(key).data; + } + + const cacheItem = fn.apply(this, arguments_); + bestCache.set(key, { + data: cacheItem, + maxAge: maxAge ? Date.now() + maxAge : Infinity + }); + return cacheItem; + }; + + try { + // The below call will throw in some host environments + // See https://github.com/sindresorhus/mimic-fn/issues/10 + mimicFn_1(memoized, fn); + } catch (_) {} + + cacheStore.set(memoized, cache); + return memoized; +}; + +var mem_1 = mem; + +var clear = fn => { + if (!cacheStore.has(fn)) { + throw new Error('Can\'t clear a function that was not memoized!'); + } + + const cache = cacheStore.get(fn); + + if (typeof cache.clear === 'function') { + cache.clear(); + } +}; +mem_1.clear = clear; + +var thirdParty = require("./third-party"); + +const ParserEND = 0x110000; + +class ParserError extends Error { + /* istanbul ignore next */ + constructor(msg, filename, linenumber) { + super('[ParserError] ' + msg, filename, linenumber); + this.name = 'ParserError'; + this.code = 'ParserError'; + if (Error.captureStackTrace) Error.captureStackTrace(this, ParserError); + } + +} + +class State { + constructor(parser) { + this.parser = parser; + this.buf = ''; + this.returned = null; + this.result = null; + this.resultTable = null; + this.resultArr = null; + } + +} + +class Parser { + constructor() { + this.pos = 0; + this.col = 0; + this.line = 0; + this.obj = {}; + this.ctx = this.obj; + this.stack = []; + this._buf = ''; + this.char = null; + this.ii = 0; + this.state = new State(this.parseStart); + } + + parse(str) { + /* istanbul ignore next */ + if (str.length === 0 || str.length == null) return; + this._buf = String(str); + this.ii = -1; + this.char = -1; + let getNext; + + while (getNext === false || this.nextChar()) { + getNext = this.runOne(); + } + + this._buf = null; + } + + nextChar() { + if (this.char === 0x0A) { + ++this.line; + this.col = -1; + } + + ++this.ii; + this.char = this._buf.codePointAt(this.ii); + ++this.pos; + ++this.col; + return this.haveBuffer(); + } + + haveBuffer() { + return this.ii < this._buf.length; + } + + runOne() { + return this.state.parser.call(this, this.state.returned); + } + + finish() { + this.char = ParserEND; + let last; + + do { + last = this.state.parser; + this.runOne(); + } while (this.state.parser !== last); + + this.ctx = null; + this.state = null; + this._buf = null; + return this.obj; + } + + next(fn) { + /* istanbul ignore next */ + if (typeof fn !== 'function') throw new ParserError('Tried to set state to non-existent state: ' + JSON.stringify(fn)); + this.state.parser = fn; + } + + goto(fn) { + this.next(fn); + return this.runOne(); + } + + call(fn, returnWith) { + if (returnWith) this.next(returnWith); + this.stack.push(this.state); + this.state = new State(fn); + } + + callNow(fn, returnWith) { + this.call(fn, returnWith); + return this.runOne(); + } + + return(value) { + /* istanbul ignore next */ + if (this.stack.length === 0) throw this.error(new ParserError('Stack underflow')); + if (value === undefined) value = this.state.buf; + this.state = this.stack.pop(); + this.state.returned = value; + } + + returnNow(value) { + this.return(value); + return this.runOne(); + } + + consume() { + /* istanbul ignore next */ + if (this.char === ParserEND) throw this.error(new ParserError('Unexpected end-of-buffer')); + this.state.buf += this._buf[this.ii]; + } + + error(err) { + err.line = this.line; + err.col = this.col; + err.pos = this.pos; + return err; + } + /* istanbul ignore next */ + + + parseStart() { + throw new ParserError('Must declare a parseStart method'); + } + +} + +Parser.END = ParserEND; +Parser.Error = ParserError; +var parser$1 = Parser; + +var createDatetime = value => { + const date = new Date(value); + /* istanbul ignore if */ + + if (isNaN(date)) { + throw new TypeError('Invalid Datetime'); + } else { + return date; + } +}; + +var formatNum = (d, num) => { + num = String(num); + + while (num.length < d) num = '0' + num; + + return num; +}; + +class FloatingDateTime extends Date { + constructor(value) { + super(value + 'Z'); + this.isFloating = true; + } + + toISOString() { + const date = `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`; + const time = `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`; + return `${date}T${time}`; + } + +} + +var createDatetimeFloat = value => { + const date = new FloatingDateTime(value); + /* istanbul ignore if */ + + if (isNaN(date)) { + throw new TypeError('Invalid Datetime'); + } else { + return date; + } +}; + +const DateTime = global.Date; + +class Date$1 extends DateTime { + constructor(value) { + super(value); + this.isDate = true; + } + + toISOString() { + return `${this.getUTCFullYear()}-${formatNum(2, this.getUTCMonth() + 1)}-${formatNum(2, this.getUTCDate())}`; + } + +} + +var createDate = value => { + const date = new Date$1(value); + /* istanbul ignore if */ + + if (isNaN(date)) { + throw new TypeError('Invalid Datetime'); + } else { + return date; + } +}; + +class Time extends Date { + constructor(value) { + super(`0000-01-01T${value}Z`); + this.isTime = true; + } + + toISOString() { + return `${formatNum(2, this.getUTCHours())}:${formatNum(2, this.getUTCMinutes())}:${formatNum(2, this.getUTCSeconds())}.${formatNum(3, this.getUTCMilliseconds())}`; + } + +} + +var createTime = value => { + const date = new Time(value); + /* istanbul ignore if */ + + if (isNaN(date)) { + throw new TypeError('Invalid Datetime'); + } else { + return date; + } +}; + +/* eslint-disable no-new-wrappers, no-eval, camelcase, operator-linebreak */ + + +var tomlParser = makeParserClass(parser$1); +var makeParserClass_1 = makeParserClass; + +class TomlError extends Error { + constructor(msg) { + super(msg); + this.name = 'TomlError'; + /* istanbul ignore next */ + + if (Error.captureStackTrace) Error.captureStackTrace(this, TomlError); + this.fromTOML = true; + this.wrapped = null; + } + +} + +TomlError.wrap = err => { + const terr = new TomlError(err.message); + terr.code = err.code; + terr.wrapped = err; + return terr; +}; + +var TomlError_1 = TomlError; +const CTRL_I = 0x09; +const CTRL_J = 0x0A; +const CTRL_M = 0x0D; +const CTRL_CHAR_BOUNDARY = 0x1F; // the last non-character in the latin1 region of unicode, except DEL + +const CHAR_SP = 0x20; +const CHAR_QUOT = 0x22; +const CHAR_NUM = 0x23; +const CHAR_APOS = 0x27; +const CHAR_PLUS = 0x2B; +const CHAR_COMMA = 0x2C; +const CHAR_HYPHEN = 0x2D; +const CHAR_PERIOD = 0x2E; +const CHAR_0 = 0x30; +const CHAR_1 = 0x31; +const CHAR_7 = 0x37; +const CHAR_9 = 0x39; +const CHAR_COLON = 0x3A; +const CHAR_EQUALS = 0x3D; +const CHAR_A = 0x41; +const CHAR_E = 0x45; +const CHAR_F = 0x46; +const CHAR_T = 0x54; +const CHAR_U = 0x55; +const CHAR_Z = 0x5A; +const CHAR_LOWBAR = 0x5F; +const CHAR_a = 0x61; +const CHAR_b = 0x62; +const CHAR_e = 0x65; +const CHAR_f = 0x66; +const CHAR_i = 0x69; +const CHAR_l = 0x6C; +const CHAR_n = 0x6E; +const CHAR_o = 0x6F; +const CHAR_r = 0x72; +const CHAR_s = 0x73; +const CHAR_t = 0x74; +const CHAR_u = 0x75; +const CHAR_x = 0x78; +const CHAR_z = 0x7A; +const CHAR_LCUB = 0x7B; +const CHAR_RCUB = 0x7D; +const CHAR_LSQB = 0x5B; +const CHAR_BSOL = 0x5C; +const CHAR_RSQB = 0x5D; +const CHAR_DEL = 0x7F; +const SURROGATE_FIRST = 0xD800; +const SURROGATE_LAST = 0xDFFF; +const escapes = { + [CHAR_b]: '\u0008', + [CHAR_t]: '\u0009', + [CHAR_n]: '\u000A', + [CHAR_f]: '\u000C', + [CHAR_r]: '\u000D', + [CHAR_QUOT]: '\u0022', + [CHAR_BSOL]: '\u005C' +}; + +function isDigit(cp) { + return cp >= CHAR_0 && cp <= CHAR_9; +} + +function isHexit(cp) { + return cp >= CHAR_A && cp <= CHAR_F || cp >= CHAR_a && cp <= CHAR_f || cp >= CHAR_0 && cp <= CHAR_9; +} + +function isBit(cp) { + return cp === CHAR_1 || cp === CHAR_0; +} + +function isOctit(cp) { + return cp >= CHAR_0 && cp <= CHAR_7; +} + +function isAlphaNumQuoteHyphen(cp) { + return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_APOS || cp === CHAR_QUOT || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN; +} + +function isAlphaNumHyphen(cp) { + return cp >= CHAR_A && cp <= CHAR_Z || cp >= CHAR_a && cp <= CHAR_z || cp >= CHAR_0 && cp <= CHAR_9 || cp === CHAR_LOWBAR || cp === CHAR_HYPHEN; +} + +const _type = Symbol('type'); + +const _declared = Symbol('declared'); + +const hasOwnProperty$2 = Object.prototype.hasOwnProperty; +const defineProperty = Object.defineProperty; +const descriptor = { + configurable: true, + enumerable: true, + writable: true, + value: undefined +}; + +function hasKey(obj, key) { + if (hasOwnProperty$2.call(obj, key)) return true; + if (key === '__proto__') defineProperty(obj, '__proto__', descriptor); + return false; +} + +const INLINE_TABLE = Symbol('inline-table'); + +function InlineTable() { + return Object.defineProperties({}, { + [_type]: { + value: INLINE_TABLE + } + }); +} + +function isInlineTable(obj) { + if (obj === null || typeof obj !== 'object') return false; + return obj[_type] === INLINE_TABLE; +} + +const TABLE = Symbol('table'); + +function Table() { + return Object.defineProperties({}, { + [_type]: { + value: TABLE + }, + [_declared]: { + value: false, + writable: true + } + }); +} + +function isTable(obj) { + if (obj === null || typeof obj !== 'object') return false; + return obj[_type] === TABLE; +} + +const _contentType = Symbol('content-type'); + +const INLINE_LIST = Symbol('inline-list'); + +function InlineList(type) { + return Object.defineProperties([], { + [_type]: { + value: INLINE_LIST + }, + [_contentType]: { + value: type + } + }); +} + +function isInlineList(obj) { + if (obj === null || typeof obj !== 'object') return false; + return obj[_type] === INLINE_LIST; +} + +const LIST = Symbol('list'); + +function List() { + return Object.defineProperties([], { + [_type]: { + value: LIST + } + }); +} + +function isList(obj) { + if (obj === null || typeof obj !== 'object') return false; + return obj[_type] === LIST; +} // in an eval, to let bundlers not slurp in a util proxy + + +let _custom; + +try { + const utilInspect = util__default['default'].inspect; + _custom = utilInspect.custom; +} catch (_) { + /* eval require not available in transpiled bundle */ +} +/* istanbul ignore next */ + + +const _inspect = _custom || 'inspect'; + +class BoxedBigInt { + constructor(value) { + try { + this.value = global.BigInt.asIntN(64, value); + } catch (_) { + /* istanbul ignore next */ + this.value = null; + } + + Object.defineProperty(this, _type, { + value: INTEGER + }); + } + + isNaN() { + return this.value === null; + } + /* istanbul ignore next */ + + + toString() { + return String(this.value); + } + /* istanbul ignore next */ + + + [_inspect]() { + return `[BigInt: ${this.toString()}]}`; + } + + valueOf() { + return this.value; + } + +} + +const INTEGER = Symbol('integer'); + +function Integer(value) { + let num = Number(value); // -0 is a float thing, not an int thing + + if (Object.is(num, -0)) num = 0; + /* istanbul ignore else */ + + if (global.BigInt && !Number.isSafeInteger(num)) { + return new BoxedBigInt(value); + } else { + /* istanbul ignore next */ + return Object.defineProperties(new Number(num), { + isNaN: { + value: function () { + return isNaN(this); + } + }, + [_type]: { + value: INTEGER + }, + [_inspect]: { + value: () => `[Integer: ${value}]` + } + }); + } +} + +function isInteger(obj) { + if (obj === null || typeof obj !== 'object') return false; + return obj[_type] === INTEGER; +} + +const FLOAT = Symbol('float'); + +function Float(value) { + /* istanbul ignore next */ + return Object.defineProperties(new Number(value), { + [_type]: { + value: FLOAT + }, + [_inspect]: { + value: () => `[Float: ${value}]` + } + }); +} + +function isFloat(obj) { + if (obj === null || typeof obj !== 'object') return false; + return obj[_type] === FLOAT; +} + +function tomlType(value) { + const type = typeof value; + + if (type === 'object') { + /* istanbul ignore if */ + if (value === null) return 'null'; + if (value instanceof Date) return 'datetime'; + /* istanbul ignore else */ + + if (_type in value) { + switch (value[_type]) { + case INLINE_TABLE: + return 'inline-table'; + + case INLINE_LIST: + return 'inline-list'; + + /* istanbul ignore next */ + + case TABLE: + return 'table'; + + /* istanbul ignore next */ + + case LIST: + return 'list'; + + case FLOAT: + return 'float'; + + case INTEGER: + return 'integer'; + } + } + } + + return type; +} + +function makeParserClass(Parser) { + class TOMLParser extends Parser { + constructor() { + super(); + this.ctx = this.obj = Table(); + } + /* MATCH HELPER */ + + + atEndOfWord() { + return this.char === CHAR_NUM || this.char === CTRL_I || this.char === CHAR_SP || this.atEndOfLine(); + } + + atEndOfLine() { + return this.char === Parser.END || this.char === CTRL_J || this.char === CTRL_M; + } + + parseStart() { + if (this.char === Parser.END) { + return null; + } else if (this.char === CHAR_LSQB) { + return this.call(this.parseTableOrList); + } else if (this.char === CHAR_NUM) { + return this.call(this.parseComment); + } else if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { + return null; + } else if (isAlphaNumQuoteHyphen(this.char)) { + return this.callNow(this.parseAssignStatement); + } else { + throw this.error(new TomlError(`Unknown character "${this.char}"`)); + } + } // HELPER, this strips any whitespace and comments to the end of the line + // then RETURNS. Last state in a production. + + + parseWhitespaceToEOL() { + if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { + return null; + } else if (this.char === CHAR_NUM) { + return this.goto(this.parseComment); + } else if (this.char === Parser.END || this.char === CTRL_J) { + return this.return(); + } else { + throw this.error(new TomlError('Unexpected character, expected only whitespace or comments till end of line')); + } + } + /* ASSIGNMENT: key = value */ + + + parseAssignStatement() { + return this.callNow(this.parseAssign, this.recordAssignStatement); + } + + recordAssignStatement(kv) { + let target = this.ctx; + let finalKey = kv.key.pop(); + + for (let kw of kv.key) { + if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) { + throw this.error(new TomlError("Can't redefine existing key")); + } + + target = target[kw] = target[kw] || Table(); + } + + if (hasKey(target, finalKey)) { + throw this.error(new TomlError("Can't redefine existing key")); + } // unbox our numbers + + + if (isInteger(kv.value) || isFloat(kv.value)) { + target[finalKey] = kv.value.valueOf(); + } else { + target[finalKey] = kv.value; + } + + return this.goto(this.parseWhitespaceToEOL); + } + /* ASSSIGNMENT expression, key = value possibly inside an inline table */ + + + parseAssign() { + return this.callNow(this.parseKeyword, this.recordAssignKeyword); + } + + recordAssignKeyword(key) { + if (this.state.resultTable) { + this.state.resultTable.push(key); + } else { + this.state.resultTable = [key]; + } + + return this.goto(this.parseAssignKeywordPreDot); + } + + parseAssignKeywordPreDot() { + if (this.char === CHAR_PERIOD) { + return this.next(this.parseAssignKeywordPostDot); + } else if (this.char !== CHAR_SP && this.char !== CTRL_I) { + return this.goto(this.parseAssignEqual); + } + } + + parseAssignKeywordPostDot() { + if (this.char !== CHAR_SP && this.char !== CTRL_I) { + return this.callNow(this.parseKeyword, this.recordAssignKeyword); + } + } + + parseAssignEqual() { + if (this.char === CHAR_EQUALS) { + return this.next(this.parseAssignPreValue); + } else { + throw this.error(new TomlError('Invalid character, expected "="')); + } + } + + parseAssignPreValue() { + if (this.char === CHAR_SP || this.char === CTRL_I) { + return null; + } else { + return this.callNow(this.parseValue, this.recordAssignValue); + } + } + + recordAssignValue(value) { + return this.returnNow({ + key: this.state.resultTable, + value: value + }); + } + /* COMMENTS: #...eol */ + + + parseComment() { + do { + if (this.char === Parser.END || this.char === CTRL_J) { + return this.return(); + } + } while (this.nextChar()); + } + /* TABLES AND LISTS, [foo] and [[foo]] */ + + + parseTableOrList() { + if (this.char === CHAR_LSQB) { + this.next(this.parseList); + } else { + return this.goto(this.parseTable); + } + } + /* TABLE [foo.bar.baz] */ + + + parseTable() { + this.ctx = this.obj; + return this.goto(this.parseTableNext); + } + + parseTableNext() { + if (this.char === CHAR_SP || this.char === CTRL_I) { + return null; + } else { + return this.callNow(this.parseKeyword, this.parseTableMore); + } + } + + parseTableMore(keyword) { + if (this.char === CHAR_SP || this.char === CTRL_I) { + return null; + } else if (this.char === CHAR_RSQB) { + if (hasKey(this.ctx, keyword) && (!isTable(this.ctx[keyword]) || this.ctx[keyword][_declared])) { + throw this.error(new TomlError("Can't redefine existing key")); + } else { + this.ctx = this.ctx[keyword] = this.ctx[keyword] || Table(); + this.ctx[_declared] = true; + } + + return this.next(this.parseWhitespaceToEOL); + } else if (this.char === CHAR_PERIOD) { + if (!hasKey(this.ctx, keyword)) { + this.ctx = this.ctx[keyword] = Table(); + } else if (isTable(this.ctx[keyword])) { + this.ctx = this.ctx[keyword]; + } else if (isList(this.ctx[keyword])) { + this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]; + } else { + throw this.error(new TomlError("Can't redefine existing key")); + } + + return this.next(this.parseTableNext); + } else { + throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')); + } + } + /* LIST [[a.b.c]] */ + + + parseList() { + this.ctx = this.obj; + return this.goto(this.parseListNext); + } + + parseListNext() { + if (this.char === CHAR_SP || this.char === CTRL_I) { + return null; + } else { + return this.callNow(this.parseKeyword, this.parseListMore); + } + } + + parseListMore(keyword) { + if (this.char === CHAR_SP || this.char === CTRL_I) { + return null; + } else if (this.char === CHAR_RSQB) { + if (!hasKey(this.ctx, keyword)) { + this.ctx[keyword] = List(); + } + + if (isInlineList(this.ctx[keyword])) { + throw this.error(new TomlError("Can't extend an inline array")); + } else if (isList(this.ctx[keyword])) { + const next = Table(); + this.ctx[keyword].push(next); + this.ctx = next; + } else { + throw this.error(new TomlError("Can't redefine an existing key")); + } + + return this.next(this.parseListEnd); + } else if (this.char === CHAR_PERIOD) { + if (!hasKey(this.ctx, keyword)) { + this.ctx = this.ctx[keyword] = Table(); + } else if (isInlineList(this.ctx[keyword])) { + throw this.error(new TomlError("Can't extend an inline array")); + } else if (isInlineTable(this.ctx[keyword])) { + throw this.error(new TomlError("Can't extend an inline table")); + } else if (isList(this.ctx[keyword])) { + this.ctx = this.ctx[keyword][this.ctx[keyword].length - 1]; + } else if (isTable(this.ctx[keyword])) { + this.ctx = this.ctx[keyword]; + } else { + throw this.error(new TomlError("Can't redefine an existing key")); + } + + return this.next(this.parseListNext); + } else { + throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')); + } + } + + parseListEnd(keyword) { + if (this.char === CHAR_RSQB) { + return this.next(this.parseWhitespaceToEOL); + } else { + throw this.error(new TomlError('Unexpected character, expected whitespace, . or ]')); + } + } + /* VALUE string, number, boolean, inline list, inline object */ + + + parseValue() { + if (this.char === Parser.END) { + throw this.error(new TomlError('Key without value')); + } else if (this.char === CHAR_QUOT) { + return this.next(this.parseDoubleString); + } + + if (this.char === CHAR_APOS) { + return this.next(this.parseSingleString); + } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { + return this.goto(this.parseNumberSign); + } else if (this.char === CHAR_i) { + return this.next(this.parseInf); + } else if (this.char === CHAR_n) { + return this.next(this.parseNan); + } else if (isDigit(this.char)) { + return this.goto(this.parseNumberOrDateTime); + } else if (this.char === CHAR_t || this.char === CHAR_f) { + return this.goto(this.parseBoolean); + } else if (this.char === CHAR_LSQB) { + return this.call(this.parseInlineList, this.recordValue); + } else if (this.char === CHAR_LCUB) { + return this.call(this.parseInlineTable, this.recordValue); + } else { + throw this.error(new TomlError('Unexpected character, expecting string, number, datetime, boolean, inline array or inline table')); + } + } + + recordValue(value) { + return this.returnNow(value); + } + + parseInf() { + if (this.char === CHAR_n) { + return this.next(this.parseInf2); + } else { + throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"')); + } + } + + parseInf2() { + if (this.char === CHAR_f) { + if (this.state.buf === '-') { + return this.return(-Infinity); + } else { + return this.return(Infinity); + } + } else { + throw this.error(new TomlError('Unexpected character, expected "inf", "+inf" or "-inf"')); + } + } + + parseNan() { + if (this.char === CHAR_a) { + return this.next(this.parseNan2); + } else { + throw this.error(new TomlError('Unexpected character, expected "nan"')); + } + } + + parseNan2() { + if (this.char === CHAR_n) { + return this.return(NaN); + } else { + throw this.error(new TomlError('Unexpected character, expected "nan"')); + } + } + /* KEYS, barewords or basic, literal, or dotted */ + + + parseKeyword() { + if (this.char === CHAR_QUOT) { + return this.next(this.parseBasicString); + } else if (this.char === CHAR_APOS) { + return this.next(this.parseLiteralString); + } else { + return this.goto(this.parseBareKey); + } + } + /* KEYS: barewords */ + + + parseBareKey() { + do { + if (this.char === Parser.END) { + throw this.error(new TomlError('Key ended without value')); + } else if (isAlphaNumHyphen(this.char)) { + this.consume(); + } else if (this.state.buf.length === 0) { + throw this.error(new TomlError('Empty bare keys are not allowed')); + } else { + return this.returnNow(); + } + } while (this.nextChar()); + } + /* STRINGS, single quoted (literal) */ + + + parseSingleString() { + if (this.char === CHAR_APOS) { + return this.next(this.parseLiteralMultiStringMaybe); + } else { + return this.goto(this.parseLiteralString); + } + } + + parseLiteralString() { + do { + if (this.char === CHAR_APOS) { + return this.return(); + } else if (this.atEndOfLine()) { + throw this.error(new TomlError('Unterminated string')); + } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) { + throw this.errorControlCharInString(); + } else { + this.consume(); + } + } while (this.nextChar()); + } + + parseLiteralMultiStringMaybe() { + if (this.char === CHAR_APOS) { + return this.next(this.parseLiteralMultiString); + } else { + return this.returnNow(); + } + } + + parseLiteralMultiString() { + if (this.char === CTRL_M) { + return null; + } else if (this.char === CTRL_J) { + return this.next(this.parseLiteralMultiStringContent); + } else { + return this.goto(this.parseLiteralMultiStringContent); + } + } + + parseLiteralMultiStringContent() { + do { + if (this.char === CHAR_APOS) { + return this.next(this.parseLiteralMultiEnd); + } else if (this.char === Parser.END) { + throw this.error(new TomlError('Unterminated multi-line string')); + } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) { + throw this.errorControlCharInString(); + } else { + this.consume(); + } + } while (this.nextChar()); + } + + parseLiteralMultiEnd() { + if (this.char === CHAR_APOS) { + return this.next(this.parseLiteralMultiEnd2); + } else { + this.state.buf += "'"; + return this.goto(this.parseLiteralMultiStringContent); + } + } + + parseLiteralMultiEnd2() { + if (this.char === CHAR_APOS) { + return this.return(); + } else { + this.state.buf += "''"; + return this.goto(this.parseLiteralMultiStringContent); + } + } + /* STRINGS double quoted */ + + + parseDoubleString() { + if (this.char === CHAR_QUOT) { + return this.next(this.parseMultiStringMaybe); + } else { + return this.goto(this.parseBasicString); + } + } + + parseBasicString() { + do { + if (this.char === CHAR_BSOL) { + return this.call(this.parseEscape, this.recordEscapeReplacement); + } else if (this.char === CHAR_QUOT) { + return this.return(); + } else if (this.atEndOfLine()) { + throw this.error(new TomlError('Unterminated string')); + } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I) { + throw this.errorControlCharInString(); + } else { + this.consume(); + } + } while (this.nextChar()); + } + + recordEscapeReplacement(replacement) { + this.state.buf += replacement; + return this.goto(this.parseBasicString); + } + + parseMultiStringMaybe() { + if (this.char === CHAR_QUOT) { + return this.next(this.parseMultiString); + } else { + return this.returnNow(); + } + } + + parseMultiString() { + if (this.char === CTRL_M) { + return null; + } else if (this.char === CTRL_J) { + return this.next(this.parseMultiStringContent); + } else { + return this.goto(this.parseMultiStringContent); + } + } + + parseMultiStringContent() { + do { + if (this.char === CHAR_BSOL) { + return this.call(this.parseMultiEscape, this.recordMultiEscapeReplacement); + } else if (this.char === CHAR_QUOT) { + return this.next(this.parseMultiEnd); + } else if (this.char === Parser.END) { + throw this.error(new TomlError('Unterminated multi-line string')); + } else if (this.char === CHAR_DEL || this.char <= CTRL_CHAR_BOUNDARY && this.char !== CTRL_I && this.char !== CTRL_J && this.char !== CTRL_M) { + throw this.errorControlCharInString(); + } else { + this.consume(); + } + } while (this.nextChar()); + } + + errorControlCharInString() { + let displayCode = '\\u00'; + + if (this.char < 16) { + displayCode += '0'; + } + + displayCode += this.char.toString(16); + return this.error(new TomlError(`Control characters (codes < 0x1f and 0x7f) are not allowed in strings, use ${displayCode} instead`)); + } + + recordMultiEscapeReplacement(replacement) { + this.state.buf += replacement; + return this.goto(this.parseMultiStringContent); + } + + parseMultiEnd() { + if (this.char === CHAR_QUOT) { + return this.next(this.parseMultiEnd2); + } else { + this.state.buf += '"'; + return this.goto(this.parseMultiStringContent); + } + } + + parseMultiEnd2() { + if (this.char === CHAR_QUOT) { + return this.return(); + } else { + this.state.buf += '""'; + return this.goto(this.parseMultiStringContent); + } + } + + parseMultiEscape() { + if (this.char === CTRL_M || this.char === CTRL_J) { + return this.next(this.parseMultiTrim); + } else if (this.char === CHAR_SP || this.char === CTRL_I) { + return this.next(this.parsePreMultiTrim); + } else { + return this.goto(this.parseEscape); + } + } + + parsePreMultiTrim() { + if (this.char === CHAR_SP || this.char === CTRL_I) { + return null; + } else if (this.char === CTRL_M || this.char === CTRL_J) { + return this.next(this.parseMultiTrim); + } else { + throw this.error(new TomlError("Can't escape whitespace")); + } + } + + parseMultiTrim() { + // explicitly whitespace here, END should follow the same path as chars + if (this.char === CTRL_J || this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M) { + return null; + } else { + return this.returnNow(); + } + } + + parseEscape() { + if (this.char in escapes) { + return this.return(escapes[this.char]); + } else if (this.char === CHAR_u) { + return this.call(this.parseSmallUnicode, this.parseUnicodeReturn); + } else if (this.char === CHAR_U) { + return this.call(this.parseLargeUnicode, this.parseUnicodeReturn); + } else { + throw this.error(new TomlError('Unknown escape character: ' + this.char)); + } + } + + parseUnicodeReturn(char) { + try { + const codePoint = parseInt(char, 16); + + if (codePoint >= SURROGATE_FIRST && codePoint <= SURROGATE_LAST) { + throw this.error(new TomlError('Invalid unicode, character in range 0xD800 - 0xDFFF is reserved')); + } + + return this.returnNow(String.fromCodePoint(codePoint)); + } catch (err) { + throw this.error(TomlError.wrap(err)); + } + } + + parseSmallUnicode() { + if (!isHexit(this.char)) { + throw this.error(new TomlError('Invalid character in unicode sequence, expected hex')); + } else { + this.consume(); + if (this.state.buf.length >= 4) return this.return(); + } + } + + parseLargeUnicode() { + if (!isHexit(this.char)) { + throw this.error(new TomlError('Invalid character in unicode sequence, expected hex')); + } else { + this.consume(); + if (this.state.buf.length >= 8) return this.return(); + } + } + /* NUMBERS */ + + + parseNumberSign() { + this.consume(); + return this.next(this.parseMaybeSignedInfOrNan); + } + + parseMaybeSignedInfOrNan() { + if (this.char === CHAR_i) { + return this.next(this.parseInf); + } else if (this.char === CHAR_n) { + return this.next(this.parseNan); + } else { + return this.callNow(this.parseNoUnder, this.parseNumberIntegerStart); + } + } + + parseNumberIntegerStart() { + if (this.char === CHAR_0) { + this.consume(); + return this.next(this.parseNumberIntegerExponentOrDecimal); + } else { + return this.goto(this.parseNumberInteger); + } + } + + parseNumberIntegerExponentOrDecimal() { + if (this.char === CHAR_PERIOD) { + this.consume(); + return this.call(this.parseNoUnder, this.parseNumberFloat); + } else if (this.char === CHAR_E || this.char === CHAR_e) { + this.consume(); + return this.next(this.parseNumberExponentSign); + } else { + return this.returnNow(Integer(this.state.buf)); + } + } + + parseNumberInteger() { + if (isDigit(this.char)) { + this.consume(); + } else if (this.char === CHAR_LOWBAR) { + return this.call(this.parseNoUnder); + } else if (this.char === CHAR_E || this.char === CHAR_e) { + this.consume(); + return this.next(this.parseNumberExponentSign); + } else if (this.char === CHAR_PERIOD) { + this.consume(); + return this.call(this.parseNoUnder, this.parseNumberFloat); + } else { + const result = Integer(this.state.buf); + /* istanbul ignore if */ + + if (result.isNaN()) { + throw this.error(new TomlError('Invalid number')); + } else { + return this.returnNow(result); + } + } + } + + parseNoUnder() { + if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD || this.char === CHAR_E || this.char === CHAR_e) { + throw this.error(new TomlError('Unexpected character, expected digit')); + } else if (this.atEndOfWord()) { + throw this.error(new TomlError('Incomplete number')); + } + + return this.returnNow(); + } + + parseNoUnderHexOctBinLiteral() { + if (this.char === CHAR_LOWBAR || this.char === CHAR_PERIOD) { + throw this.error(new TomlError('Unexpected character, expected digit')); + } else if (this.atEndOfWord()) { + throw this.error(new TomlError('Incomplete number')); + } + + return this.returnNow(); + } + + parseNumberFloat() { + if (this.char === CHAR_LOWBAR) { + return this.call(this.parseNoUnder, this.parseNumberFloat); + } else if (isDigit(this.char)) { + this.consume(); + } else if (this.char === CHAR_E || this.char === CHAR_e) { + this.consume(); + return this.next(this.parseNumberExponentSign); + } else { + return this.returnNow(Float(this.state.buf)); + } + } + + parseNumberExponentSign() { + if (isDigit(this.char)) { + return this.goto(this.parseNumberExponent); + } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { + this.consume(); + this.call(this.parseNoUnder, this.parseNumberExponent); + } else { + throw this.error(new TomlError('Unexpected character, expected -, + or digit')); + } + } + + parseNumberExponent() { + if (isDigit(this.char)) { + this.consume(); + } else if (this.char === CHAR_LOWBAR) { + return this.call(this.parseNoUnder); + } else { + return this.returnNow(Float(this.state.buf)); + } + } + /* NUMBERS or DATETIMES */ + + + parseNumberOrDateTime() { + if (this.char === CHAR_0) { + this.consume(); + return this.next(this.parseNumberBaseOrDateTime); + } else { + return this.goto(this.parseNumberOrDateTimeOnly); + } + } + + parseNumberOrDateTimeOnly() { + // note, if two zeros are in a row then it MUST be a date + if (this.char === CHAR_LOWBAR) { + return this.call(this.parseNoUnder, this.parseNumberInteger); + } else if (isDigit(this.char)) { + this.consume(); + if (this.state.buf.length > 4) this.next(this.parseNumberInteger); + } else if (this.char === CHAR_E || this.char === CHAR_e) { + this.consume(); + return this.next(this.parseNumberExponentSign); + } else if (this.char === CHAR_PERIOD) { + this.consume(); + return this.call(this.parseNoUnder, this.parseNumberFloat); + } else if (this.char === CHAR_HYPHEN) { + return this.goto(this.parseDateTime); + } else if (this.char === CHAR_COLON) { + return this.goto(this.parseOnlyTimeHour); + } else { + return this.returnNow(Integer(this.state.buf)); + } + } + + parseDateTimeOnly() { + if (this.state.buf.length < 4) { + if (isDigit(this.char)) { + return this.consume(); + } else if (this.char === CHAR_COLON) { + return this.goto(this.parseOnlyTimeHour); + } else { + throw this.error(new TomlError('Expected digit while parsing year part of a date')); + } + } else { + if (this.char === CHAR_HYPHEN) { + return this.goto(this.parseDateTime); + } else { + throw this.error(new TomlError('Expected hyphen (-) while parsing year part of date')); + } + } + } + + parseNumberBaseOrDateTime() { + if (this.char === CHAR_b) { + this.consume(); + return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerBin); + } else if (this.char === CHAR_o) { + this.consume(); + return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerOct); + } else if (this.char === CHAR_x) { + this.consume(); + return this.call(this.parseNoUnderHexOctBinLiteral, this.parseIntegerHex); + } else if (this.char === CHAR_PERIOD) { + return this.goto(this.parseNumberInteger); + } else if (isDigit(this.char)) { + return this.goto(this.parseDateTimeOnly); + } else { + return this.returnNow(Integer(this.state.buf)); + } + } + + parseIntegerHex() { + if (isHexit(this.char)) { + this.consume(); + } else if (this.char === CHAR_LOWBAR) { + return this.call(this.parseNoUnderHexOctBinLiteral); + } else { + const result = Integer(this.state.buf); + /* istanbul ignore if */ + + if (result.isNaN()) { + throw this.error(new TomlError('Invalid number')); + } else { + return this.returnNow(result); + } + } + } + + parseIntegerOct() { + if (isOctit(this.char)) { + this.consume(); + } else if (this.char === CHAR_LOWBAR) { + return this.call(this.parseNoUnderHexOctBinLiteral); + } else { + const result = Integer(this.state.buf); + /* istanbul ignore if */ + + if (result.isNaN()) { + throw this.error(new TomlError('Invalid number')); + } else { + return this.returnNow(result); + } + } + } + + parseIntegerBin() { + if (isBit(this.char)) { + this.consume(); + } else if (this.char === CHAR_LOWBAR) { + return this.call(this.parseNoUnderHexOctBinLiteral); + } else { + const result = Integer(this.state.buf); + /* istanbul ignore if */ + + if (result.isNaN()) { + throw this.error(new TomlError('Invalid number')); + } else { + return this.returnNow(result); + } + } + } + /* DATETIME */ + + + parseDateTime() { + // we enter here having just consumed the year and about to consume the hyphen + if (this.state.buf.length < 4) { + throw this.error(new TomlError('Years less than 1000 must be zero padded to four characters')); + } + + this.state.result = this.state.buf; + this.state.buf = ''; + return this.next(this.parseDateMonth); + } + + parseDateMonth() { + if (this.char === CHAR_HYPHEN) { + if (this.state.buf.length < 2) { + throw this.error(new TomlError('Months less than 10 must be zero padded to two characters')); + } + + this.state.result += '-' + this.state.buf; + this.state.buf = ''; + return this.next(this.parseDateDay); + } else if (isDigit(this.char)) { + this.consume(); + } else { + throw this.error(new TomlError('Incomplete datetime')); + } + } + + parseDateDay() { + if (this.char === CHAR_T || this.char === CHAR_SP) { + if (this.state.buf.length < 2) { + throw this.error(new TomlError('Days less than 10 must be zero padded to two characters')); + } + + this.state.result += '-' + this.state.buf; + this.state.buf = ''; + return this.next(this.parseStartTimeHour); + } else if (this.atEndOfWord()) { + return this.returnNow(createDate(this.state.result + '-' + this.state.buf)); + } else if (isDigit(this.char)) { + this.consume(); + } else { + throw this.error(new TomlError('Incomplete datetime')); + } + } + + parseStartTimeHour() { + if (this.atEndOfWord()) { + return this.returnNow(createDate(this.state.result)); + } else { + return this.goto(this.parseTimeHour); + } + } + + parseTimeHour() { + if (this.char === CHAR_COLON) { + if (this.state.buf.length < 2) { + throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters')); + } + + this.state.result += 'T' + this.state.buf; + this.state.buf = ''; + return this.next(this.parseTimeMin); + } else if (isDigit(this.char)) { + this.consume(); + } else { + throw this.error(new TomlError('Incomplete datetime')); + } + } + + parseTimeMin() { + if (this.state.buf.length < 2 && isDigit(this.char)) { + this.consume(); + } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) { + this.state.result += ':' + this.state.buf; + this.state.buf = ''; + return this.next(this.parseTimeSec); + } else { + throw this.error(new TomlError('Incomplete datetime')); + } + } + + parseTimeSec() { + if (isDigit(this.char)) { + this.consume(); + + if (this.state.buf.length === 2) { + this.state.result += ':' + this.state.buf; + this.state.buf = ''; + return this.next(this.parseTimeZoneOrFraction); + } + } else { + throw this.error(new TomlError('Incomplete datetime')); + } + } + + parseOnlyTimeHour() { + /* istanbul ignore else */ + if (this.char === CHAR_COLON) { + if (this.state.buf.length < 2) { + throw this.error(new TomlError('Hours less than 10 must be zero padded to two characters')); + } + + this.state.result = this.state.buf; + this.state.buf = ''; + return this.next(this.parseOnlyTimeMin); + } else { + throw this.error(new TomlError('Incomplete time')); + } + } + + parseOnlyTimeMin() { + if (this.state.buf.length < 2 && isDigit(this.char)) { + this.consume(); + } else if (this.state.buf.length === 2 && this.char === CHAR_COLON) { + this.state.result += ':' + this.state.buf; + this.state.buf = ''; + return this.next(this.parseOnlyTimeSec); + } else { + throw this.error(new TomlError('Incomplete time')); + } + } + + parseOnlyTimeSec() { + if (isDigit(this.char)) { + this.consume(); + + if (this.state.buf.length === 2) { + return this.next(this.parseOnlyTimeFractionMaybe); + } + } else { + throw this.error(new TomlError('Incomplete time')); + } + } + + parseOnlyTimeFractionMaybe() { + this.state.result += ':' + this.state.buf; + + if (this.char === CHAR_PERIOD) { + this.state.buf = ''; + this.next(this.parseOnlyTimeFraction); + } else { + return this.return(createTime(this.state.result)); + } + } + + parseOnlyTimeFraction() { + if (isDigit(this.char)) { + this.consume(); + } else if (this.atEndOfWord()) { + if (this.state.buf.length === 0) throw this.error(new TomlError('Expected digit in milliseconds')); + return this.returnNow(createTime(this.state.result + '.' + this.state.buf)); + } else { + throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')); + } + } + + parseTimeZoneOrFraction() { + if (this.char === CHAR_PERIOD) { + this.consume(); + this.next(this.parseDateTimeFraction); + } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { + this.consume(); + this.next(this.parseTimeZoneHour); + } else if (this.char === CHAR_Z) { + this.consume(); + return this.return(createDatetime(this.state.result + this.state.buf)); + } else if (this.atEndOfWord()) { + return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf)); + } else { + throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')); + } + } + + parseDateTimeFraction() { + if (isDigit(this.char)) { + this.consume(); + } else if (this.state.buf.length === 1) { + throw this.error(new TomlError('Expected digit in milliseconds')); + } else if (this.char === CHAR_HYPHEN || this.char === CHAR_PLUS) { + this.consume(); + this.next(this.parseTimeZoneHour); + } else if (this.char === CHAR_Z) { + this.consume(); + return this.return(createDatetime(this.state.result + this.state.buf)); + } else if (this.atEndOfWord()) { + return this.returnNow(createDatetimeFloat(this.state.result + this.state.buf)); + } else { + throw this.error(new TomlError('Unexpected character in datetime, expected period (.), minus (-), plus (+) or Z')); + } + } + + parseTimeZoneHour() { + if (isDigit(this.char)) { + this.consume(); // FIXME: No more regexps + + if (/\d\d$/.test(this.state.buf)) return this.next(this.parseTimeZoneSep); + } else { + throw this.error(new TomlError('Unexpected character in datetime, expected digit')); + } + } + + parseTimeZoneSep() { + if (this.char === CHAR_COLON) { + this.consume(); + this.next(this.parseTimeZoneMin); + } else { + throw this.error(new TomlError('Unexpected character in datetime, expected colon')); + } + } + + parseTimeZoneMin() { + if (isDigit(this.char)) { + this.consume(); + if (/\d\d$/.test(this.state.buf)) return this.return(createDatetime(this.state.result + this.state.buf)); + } else { + throw this.error(new TomlError('Unexpected character in datetime, expected digit')); + } + } + /* BOOLEAN */ + + + parseBoolean() { + /* istanbul ignore else */ + if (this.char === CHAR_t) { + this.consume(); + return this.next(this.parseTrue_r); + } else if (this.char === CHAR_f) { + this.consume(); + return this.next(this.parseFalse_a); + } + } + + parseTrue_r() { + if (this.char === CHAR_r) { + this.consume(); + return this.next(this.parseTrue_u); + } else { + throw this.error(new TomlError('Invalid boolean, expected true or false')); + } + } + + parseTrue_u() { + if (this.char === CHAR_u) { + this.consume(); + return this.next(this.parseTrue_e); + } else { + throw this.error(new TomlError('Invalid boolean, expected true or false')); + } + } + + parseTrue_e() { + if (this.char === CHAR_e) { + return this.return(true); + } else { + throw this.error(new TomlError('Invalid boolean, expected true or false')); + } + } + + parseFalse_a() { + if (this.char === CHAR_a) { + this.consume(); + return this.next(this.parseFalse_l); + } else { + throw this.error(new TomlError('Invalid boolean, expected true or false')); + } + } + + parseFalse_l() { + if (this.char === CHAR_l) { + this.consume(); + return this.next(this.parseFalse_s); + } else { + throw this.error(new TomlError('Invalid boolean, expected true or false')); + } + } + + parseFalse_s() { + if (this.char === CHAR_s) { + this.consume(); + return this.next(this.parseFalse_e); + } else { + throw this.error(new TomlError('Invalid boolean, expected true or false')); + } + } + + parseFalse_e() { + if (this.char === CHAR_e) { + return this.return(false); + } else { + throw this.error(new TomlError('Invalid boolean, expected true or false')); + } + } + /* INLINE LISTS */ + + + parseInlineList() { + if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) { + return null; + } else if (this.char === Parser.END) { + throw this.error(new TomlError('Unterminated inline array')); + } else if (this.char === CHAR_NUM) { + return this.call(this.parseComment); + } else if (this.char === CHAR_RSQB) { + return this.return(this.state.resultArr || InlineList()); + } else { + return this.callNow(this.parseValue, this.recordInlineListValue); + } + } + + recordInlineListValue(value) { + if (this.state.resultArr) { + const listType = this.state.resultArr[_contentType]; + const valueType = tomlType(value); + + if (listType !== valueType) { + throw this.error(new TomlError(`Inline lists must be a single type, not a mix of ${listType} and ${valueType}`)); + } + } else { + this.state.resultArr = InlineList(tomlType(value)); + } + + if (isFloat(value) || isInteger(value)) { + // unbox now that we've verified they're ok + this.state.resultArr.push(value.valueOf()); + } else { + this.state.resultArr.push(value); + } + + return this.goto(this.parseInlineListNext); + } + + parseInlineListNext() { + if (this.char === CHAR_SP || this.char === CTRL_I || this.char === CTRL_M || this.char === CTRL_J) { + return null; + } else if (this.char === CHAR_NUM) { + return this.call(this.parseComment); + } else if (this.char === CHAR_COMMA) { + return this.next(this.parseInlineList); + } else if (this.char === CHAR_RSQB) { + return this.goto(this.parseInlineList); + } else { + throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])')); + } + } + /* INLINE TABLE */ + + + parseInlineTable() { + if (this.char === CHAR_SP || this.char === CTRL_I) { + return null; + } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) { + throw this.error(new TomlError('Unterminated inline array')); + } else if (this.char === CHAR_RCUB) { + return this.return(this.state.resultTable || InlineTable()); + } else { + if (!this.state.resultTable) this.state.resultTable = InlineTable(); + return this.callNow(this.parseAssign, this.recordInlineTableValue); + } + } + + recordInlineTableValue(kv) { + let target = this.state.resultTable; + let finalKey = kv.key.pop(); + + for (let kw of kv.key) { + if (hasKey(target, kw) && (!isTable(target[kw]) || target[kw][_declared])) { + throw this.error(new TomlError("Can't redefine existing key")); + } + + target = target[kw] = target[kw] || Table(); + } + + if (hasKey(target, finalKey)) { + throw this.error(new TomlError("Can't redefine existing key")); + } + + if (isInteger(kv.value) || isFloat(kv.value)) { + target[finalKey] = kv.value.valueOf(); + } else { + target[finalKey] = kv.value; + } + + return this.goto(this.parseInlineTableNext); + } + + parseInlineTableNext() { + if (this.char === CHAR_SP || this.char === CTRL_I) { + return null; + } else if (this.char === Parser.END || this.char === CHAR_NUM || this.char === CTRL_J || this.char === CTRL_M) { + throw this.error(new TomlError('Unterminated inline array')); + } else if (this.char === CHAR_COMMA) { + return this.next(this.parseInlineTable); + } else if (this.char === CHAR_RCUB) { + return this.goto(this.parseInlineTable); + } else { + throw this.error(new TomlError('Invalid character, expected whitespace, comma (,) or close bracket (])')); + } + } + + } + + return TOMLParser; +} +tomlParser.makeParserClass = makeParserClass_1; +tomlParser.TomlError = TomlError_1; + +var parsePrettyError = prettyError; + +function prettyError(err, buf) { + /* istanbul ignore if */ + if (err.pos == null || err.line == null) return err; + let msg = err.message; + msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`; + /* istanbul ignore else */ + + if (buf && buf.split) { + const lines = buf.split(/\n/); + const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length; + let linePadding = ' '; + + while (linePadding.length < lineNumWidth) linePadding += ' '; + + for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) { + let lineNum = String(ii + 1); + if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum; + + if (err.line === ii) { + msg += lineNum + '> ' + lines[ii] + '\n'; + msg += linePadding + ' '; + + for (let hh = 0; hh < err.col; ++hh) { + msg += ' '; + } + + msg += '^\n'; + } else { + msg += lineNum + ': ' + lines[ii] + '\n'; + } + } + } + + err.message = msg + '\n'; + return err; +} + +var parseString_1 = parseString; + +function parseString(str) { + if (global.Buffer && global.Buffer.isBuffer(str)) { + str = str.toString('utf8'); + } + + const parser = new tomlParser(); + + try { + parser.parse(str); + return parser.finish(); + } catch (err) { + throw parsePrettyError(err, str); + } +} + +var loadToml = function (filePath, content) { + try { + return parseString_1(content); + } catch (error) { + error.message = `TOML Error in ${filePath}:\n${error.message}`; + throw error; + } +}; + +// This is a generated file. Do not edit. +var Space_Separator = /[\u1680\u2000-\u200A\u202F\u205F\u3000]/; +var ID_Start = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]/; +var ID_Continue = /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u09FC\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF9\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF2D-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDE00-\uDE3E\uDE47\uDE50-\uDE83\uDE86-\uDE99\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD36\uDD3A\uDD3C\uDD3D\uDD3F-\uDD47\uDD50-\uDD59]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/; +var unicode = { + Space_Separator: Space_Separator, + ID_Start: ID_Start, + ID_Continue: ID_Continue +}; +var util$2 = { + isSpaceSeparator(c) { + return typeof c === 'string' && unicode.Space_Separator.test(c); + }, + + isIdStartChar(c) { + return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c === '$' || c === '_' || unicode.ID_Start.test(c)); + }, + + isIdContinueChar(c) { + return typeof c === 'string' && (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c === '$' || c === '_' || c === '\u200C' || c === '\u200D' || unicode.ID_Continue.test(c)); + }, + + isDigit(c) { + return typeof c === 'string' && /[0-9]/.test(c); + }, + + isHexDigit(c) { + return typeof c === 'string' && /[0-9A-Fa-f]/.test(c); + } + +}; +let source$1; +let parseState; +let stack; +let pos; +let line$2; +let column; +let token; +let key; +let root$1; + +var parse$2 = function parse(text, reviver) { + source$1 = String(text); + parseState = 'start'; + stack = []; + pos = 0; + line$2 = 1; + column = 0; + token = undefined; + key = undefined; + root$1 = undefined; + + do { + token = lex(); // This code is unreachable. + // if (!parseStates[parseState]) { + // throw invalidParseState() + // } + + parseStates[parseState](); + } while (token.type !== 'eof'); + + if (typeof reviver === 'function') { + return internalize({ + '': root$1 + }, '', reviver); + } + + return root$1; +}; + +function internalize(holder, name, reviver) { + const value = holder[name]; + + if (value != null && typeof value === 'object') { + for (const key in value) { + const replacement = internalize(value, key, reviver); + + if (replacement === undefined) { + delete value[key]; + } else { + value[key] = replacement; + } + } + } + + return reviver.call(holder, name, value); +} + +let lexState; +let buffer; +let doubleQuote; +let sign; +let c; + +function lex() { + lexState = 'default'; + buffer = ''; + doubleQuote = false; + sign = 1; + + for (;;) { + c = peek(); // This code is unreachable. + // if (!lexStates[lexState]) { + // throw invalidLexState(lexState) + // } + + const token = lexStates[lexState](); + + if (token) { + return token; + } + } +} + +function peek() { + if (source$1[pos]) { + return String.fromCodePoint(source$1.codePointAt(pos)); + } +} + +function read() { + const c = peek(); + + if (c === '\n') { + line$2++; + column = 0; + } else if (c) { + column += c.length; + } else { + column++; + } + + if (c) { + pos += c.length; + } + + return c; +} + +const lexStates = { + default() { + switch (c) { + case '\t': + case '\v': + case '\f': + case ' ': + case '\u00A0': + case '\uFEFF': + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read(); + return; + + case '/': + read(); + lexState = 'comment'; + return; + + case undefined: + read(); + return newToken('eof'); + } + + if (util$2.isSpaceSeparator(c)) { + read(); + return; + } // This code is unreachable. + // if (!lexStates[parseState]) { + // throw invalidLexState(parseState) + // } + + + return lexStates[parseState](); + }, + + comment() { + switch (c) { + case '*': + read(); + lexState = 'multiLineComment'; + return; + + case '/': + read(); + lexState = 'singleLineComment'; + return; + } + + throw invalidChar(read()); + }, + + multiLineComment() { + switch (c) { + case '*': + read(); + lexState = 'multiLineCommentAsterisk'; + return; + + case undefined: + throw invalidChar(read()); + } + + read(); + }, + + multiLineCommentAsterisk() { + switch (c) { + case '*': + read(); + return; + + case '/': + read(); + lexState = 'default'; + return; + + case undefined: + throw invalidChar(read()); + } + + read(); + lexState = 'multiLineComment'; + }, + + singleLineComment() { + switch (c) { + case '\n': + case '\r': + case '\u2028': + case '\u2029': + read(); + lexState = 'default'; + return; + + case undefined: + read(); + return newToken('eof'); + } + + read(); + }, + + value() { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read()); + + case 'n': + read(); + literal('ull'); + return newToken('null', null); + + case 't': + read(); + literal('rue'); + return newToken('boolean', true); + + case 'f': + read(); + literal('alse'); + return newToken('boolean', false); + + case '-': + case '+': + if (read() === '-') { + sign = -1; + } + + lexState = 'sign'; + return; + + case '.': + buffer = read(); + lexState = 'decimalPointLeading'; + return; + + case '0': + buffer = read(); + lexState = 'zero'; + return; + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read(); + lexState = 'decimalInteger'; + return; + + case 'I': + read(); + literal('nfinity'); + return newToken('numeric', Infinity); + + case 'N': + read(); + literal('aN'); + return newToken('numeric', NaN); + + case '"': + case "'": + doubleQuote = read() === '"'; + buffer = ''; + lexState = 'string'; + return; + } + + throw invalidChar(read()); + }, + + identifierNameStartEscape() { + if (c !== 'u') { + throw invalidChar(read()); + } + + read(); + const u = unicodeEscape(); + + switch (u) { + case '$': + case '_': + break; + + default: + if (!util$2.isIdStartChar(u)) { + throw invalidIdentifier(); + } + + break; + } + + buffer += u; + lexState = 'identifierName'; + }, + + identifierName() { + switch (c) { + case '$': + case '_': + case '\u200C': + case '\u200D': + buffer += read(); + return; + + case '\\': + read(); + lexState = 'identifierNameEscape'; + return; + } + + if (util$2.isIdContinueChar(c)) { + buffer += read(); + return; + } + + return newToken('identifier', buffer); + }, + + identifierNameEscape() { + if (c !== 'u') { + throw invalidChar(read()); + } + + read(); + const u = unicodeEscape(); + + switch (u) { + case '$': + case '_': + case '\u200C': + case '\u200D': + break; + + default: + if (!util$2.isIdContinueChar(u)) { + throw invalidIdentifier(); + } + + break; + } + + buffer += u; + lexState = 'identifierName'; + }, + + sign() { + switch (c) { + case '.': + buffer = read(); + lexState = 'decimalPointLeading'; + return; + + case '0': + buffer = read(); + lexState = 'zero'; + return; + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + buffer = read(); + lexState = 'decimalInteger'; + return; + + case 'I': + read(); + literal('nfinity'); + return newToken('numeric', sign * Infinity); + + case 'N': + read(); + literal('aN'); + return newToken('numeric', NaN); + } + + throw invalidChar(read()); + }, + + zero() { + switch (c) { + case '.': + buffer += read(); + lexState = 'decimalPoint'; + return; + + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return; + + case 'x': + case 'X': + buffer += read(); + lexState = 'hexadecimal'; + return; + } + + return newToken('numeric', sign * 0); + }, + + decimalInteger() { + switch (c) { + case '.': + buffer += read(); + lexState = 'decimalPoint'; + return; + + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return; + } + + if (util$2.isDigit(c)) { + buffer += read(); + return; + } + + return newToken('numeric', sign * Number(buffer)); + }, + + decimalPointLeading() { + if (util$2.isDigit(c)) { + buffer += read(); + lexState = 'decimalFraction'; + return; + } + + throw invalidChar(read()); + }, + + decimalPoint() { + switch (c) { + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return; + } + + if (util$2.isDigit(c)) { + buffer += read(); + lexState = 'decimalFraction'; + return; + } + + return newToken('numeric', sign * Number(buffer)); + }, + + decimalFraction() { + switch (c) { + case 'e': + case 'E': + buffer += read(); + lexState = 'decimalExponent'; + return; + } + + if (util$2.isDigit(c)) { + buffer += read(); + return; + } + + return newToken('numeric', sign * Number(buffer)); + }, + + decimalExponent() { + switch (c) { + case '+': + case '-': + buffer += read(); + lexState = 'decimalExponentSign'; + return; + } + + if (util$2.isDigit(c)) { + buffer += read(); + lexState = 'decimalExponentInteger'; + return; + } + + throw invalidChar(read()); + }, + + decimalExponentSign() { + if (util$2.isDigit(c)) { + buffer += read(); + lexState = 'decimalExponentInteger'; + return; + } + + throw invalidChar(read()); + }, + + decimalExponentInteger() { + if (util$2.isDigit(c)) { + buffer += read(); + return; + } + + return newToken('numeric', sign * Number(buffer)); + }, + + hexadecimal() { + if (util$2.isHexDigit(c)) { + buffer += read(); + lexState = 'hexadecimalInteger'; + return; + } + + throw invalidChar(read()); + }, + + hexadecimalInteger() { + if (util$2.isHexDigit(c)) { + buffer += read(); + return; + } + + return newToken('numeric', sign * Number(buffer)); + }, + + string() { + switch (c) { + case '\\': + read(); + buffer += escape(); + return; + + case '"': + if (doubleQuote) { + read(); + return newToken('string', buffer); + } + + buffer += read(); + return; + + case "'": + if (!doubleQuote) { + read(); + return newToken('string', buffer); + } + + buffer += read(); + return; + + case '\n': + case '\r': + throw invalidChar(read()); + + case '\u2028': + case '\u2029': + separatorChar(c); + break; + + case undefined: + throw invalidChar(read()); + } + + buffer += read(); + }, + + start() { + switch (c) { + case '{': + case '[': + return newToken('punctuator', read()); + // This code is unreachable since the default lexState handles eof. + // case undefined: + // return newToken('eof') + } + + lexState = 'value'; + }, + + beforePropertyName() { + switch (c) { + case '$': + case '_': + buffer = read(); + lexState = 'identifierName'; + return; + + case '\\': + read(); + lexState = 'identifierNameStartEscape'; + return; + + case '}': + return newToken('punctuator', read()); + + case '"': + case "'": + doubleQuote = read() === '"'; + lexState = 'string'; + return; + } + + if (util$2.isIdStartChar(c)) { + buffer += read(); + lexState = 'identifierName'; + return; + } + + throw invalidChar(read()); + }, + + afterPropertyName() { + if (c === ':') { + return newToken('punctuator', read()); + } + + throw invalidChar(read()); + }, + + beforePropertyValue() { + lexState = 'value'; + }, + + afterPropertyValue() { + switch (c) { + case ',': + case '}': + return newToken('punctuator', read()); + } + + throw invalidChar(read()); + }, + + beforeArrayValue() { + if (c === ']') { + return newToken('punctuator', read()); + } + + lexState = 'value'; + }, + + afterArrayValue() { + switch (c) { + case ',': + case ']': + return newToken('punctuator', read()); + } + + throw invalidChar(read()); + }, + + end() { + // This code is unreachable since it's handled by the default lexState. + // if (c === undefined) { + // read() + // return newToken('eof') + // } + throw invalidChar(read()); + } + +}; + +function newToken(type, value) { + return { + type, + value, + line: line$2, + column + }; +} + +function literal(s) { + for (const c of s) { + const p = peek(); + + if (p !== c) { + throw invalidChar(read()); + } + + read(); + } +} + +function escape() { + const c = peek(); + + switch (c) { + case 'b': + read(); + return '\b'; + + case 'f': + read(); + return '\f'; + + case 'n': + read(); + return '\n'; + + case 'r': + read(); + return '\r'; + + case 't': + read(); + return '\t'; + + case 'v': + read(); + return '\v'; + + case '0': + read(); + + if (util$2.isDigit(peek())) { + throw invalidChar(read()); + } + + return '\0'; + + case 'x': + read(); + return hexEscape(); + + case 'u': + read(); + return unicodeEscape(); + + case '\n': + case '\u2028': + case '\u2029': + read(); + return ''; + + case '\r': + read(); + + if (peek() === '\n') { + read(); + } + + return ''; + + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + throw invalidChar(read()); + + case undefined: + throw invalidChar(read()); + } + + return read(); +} + +function hexEscape() { + let buffer = ''; + let c = peek(); + + if (!util$2.isHexDigit(c)) { + throw invalidChar(read()); + } + + buffer += read(); + c = peek(); + + if (!util$2.isHexDigit(c)) { + throw invalidChar(read()); + } + + buffer += read(); + return String.fromCodePoint(parseInt(buffer, 16)); +} + +function unicodeEscape() { + let buffer = ''; + let count = 4; + + while (count-- > 0) { + const c = peek(); + + if (!util$2.isHexDigit(c)) { + throw invalidChar(read()); + } + + buffer += read(); + } + + return String.fromCodePoint(parseInt(buffer, 16)); +} + +const parseStates = { + start() { + if (token.type === 'eof') { + throw invalidEOF(); + } + + push(); + }, + + beforePropertyName() { + switch (token.type) { + case 'identifier': + case 'string': + key = token.value; + parseState = 'afterPropertyName'; + return; + + case 'punctuator': + // This code is unreachable since it's handled by the lexState. + // if (token.value !== '}') { + // throw invalidToken() + // } + pop(); + return; + + case 'eof': + throw invalidEOF(); + } // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + + }, + + afterPropertyName() { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator' || token.value !== ':') { + // throw invalidToken() + // } + if (token.type === 'eof') { + throw invalidEOF(); + } + + parseState = 'beforePropertyValue'; + }, + + beforePropertyValue() { + if (token.type === 'eof') { + throw invalidEOF(); + } + + push(); + }, + + beforeArrayValue() { + if (token.type === 'eof') { + throw invalidEOF(); + } + + if (token.type === 'punctuator' && token.value === ']') { + pop(); + return; + } + + push(); + }, + + afterPropertyValue() { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + if (token.type === 'eof') { + throw invalidEOF(); + } + + switch (token.value) { + case ',': + parseState = 'beforePropertyName'; + return; + + case '}': + pop(); + } // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + + }, + + afterArrayValue() { + // This code is unreachable since it's handled by the lexState. + // if (token.type !== 'punctuator') { + // throw invalidToken() + // } + if (token.type === 'eof') { + throw invalidEOF(); + } + + switch (token.value) { + case ',': + parseState = 'beforeArrayValue'; + return; + + case ']': + pop(); + } // This code is unreachable since it's handled by the lexState. + // throw invalidToken() + + }, + + end() {// This code is unreachable since it's handled by the lexState. + // if (token.type !== 'eof') { + // throw invalidToken() + // } + } + +}; + +function push() { + let value; + + switch (token.type) { + case 'punctuator': + switch (token.value) { + case '{': + value = {}; + break; + + case '[': + value = []; + break; + } + + break; + + case 'null': + case 'boolean': + case 'numeric': + case 'string': + value = token.value; + break; + // This code is unreachable. + // default: + // throw invalidToken() + } + + if (root$1 === undefined) { + root$1 = value; + } else { + const parent = stack[stack.length - 1]; + + if (Array.isArray(parent)) { + parent.push(value); + } else { + parent[key] = value; + } + } + + if (value !== null && typeof value === 'object') { + stack.push(value); + + if (Array.isArray(value)) { + parseState = 'beforeArrayValue'; + } else { + parseState = 'beforePropertyName'; + } + } else { + const current = stack[stack.length - 1]; + + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } + } +} + +function pop() { + stack.pop(); + const current = stack[stack.length - 1]; + + if (current == null) { + parseState = 'end'; + } else if (Array.isArray(current)) { + parseState = 'afterArrayValue'; + } else { + parseState = 'afterPropertyValue'; + } +} // This code is unreachable. +// function invalidParseState () { +// return new Error(`JSON5: invalid parse state '${parseState}'`) +// } +// This code is unreachable. +// function invalidLexState (state) { +// return new Error(`JSON5: invalid lex state '${state}'`) +// } + + +function invalidChar(c) { + if (c === undefined) { + return syntaxError(`JSON5: invalid end of input at ${line$2}:${column}`); + } + + return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line$2}:${column}`); +} + +function invalidEOF() { + return syntaxError(`JSON5: invalid end of input at ${line$2}:${column}`); +} // This code is unreachable. +// function invalidToken () { +// if (token.type === 'eof') { +// return syntaxError(`JSON5: invalid end of input at ${line}:${column}`) +// } +// const c = String.fromCodePoint(token.value.codePointAt(0)) +// return syntaxError(`JSON5: invalid character '${formatChar(c)}' at ${line}:${column}`) +// } + + +function invalidIdentifier() { + column -= 5; + return syntaxError(`JSON5: invalid identifier character at ${line$2}:${column}`); +} + +function separatorChar(c) { + console.warn(`JSON5: '${formatChar(c)}' in strings is not valid ECMAScript; consider escaping`); +} + +function formatChar(c) { + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029' + }; + + if (replacements[c]) { + return replacements[c]; + } + + if (c < ' ') { + const hexString = c.charCodeAt(0).toString(16); + return '\\x' + ('00' + hexString).substring(hexString.length); + } + + return c; +} + +function syntaxError(message) { + const err = new SyntaxError(message); + err.lineNumber = line$2; + err.columnNumber = column; + return err; +} + +var stringify = function stringify(value, replacer, space) { + const stack = []; + let indent = ''; + let propertyList; + let replacerFunc; + let gap = ''; + let quote; + + if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) { + space = replacer.space; + quote = replacer.quote; + replacer = replacer.replacer; + } + + if (typeof replacer === 'function') { + replacerFunc = replacer; + } else if (Array.isArray(replacer)) { + propertyList = []; + + for (const v of replacer) { + let item; + + if (typeof v === 'string') { + item = v; + } else if (typeof v === 'number' || v instanceof String || v instanceof Number) { + item = String(v); + } + + if (item !== undefined && propertyList.indexOf(item) < 0) { + propertyList.push(item); + } + } + } + + if (space instanceof Number) { + space = Number(space); + } else if (space instanceof String) { + space = String(space); + } + + if (typeof space === 'number') { + if (space > 0) { + space = Math.min(10, Math.floor(space)); + gap = ' '.substr(0, space); + } + } else if (typeof space === 'string') { + gap = space.substr(0, 10); + } + + return serializeProperty('', { + '': value + }); + + function serializeProperty(key, holder) { + let value = holder[key]; + + if (value != null) { + if (typeof value.toJSON5 === 'function') { + value = value.toJSON5(key); + } else if (typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + } + + if (replacerFunc) { + value = replacerFunc.call(holder, key, value); + } + + if (value instanceof Number) { + value = Number(value); + } else if (value instanceof String) { + value = String(value); + } else if (value instanceof Boolean) { + value = value.valueOf(); + } + + switch (value) { + case null: + return 'null'; + + case true: + return 'true'; + + case false: + return 'false'; + } + + if (typeof value === 'string') { + return quoteString(value); + } + + if (typeof value === 'number') { + return String(value); + } + + if (typeof value === 'object') { + return Array.isArray(value) ? serializeArray(value) : serializeObject(value); + } + + return undefined; + } + + function quoteString(value) { + const quotes = { + "'": 0.1, + '"': 0.2 + }; + const replacements = { + "'": "\\'", + '"': '\\"', + '\\': '\\\\', + '\b': '\\b', + '\f': '\\f', + '\n': '\\n', + '\r': '\\r', + '\t': '\\t', + '\v': '\\v', + '\0': '\\0', + '\u2028': '\\u2028', + '\u2029': '\\u2029' + }; + let product = ''; + + for (let i = 0; i < value.length; i++) { + const c = value[i]; + + switch (c) { + case "'": + case '"': + quotes[c]++; + product += c; + continue; + + case '\0': + if (util$2.isDigit(value[i + 1])) { + product += '\\x00'; + continue; + } + + } + + if (replacements[c]) { + product += replacements[c]; + continue; + } + + if (c < ' ') { + let hexString = c.charCodeAt(0).toString(16); + product += '\\x' + ('00' + hexString).substring(hexString.length); + continue; + } + + product += c; + } + + const quoteChar = quote || Object.keys(quotes).reduce((a, b) => quotes[a] < quotes[b] ? a : b); + product = product.replace(new RegExp(quoteChar, 'g'), replacements[quoteChar]); + return quoteChar + product + quoteChar; + } + + function serializeObject(value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5'); + } + + stack.push(value); + let stepback = indent; + indent = indent + gap; + let keys = propertyList || Object.keys(value); + let partial = []; + + for (const key of keys) { + const propertyString = serializeProperty(key, value); + + if (propertyString !== undefined) { + let member = serializeKey(key) + ':'; + + if (gap !== '') { + member += ' '; + } + + member += propertyString; + partial.push(member); + } + } + + let final; + + if (partial.length === 0) { + final = '{}'; + } else { + let properties; + + if (gap === '') { + properties = partial.join(','); + final = '{' + properties + '}'; + } else { + let separator = ',\n' + indent; + properties = partial.join(separator); + final = '{\n' + indent + properties + ',\n' + stepback + '}'; + } + } + + stack.pop(); + indent = stepback; + return final; + } + + function serializeKey(key) { + if (key.length === 0) { + return quoteString(key); + } + + const firstChar = String.fromCodePoint(key.codePointAt(0)); + + if (!util$2.isIdStartChar(firstChar)) { + return quoteString(key); + } + + for (let i = firstChar.length; i < key.length; i++) { + if (!util$2.isIdContinueChar(String.fromCodePoint(key.codePointAt(i)))) { + return quoteString(key); + } + } + + return key; + } + + function serializeArray(value) { + if (stack.indexOf(value) >= 0) { + throw TypeError('Converting circular structure to JSON5'); + } + + stack.push(value); + let stepback = indent; + indent = indent + gap; + let partial = []; + + for (let i = 0; i < value.length; i++) { + const propertyString = serializeProperty(String(i), value); + partial.push(propertyString !== undefined ? propertyString : 'null'); + } + + let final; + + if (partial.length === 0) { + final = '[]'; + } else { + if (gap === '') { + let properties = partial.join(','); + final = '[' + properties + ']'; + } else { + let separator = ',\n' + indent; + let properties = partial.join(separator); + final = '[\n' + indent + properties + ',\n' + stepback + ']'; + } + } + + stack.pop(); + indent = stepback; + return final; + } +}; + +const JSON5 = { + parse: parse$2, + stringify +}; +var lib$5 = JSON5; + +var dist$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': lib$5 +}); + +var require$$0$1 = getCjsExportFromNamespace(dist$1); + +const { + parse: parse$3 +} = require$$0$1; + +var loadJson5 = function (filePath, content) { + try { + return parse$3(content); + } catch (error) { + error.message = `JSON5 Error in ${filePath}:\n${error.message}`; + throw error; + } +}; + +var caller = function () { + // see https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + var origPrepareStackTrace = Error.prepareStackTrace; + + Error.prepareStackTrace = function (_, stack) { + return stack; + }; + + var stack = new Error().stack; + Error.prepareStackTrace = origPrepareStackTrace; + return stack[2].getFileName(); +}; + +var pathParse = createCommonjsModule(function (module) { + + var isWindows = process.platform === 'win32'; // Regex to split a windows path into three parts: [*, device, slash, + // tail] windows-only + + var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; // Regex to split the tail part of the above into [*, dir, basename, ext] + + var splitTailRe = /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/; + var win32 = {}; // Function to split a filename into [root, dir, basename, ext] + + function win32SplitPath(filename) { + // Separate device+slash from tail + var result = splitDeviceRe.exec(filename), + device = (result[1] || '') + (result[2] || ''), + tail = result[3] || ''; // Split the tail into dir, basename and extension + + var result2 = splitTailRe.exec(tail), + dir = result2[1], + basename = result2[2], + ext = result2[3]; + return [device, dir, basename, ext]; + } + + win32.parse = function (pathString) { + if (typeof pathString !== 'string') { + throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString); + } + + var allParts = win32SplitPath(pathString); + + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; + }; // Split a filename into [root, dir, basename, ext], unix version + // 'root' is just a slash, or nothing. + + + var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; + var posix = {}; + + function posixSplitPath(filename) { + return splitPathRe.exec(filename).slice(1); + } + + posix.parse = function (pathString) { + if (typeof pathString !== 'string') { + throw new TypeError("Parameter 'pathString' must be a string, not " + typeof pathString); + } + + var allParts = posixSplitPath(pathString); + + if (!allParts || allParts.length !== 4) { + throw new TypeError("Invalid path '" + pathString + "'"); + } + + allParts[1] = allParts[1] || ''; + allParts[2] = allParts[2] || ''; + allParts[3] = allParts[3] || ''; + return { + root: allParts[0], + dir: allParts[0] + allParts[1].slice(0, -1), + base: allParts[2], + ext: allParts[3], + name: allParts[2].slice(0, allParts[2].length - allParts[3].length) + }; + }; + + if (isWindows) module.exports = win32.parse;else + /* posix */ + module.exports = posix.parse; + module.exports.posix = posix.parse; + module.exports.win32 = win32.parse; +}); + +var parse$4 = path__default['default'].parse || pathParse; + +var getNodeModulesDirs = function getNodeModulesDirs(absoluteStart, modules) { + var prefix = '/'; + + if (/^([A-Za-z]:)/.test(absoluteStart)) { + prefix = ''; + } else if (/^\\\\/.test(absoluteStart)) { + prefix = '\\\\'; + } + + var paths = [absoluteStart]; + var parsed = parse$4(absoluteStart); + + while (parsed.dir !== paths[paths.length - 1]) { + paths.push(parsed.dir); + parsed = parse$4(parsed.dir); + } + + return paths.reduce(function (dirs, aPath) { + return dirs.concat(modules.map(function (moduleDir) { + return path__default['default'].resolve(prefix, aPath, moduleDir); + })); + }, []); +}; + +var nodeModulesPaths = function nodeModulesPaths(start, opts, request) { + var modules = opts && opts.moduleDirectory ? [].concat(opts.moduleDirectory) : ['node_modules']; + + if (opts && typeof opts.paths === 'function') { + return opts.paths(request, start, function () { + return getNodeModulesDirs(start, modules); + }, opts); + } + + var dirs = getNodeModulesDirs(start, modules); + return opts && opts.paths ? dirs.concat(opts.paths) : dirs; +}; + +var normalizeOptions$2 = function (x, opts) { + /** + * This file is purposefully a passthrough. It's expected that third-party + * environments will override it at runtime in order to inject special logic + * into `resolve` (by manipulating the options). One such example is the PnP + * code path in Yarn. + */ + return opts || {}; +}; + +var assert = true; +var async_hooks = ">= 8"; +var buffer_ieee754 = "< 0.9.7"; +var buffer$1 = true; +var child_process = true; +var cluster = true; +var console$1 = true; +var constants$1 = true; +var crypto = true; +var _debug_agent = ">= 1 && < 8"; +var _debugger = "< 8"; +var dgram = true; +var dns = true; +var domain = true; +var events = true; +var freelist = "< 6"; +var fs = true; +var _http_agent = ">= 0.11.1"; +var _http_client = ">= 0.11.1"; +var _http_common = ">= 0.11.1"; +var _http_incoming = ">= 0.11.1"; +var _http_outgoing = ">= 0.11.1"; +var _http_server = ">= 0.11.1"; +var http = true; +var http2 = ">= 8.8"; +var https = true; +var inspector = ">= 8.0.0"; +var _linklist = "< 8"; +var module$1 = true; +var net = true; +var os = true; +var path$1 = true; +var perf_hooks = ">= 8.5"; +var process$1 = ">= 1"; +var punycode = true; +var querystring = true; +var readline = true; +var repl = true; +var smalloc = ">= 0.11.5 && < 3"; +var _stream_duplex = ">= 0.9.4"; +var _stream_transform = ">= 0.9.4"; +var _stream_wrap = ">= 1.4.1"; +var _stream_passthrough = ">= 0.9.4"; +var _stream_readable = ">= 0.9.4"; +var _stream_writable = ">= 0.9.4"; +var stream = true; +var string_decoder = true; +var sys = true; +var timers = true; +var _tls_common = ">= 0.11.13"; +var _tls_legacy = ">= 0.11.3 && < 10"; +var _tls_wrap = ">= 0.11.3"; +var tls = true; +var trace_events = ">= 10"; +var tty = true; +var url = true; +var util$3 = true; +var v8 = ">= 1"; +var vm = true; +var wasi = ">= 13.4 && < 13.5"; +var worker_threads = ">= 11.7"; +var zlib = true; +var core$1 = { + assert: assert, + async_hooks: async_hooks, + buffer_ieee754: buffer_ieee754, + buffer: buffer$1, + child_process: child_process, + cluster: cluster, + console: console$1, + constants: constants$1, + crypto: crypto, + _debug_agent: _debug_agent, + _debugger: _debugger, + dgram: dgram, + dns: dns, + domain: domain, + events: events, + freelist: freelist, + fs: fs, + "fs/promises": [ + ">= 10 && < 10.1", + ">= 14" +], + _http_agent: _http_agent, + _http_client: _http_client, + _http_common: _http_common, + _http_incoming: _http_incoming, + _http_outgoing: _http_outgoing, + _http_server: _http_server, + http: http, + http2: http2, + https: https, + inspector: inspector, + _linklist: _linklist, + module: module$1, + net: net, + "node-inspect/lib/_inspect": ">= 7.6.0 && < 12", + "node-inspect/lib/internal/inspect_client": ">= 7.6.0 && < 12", + "node-inspect/lib/internal/inspect_repl": ">= 7.6.0 && < 12", + os: os, + path: path$1, + perf_hooks: perf_hooks, + process: process$1, + punycode: punycode, + querystring: querystring, + readline: readline, + repl: repl, + smalloc: smalloc, + _stream_duplex: _stream_duplex, + _stream_transform: _stream_transform, + _stream_wrap: _stream_wrap, + _stream_passthrough: _stream_passthrough, + _stream_readable: _stream_readable, + _stream_writable: _stream_writable, + stream: stream, + string_decoder: string_decoder, + sys: sys, + timers: timers, + _tls_common: _tls_common, + _tls_legacy: _tls_legacy, + _tls_wrap: _tls_wrap, + tls: tls, + trace_events: trace_events, + tty: tty, + url: url, + util: util$3, + "v8/tools/arguments": ">= 10 && < 12", + "v8/tools/codemap": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" +], + "v8/tools/consarray": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" +], + "v8/tools/csvparser": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" +], + "v8/tools/logreader": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" +], + "v8/tools/profile_view": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" +], + "v8/tools/splaytree": [ + ">= 4.4.0 && < 5", + ">= 5.2.0 && < 12" +], + v8: v8, + vm: vm, + wasi: wasi, + worker_threads: worker_threads, + zlib: zlib +}; + +var core$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + assert: assert, + async_hooks: async_hooks, + buffer_ieee754: buffer_ieee754, + buffer: buffer$1, + child_process: child_process, + cluster: cluster, + console: console$1, + constants: constants$1, + crypto: crypto, + _debug_agent: _debug_agent, + _debugger: _debugger, + dgram: dgram, + dns: dns, + domain: domain, + events: events, + freelist: freelist, + fs: fs, + _http_agent: _http_agent, + _http_client: _http_client, + _http_common: _http_common, + _http_incoming: _http_incoming, + _http_outgoing: _http_outgoing, + _http_server: _http_server, + http: http, + http2: http2, + https: https, + inspector: inspector, + _linklist: _linklist, + module: module$1, + net: net, + os: os, + path: path$1, + perf_hooks: perf_hooks, + process: process$1, + punycode: punycode, + querystring: querystring, + readline: readline, + repl: repl, + smalloc: smalloc, + _stream_duplex: _stream_duplex, + _stream_transform: _stream_transform, + _stream_wrap: _stream_wrap, + _stream_passthrough: _stream_passthrough, + _stream_readable: _stream_readable, + _stream_writable: _stream_writable, + stream: stream, + string_decoder: string_decoder, + sys: sys, + timers: timers, + _tls_common: _tls_common, + _tls_legacy: _tls_legacy, + _tls_wrap: _tls_wrap, + tls: tls, + trace_events: trace_events, + tty: tty, + url: url, + util: util$3, + v8: v8, + vm: vm, + wasi: wasi, + worker_threads: worker_threads, + zlib: zlib, + 'default': core$1 +}); + +var data = getCjsExportFromNamespace(core$2); + +var current = process.versions && process.versions.node && process.versions.node.split('.') || []; + +function specifierIncluded(specifier) { + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + + for (var i = 0; i < 3; ++i) { + var cur = Number(current[i] || 0); + var ver = Number(versionParts[i] || 0); + + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + + if (op === '<') { + return cur < ver; + } else if (op === '>=') { + return cur >= ver; + } else { + return false; + } + } + + return op === '>='; +} + +function matchesRange(range) { + var specifiers = range.split(/ ?&& ?/); + + if (specifiers.length === 0) { + return false; + } + + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(specifiers[i])) { + return false; + } + } + + return true; +} + +function versionIncluded(specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } + + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(specifierValue[i])) { + return true; + } + } + + return false; + } + + return matchesRange(specifierValue); +} + +var core$3 = {}; + +for (var mod in data) { + // eslint-disable-line no-restricted-syntax + if (Object.prototype.hasOwnProperty.call(data, mod)) { + core$3[mod] = versionIncluded(data[mod]); + } +} + +var core_1 = core$3; + +var isCore = function isCore(x) { + return Object.prototype.hasOwnProperty.call(core_1, x); +}; + +var realpathFS = fs__default['default'].realpath && typeof fs__default['default'].realpath.native === 'function' ? fs__default['default'].realpath.native : fs__default['default'].realpath; + +var defaultIsFile = function isFile(file, cb) { + fs__default['default'].stat(file, function (err, stat) { + if (!err) { + return cb(null, stat.isFile() || stat.isFIFO()); + } + + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultIsDir = function isDirectory(dir, cb) { + fs__default['default'].stat(dir, function (err, stat) { + if (!err) { + return cb(null, stat.isDirectory()); + } + + if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return cb(null, false); + return cb(err); + }); +}; + +var defaultRealpath = function realpath(x, cb) { + realpathFS(x, function (realpathErr, realPath) { + if (realpathErr && realpathErr.code !== 'ENOENT') cb(realpathErr);else cb(null, realpathErr ? x : realPath); + }); +}; + +var maybeRealpath = function maybeRealpath(realpath, x, opts, cb) { + if (opts && opts.preserveSymlinks === false) { + realpath(x, cb); + } else { + cb(null, x); + } +}; + +var getPackageCandidates = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path__default['default'].join(dirs[i], x); + } + + return dirs; +}; + +var async = function resolve(x, options, callback) { + var cb = callback; + var opts = options; + + if (typeof options === 'function') { + cb = opts; + opts = {}; + } + + if (typeof x !== 'string') { + var err = new TypeError('Path must be a string.'); + return process.nextTick(function () { + cb(err); + }); + } + + opts = normalizeOptions$2(x, opts); + var isFile = opts.isFile || defaultIsFile; + var isDirectory = opts.isDirectory || defaultIsDir; + var readFile = opts.readFile || fs__default['default'].readFile; + var realpath = opts.realpath || defaultRealpath; + var packageIterator = opts.packageIterator; + var extensions = opts.extensions || ['.js']; + var basedir = opts.basedir || path__default['default'].dirname(caller()); + var parent = opts.filename || basedir; + opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + + var absoluteStart = path__default['default'].resolve(basedir); + maybeRealpath(realpath, absoluteStart, opts, function (err, realStart) { + if (err) cb(err);else init(realStart); + }); + var res; + + function init(basedir) { + if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) { + res = path__default['default'].resolve(basedir, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + + if (/\/$/.test(x) && res === basedir) { + loadAsDirectory(res, opts.package, onfile); + } else loadAsFile(res, opts.package, onfile); + } else if (isCore(x)) { + return cb(null, x); + } else loadNodeModules(x, basedir, function (err, n, pkg) { + if (err) cb(err);else if (n) { + return maybeRealpath(realpath, n, opts, function (err, realN) { + if (err) { + cb(err); + } else { + cb(null, realN, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function onfile(err, m, pkg) { + if (err) cb(err);else if (m) cb(null, m, pkg);else loadAsDirectory(res, function (err, d, pkg) { + if (err) cb(err);else if (d) { + maybeRealpath(realpath, d, opts, function (err, realD) { + if (err) { + cb(err); + } else { + cb(null, realD, pkg); + } + }); + } else { + var moduleError = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + moduleError.code = 'MODULE_NOT_FOUND'; + cb(moduleError); + } + }); + } + + function loadAsFile(x, thePackage, callback) { + var loadAsFilePackage = thePackage; + var cb = callback; + + if (typeof loadAsFilePackage === 'function') { + cb = loadAsFilePackage; + loadAsFilePackage = undefined; + } + + var exts = [''].concat(extensions); + load(exts, x, loadAsFilePackage); + + function load(exts, x, loadPackage) { + if (exts.length === 0) return cb(null, undefined, loadPackage); + var file = x + exts[0]; + var pkg = loadPackage; + if (pkg) onpkg(null, pkg);else loadpkg(path__default['default'].dirname(file), onpkg); + + function onpkg(err, pkg_, dir) { + pkg = pkg_; + if (err) return cb(err); + + if (dir && pkg && opts.pathFilter) { + var rfile = path__default['default'].relative(dir, file); + var rel = rfile.slice(0, rfile.length - exts[0].length); + var r = opts.pathFilter(pkg, x, rel); + if (r) return load([''].concat(extensions.slice()), path__default['default'].resolve(dir, r), pkg); + } + + isFile(file, onex); + } + + function onex(err, ex) { + if (err) return cb(err); + if (ex) return cb(null, file, pkg); + load(exts.slice(1), x, pkg); + } + } + } + + function loadpkg(dir, cb) { + if (dir === '' || dir === '/') return cb(null); + + if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) { + return cb(null); + } + + if (/[/\\]node_modules[/\\]*$/.test(dir)) return cb(null); + maybeRealpath(realpath, dir, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return loadpkg(path__default['default'].dirname(dir), cb); + var pkgfile = path__default['default'].join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + // on err, ex is false + if (!ex) return loadpkg(path__default['default'].dirname(dir), cb); + readFile(pkgfile, function (err, body) { + if (err) cb(err); + + try { + var pkg = JSON.parse(body); + } catch (jsonErr) {} + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + + cb(null, pkg, dir); + }); + }); + }); + } + + function loadAsDirectory(x, loadAsDirectoryPackage, callback) { + var cb = callback; + var fpkg = loadAsDirectoryPackage; + + if (typeof fpkg === 'function') { + cb = fpkg; + fpkg = opts.package; + } + + maybeRealpath(realpath, x, opts, function (unwrapErr, pkgdir) { + if (unwrapErr) return cb(unwrapErr); + var pkgfile = path__default['default'].join(pkgdir, 'package.json'); + isFile(pkgfile, function (err, ex) { + if (err) return cb(err); + if (!ex) return loadAsFile(path__default['default'].join(x, 'index'), fpkg, cb); + readFile(pkgfile, function (err, body) { + if (err) return cb(err); + + try { + var pkg = JSON.parse(body); + } catch (jsonErr) {} + + if (pkg && opts.packageFilter) { + pkg = opts.packageFilter(pkg, pkgfile); + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + return cb(mainError); + } + + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + + loadAsFile(path__default['default'].resolve(x, pkg.main), pkg, function (err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + if (!pkg) return loadAsFile(path__default['default'].join(x, 'index'), pkg, cb); + var dir = path__default['default'].resolve(x, pkg.main); + loadAsDirectory(dir, pkg, function (err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + loadAsFile(path__default['default'].join(x, 'index'), pkg, cb); + }); + }); + return; + } + + loadAsFile(path__default['default'].join(x, '/index'), pkg, cb); + }); + }); + }); + } + + function processDirs(cb, dirs) { + if (dirs.length === 0) return cb(null, undefined); + var dir = dirs[0]; + isDirectory(path__default['default'].dirname(dir), isdir); + + function isdir(err, isdir) { + if (err) return cb(err); + if (!isdir) return processDirs(cb, dirs.slice(1)); + loadAsFile(dir, opts.package, onfile); + } + + function onfile(err, m, pkg) { + if (err) return cb(err); + if (m) return cb(null, m, pkg); + loadAsDirectory(dir, opts.package, ondir); + } + + function ondir(err, n, pkg) { + if (err) return cb(err); + if (n) return cb(null, n, pkg); + processDirs(cb, dirs.slice(1)); + } + } + + function loadNodeModules(x, start, cb) { + var thunk = function () { + return getPackageCandidates(x, start, opts); + }; + + processDirs(cb, packageIterator ? packageIterator(x, start, thunk, opts) : thunk()); + } +}; + +var realpathFS$1 = fs__default['default'].realpathSync && typeof fs__default['default'].realpathSync.native === 'function' ? fs__default['default'].realpathSync.native : fs__default['default'].realpathSync; + +var defaultIsFile$1 = function isFile(file) { + try { + var stat = fs__default['default'].statSync(file); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + + return stat.isFile() || stat.isFIFO(); +}; + +var defaultIsDir$1 = function isDirectory(dir) { + try { + var stat = fs__default['default'].statSync(dir); + } catch (e) { + if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false; + throw e; + } + + return stat.isDirectory(); +}; + +var defaultRealpathSync = function realpathSync(x) { + try { + return realpathFS$1(x); + } catch (realpathErr) { + if (realpathErr.code !== 'ENOENT') { + throw realpathErr; + } + } + + return x; +}; + +var maybeRealpathSync = function maybeRealpathSync(realpathSync, x, opts) { + if (opts && opts.preserveSymlinks === false) { + return realpathSync(x); + } + + return x; +}; + +var getPackageCandidates$1 = function getPackageCandidates(x, start, opts) { + var dirs = nodeModulesPaths(start, opts, x); + + for (var i = 0; i < dirs.length; i++) { + dirs[i] = path__default['default'].join(dirs[i], x); + } + + return dirs; +}; + +var sync = function resolveSync(x, options) { + if (typeof x !== 'string') { + throw new TypeError('Path must be a string.'); + } + + var opts = normalizeOptions$2(x, options); + var isFile = opts.isFile || defaultIsFile$1; + var readFileSync = opts.readFileSync || fs__default['default'].readFileSync; + var isDirectory = opts.isDirectory || defaultIsDir$1; + var realpathSync = opts.realpathSync || defaultRealpathSync; + var packageIterator = opts.packageIterator; + var extensions = opts.extensions || ['.js']; + var basedir = opts.basedir || path__default['default'].dirname(caller()); + var parent = opts.filename || basedir; + opts.paths = opts.paths || []; // ensure that `basedir` is an absolute path at this point, resolving against the process' current working directory + + var absoluteStart = maybeRealpathSync(realpathSync, path__default['default'].resolve(basedir), opts); + + if (/^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[/\\])/.test(x)) { + var res = path__default['default'].resolve(absoluteStart, x); + if (x === '.' || x === '..' || x.slice(-1) === '/') res += '/'; + var m = loadAsFileSync(res) || loadAsDirectorySync(res); + if (m) return maybeRealpathSync(realpathSync, m, opts); + } else if (isCore(x)) { + return x; + } else { + var n = loadNodeModulesSync(x, absoluteStart); + if (n) return maybeRealpathSync(realpathSync, n, opts); + } + + var err = new Error("Cannot find module '" + x + "' from '" + parent + "'"); + err.code = 'MODULE_NOT_FOUND'; + throw err; + + function loadAsFileSync(x) { + var pkg = loadpkg(path__default['default'].dirname(x)); + + if (pkg && pkg.dir && pkg.pkg && opts.pathFilter) { + var rfile = path__default['default'].relative(pkg.dir, x); + var r = opts.pathFilter(pkg.pkg, x, rfile); + + if (r) { + x = path__default['default'].resolve(pkg.dir, r); // eslint-disable-line no-param-reassign + } + } + + if (isFile(x)) { + return x; + } + + for (var i = 0; i < extensions.length; i++) { + var file = x + extensions[i]; + + if (isFile(file)) { + return file; + } + } + } + + function loadpkg(dir) { + if (dir === '' || dir === '/') return; + + if (process.platform === 'win32' && /^\w:[/\\]*$/.test(dir)) { + return; + } + + if (/[/\\]node_modules[/\\]*$/.test(dir)) return; + var pkgfile = path__default['default'].join(maybeRealpathSync(realpathSync, dir, opts), 'package.json'); + + if (!isFile(pkgfile)) { + return loadpkg(path__default['default'].dirname(dir)); + } + + var body = readFileSync(pkgfile); + + try { + var pkg = JSON.parse(body); + } catch (jsonErr) {} + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, + /*pkgfile,*/ + dir); // eslint-disable-line spaced-comment + } + + return { + pkg: pkg, + dir: dir + }; + } + + function loadAsDirectorySync(x) { + var pkgfile = path__default['default'].join(maybeRealpathSync(realpathSync, x, opts), '/package.json'); + + if (isFile(pkgfile)) { + try { + var body = readFileSync(pkgfile, 'UTF8'); + var pkg = JSON.parse(body); + } catch (e) {} + + if (pkg && opts.packageFilter) { + // v2 will pass pkgfile + pkg = opts.packageFilter(pkg, + /*pkgfile,*/ + x); // eslint-disable-line spaced-comment + } + + if (pkg && pkg.main) { + if (typeof pkg.main !== 'string') { + var mainError = new TypeError('package “' + pkg.name + '” `main` must be a string'); + mainError.code = 'INVALID_PACKAGE_MAIN'; + throw mainError; + } + + if (pkg.main === '.' || pkg.main === './') { + pkg.main = 'index'; + } + + try { + var m = loadAsFileSync(path__default['default'].resolve(x, pkg.main)); + if (m) return m; + var n = loadAsDirectorySync(path__default['default'].resolve(x, pkg.main)); + if (n) return n; + } catch (e) {} + } + } + + return loadAsFileSync(path__default['default'].join(x, '/index')); + } + + function loadNodeModulesSync(x, start) { + var thunk = function () { + return getPackageCandidates$1(x, start, opts); + }; + + var dirs = packageIterator ? packageIterator(x, start, thunk, opts) : thunk(); + + for (var i = 0; i < dirs.length; i++) { + var dir = dirs[i]; + + if (isDirectory(path__default['default'].dirname(dir))) { + var m = loadAsFileSync(dir); + if (m) return m; + var n = loadAsDirectorySync(dir); + if (n) return n; + } + } + } +}; + +async.core = core_1; +async.isCore = isCore; +async.sync = sync; +var resolve = async; + +let { + resolve: resolve$1 +} = require; // In the VS Code and Atom extensions `require` is overridden and `require.resolve` doesn't support the 2nd argument. + +if (resolve$1.length === 1 || process.env.PRETTIER_FALLBACK_RESOLVE) { + resolve$1 = (id, options) => { + let basedir; + + if (options && options.paths && options.paths.length === 1) { + basedir = options.paths[0]; + } + + return resolve.sync(id, { + basedir + }); + }; +} + +var resolve_1 = resolve$1; + +var semver$2 = createCommonjsModule(function (module, exports) { + exports = module.exports = SemVer; + var debug; + /* istanbul ignore next */ + + if (typeof process === 'object' && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0); + args.unshift('SEMVER'); + console.log.apply(console, args); + }; + } else { + debug = function () {}; + } // Note: this is the semver.org version of the spec that it implements + // Not necessarily the package version of this code. + + + exports.SEMVER_SPEC_VERSION = '2.0.0'; + var MAX_LENGTH = 256; + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ + 9007199254740991; // Max safe segment length for coercion. + + var MAX_SAFE_COMPONENT_LENGTH = 16; // The actual regexps go on exports.re + + var re = exports.re = []; + var src = exports.src = []; + var R = 0; // The following Regular Expressions can be used for tokenizing, + // validating, and parsing SemVer version strings. + // ## Numeric Identifier + // A single `0`, or a non-zero digit followed by zero or more digits. + + var NUMERICIDENTIFIER = R++; + src[NUMERICIDENTIFIER] = '0|[1-9]\\d*'; + var NUMERICIDENTIFIERLOOSE = R++; + src[NUMERICIDENTIFIERLOOSE] = '[0-9]+'; // ## Non-numeric Identifier + // Zero or more digits, followed by a letter or hyphen, and then zero or + // more letters, digits, or hyphens. + + var NONNUMERICIDENTIFIER = R++; + src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*'; // ## Main Version + // Three dot-separated numeric identifiers. + + var MAINVERSION = R++; + src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')\\.' + '(' + src[NUMERICIDENTIFIER] + ')'; + var MAINVERSIONLOOSE = R++; + src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + '(' + src[NUMERICIDENTIFIERLOOSE] + ')'; // ## Pre-release Version Identifier + // A numeric identifier, or a non-numeric identifier. + + var PRERELEASEIDENTIFIER = R++; + src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + '|' + src[NONNUMERICIDENTIFIER] + ')'; + var PRERELEASEIDENTIFIERLOOSE = R++; + src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + '|' + src[NONNUMERICIDENTIFIER] + ')'; // ## Pre-release Version + // Hyphen, followed by one or more dot-separated pre-release version + // identifiers. + + var PRERELEASE = R++; + src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))'; + var PRERELEASELOOSE = R++; + src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))'; // ## Build Metadata Identifier + // Any combination of digits, letters, or hyphens. + + var BUILDIDENTIFIER = R++; + src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+'; // ## Build Metadata + // Plus sign, followed by one or more period-separated build metadata + // identifiers. + + var BUILD = R++; + src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))'; // ## Full Version String + // A main version, followed optionally by a pre-release version and + // build metadata. + // Note that the only major, minor, patch, and pre-release sections of + // the version string are capturing groups. The build metadata is not a + // capturing group, because it should not ever be used in version + // comparison. + + var FULL = R++; + var FULLPLAIN = 'v?' + src[MAINVERSION] + src[PRERELEASE] + '?' + src[BUILD] + '?'; + src[FULL] = '^' + FULLPLAIN + '$'; // like full, but allows v1.2.3 and =1.2.3, which people do sometimes. + // also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty + // common in the npm registry. + + var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + src[PRERELEASELOOSE] + '?' + src[BUILD] + '?'; + var LOOSE = R++; + src[LOOSE] = '^' + LOOSEPLAIN + '$'; + var GTLT = R++; + src[GTLT] = '((?:<|>)?=?)'; // Something like "2.*" or "1.2.x". + // Note that "x.x" is a valid xRange identifer, meaning "any version" + // Only the first item is strictly required. + + var XRANGEIDENTIFIERLOOSE = R++; + src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*'; + var XRANGEIDENTIFIER = R++; + src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*'; + var XRANGEPLAIN = R++; + src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + '(?:' + src[PRERELEASE] + ')?' + src[BUILD] + '?' + ')?)?'; + var XRANGEPLAINLOOSE = R++; + src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + '(?:' + src[PRERELEASELOOSE] + ')?' + src[BUILD] + '?' + ')?)?'; + var XRANGE = R++; + src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$'; + var XRANGELOOSE = R++; + src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$'; // Coercion. + // Extract anything that could conceivably be a part of a valid semver + + var COERCE = R++; + src[COERCE] = '(?:^|[^\\d])' + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + '(?:$|[^\\d])'; // Tilde ranges. + // Meaning is "reasonably at or greater than" + + var LONETILDE = R++; + src[LONETILDE] = '(?:~>?)'; + var TILDETRIM = R++; + src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+'; + re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g'); + var tildeTrimReplace = '$1~'; + var TILDE = R++; + src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$'; + var TILDELOOSE = R++; + src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$'; // Caret ranges. + // Meaning is "at least and backwards compatible with" + + var LONECARET = R++; + src[LONECARET] = '(?:\\^)'; + var CARETTRIM = R++; + src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+'; + re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g'); + var caretTrimReplace = '$1^'; + var CARET = R++; + src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$'; + var CARETLOOSE = R++; + src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$'; // A simple gt/lt/eq thing, or just "" to indicate "any version" + + var COMPARATORLOOSE = R++; + src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$'; + var COMPARATOR = R++; + src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$'; // An expression to strip any whitespace between the gtlt and the thing + // it modifies, so that `> 1.2.3` ==> `>1.2.3` + + var COMPARATORTRIM = R++; + src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')'; // this one has to use the /g flag + + re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g'); + var comparatorTrimReplace = '$1$2$3'; // Something like `1.2.3 - 1.2.4` + // Note that these all use the loose form, because they'll be + // checked against either the strict or loose comparator form + // later. + + var HYPHENRANGE = R++; + src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAIN] + ')' + '\\s*$'; + var HYPHENRANGELOOSE = R++; + src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + '\\s+-\\s+' + '(' + src[XRANGEPLAINLOOSE] + ')' + '\\s*$'; // Star ranges basically just allow anything at all. + + var STAR = R++; + src[STAR] = '(<|>)?=?\\s*\\*'; // Compile to actual regexp objects. + // All are flag-free, unless they were created above with a flag. + + for (var i = 0; i < R; i++) { + debug(i, src[i]); + + if (!re[i]) { + re[i] = new RegExp(src[i]); + } + } + + exports.parse = parse; + + function parse(version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (version instanceof SemVer) { + return version; + } + + if (typeof version !== 'string') { + return null; + } + + if (version.length > MAX_LENGTH) { + return null; + } + + var r = options.loose ? re[LOOSE] : re[FULL]; + + if (!r.test(version)) { + return null; + } + + try { + return new SemVer(version, options); + } catch (er) { + return null; + } + } + + exports.valid = valid; + + function valid(version, options) { + var v = parse(version, options); + return v ? v.version : null; + } + + exports.clean = clean; + + function clean(version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options); + return s ? s.version : null; + } + + exports.SemVer = SemVer; + + function SemVer(version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version; + } else { + version = version.version; + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version); + } + + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters'); + } + + if (!(this instanceof SemVer)) { + return new SemVer(version, options); + } + + debug('SemVer', version, options); + this.options = options; + this.loose = !!options.loose; + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]); + + if (!m) { + throw new TypeError('Invalid Version: ' + version); + } + + this.raw = version; // these are actually numbers + + this.major = +m[1]; + this.minor = +m[2]; + this.patch = +m[3]; + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version'); + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version'); + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version'); + } // numberify any prerelease numeric ids + + + if (!m[4]) { + this.prerelease = []; + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id; + + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num; + } + } + + return id; + }); + } + + this.build = m[5] ? m[5].split('.') : []; + this.format(); + } + + SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch; + + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.'); + } + + return this.version; + }; + + SemVer.prototype.toString = function () { + return this.version; + }; + + SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other); + + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + return this.compareMain(other) || this.comparePre(other); + }; + + SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } + + return compareIdentifiers(this.major, other.major) || compareIdentifiers(this.minor, other.minor) || compareIdentifiers(this.patch, other.patch); + }; + + SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options); + } // NOT having a prerelease is > having one + + + if (this.prerelease.length && !other.prerelease.length) { + return -1; + } else if (!this.prerelease.length && other.prerelease.length) { + return 1; + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0; + } + + var i = 0; + + do { + var a = this.prerelease[i]; + var b = other.prerelease[i]; + debug('prerelease compare', i, a, b); + + if (a === undefined && b === undefined) { + return 0; + } else if (b === undefined) { + return 1; + } else if (a === undefined) { + return -1; + } else if (a === b) { + continue; + } else { + return compareIdentifiers(a, b); + } + } while (++i); + }; // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + + + SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0; + this.patch = 0; + this.minor = 0; + this.major++; + this.inc('pre', identifier); + break; + + case 'preminor': + this.prerelease.length = 0; + this.patch = 0; + this.minor++; + this.inc('pre', identifier); + break; + + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0; + this.inc('patch', identifier); + this.inc('pre', identifier); + break; + // If the input is a non-prerelease version, this acts the same as + // prepatch. + + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier); + } + + this.inc('pre', identifier); + break; + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || this.patch !== 0 || this.prerelease.length === 0) { + this.major++; + } + + this.minor = 0; + this.patch = 0; + this.prerelease = []; + break; + + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++; + } + + this.patch = 0; + this.prerelease = []; + break; + + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++; + } + + this.prerelease = []; + break; + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0]; + } else { + var i = this.prerelease.length; + + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++; + i = -2; + } + } + + if (i === -1) { + // didn't increment anything + this.prerelease.push(0); + } + } + + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0]; + } + } else { + this.prerelease = [identifier, 0]; + } + } + + break; + + default: + throw new Error('invalid increment argument: ' + release); + } + + this.format(); + this.raw = this.version; + return this; + }; + + exports.inc = inc; + + function inc(version, release, loose, identifier) { + if (typeof loose === 'string') { + identifier = loose; + loose = undefined; + } + + try { + return new SemVer(version, loose).inc(release, identifier).version; + } catch (er) { + return null; + } + } + + exports.diff = diff; + + function diff(version1, version2) { + if (eq(version1, version2)) { + return null; + } else { + var v1 = parse(version1); + var v2 = parse(version2); + var prefix = ''; + + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre'; + var defaultResult = 'prerelease'; + } + + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key; + } + } + } + + return defaultResult; // may be undefined + } + } + + exports.compareIdentifiers = compareIdentifiers; + var numeric = /^[0-9]+$/; + + function compareIdentifiers(a, b) { + var anum = numeric.test(a); + var bnum = numeric.test(b); + + if (anum && bnum) { + a = +a; + b = +b; + } + + return a === b ? 0 : anum && !bnum ? -1 : bnum && !anum ? 1 : a < b ? -1 : 1; + } + + exports.rcompareIdentifiers = rcompareIdentifiers; + + function rcompareIdentifiers(a, b) { + return compareIdentifiers(b, a); + } + + exports.major = major; + + function major(a, loose) { + return new SemVer(a, loose).major; + } + + exports.minor = minor; + + function minor(a, loose) { + return new SemVer(a, loose).minor; + } + + exports.patch = patch; + + function patch(a, loose) { + return new SemVer(a, loose).patch; + } + + exports.compare = compare; + + function compare(a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)); + } + + exports.compareLoose = compareLoose; + + function compareLoose(a, b) { + return compare(a, b, true); + } + + exports.rcompare = rcompare; + + function rcompare(a, b, loose) { + return compare(b, a, loose); + } + + exports.sort = sort; + + function sort(list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose); + }); + } + + exports.rsort = rsort; + + function rsort(list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose); + }); + } + + exports.gt = gt; + + function gt(a, b, loose) { + return compare(a, b, loose) > 0; + } + + exports.lt = lt; + + function lt(a, b, loose) { + return compare(a, b, loose) < 0; + } + + exports.eq = eq; + + function eq(a, b, loose) { + return compare(a, b, loose) === 0; + } + + exports.neq = neq; + + function neq(a, b, loose) { + return compare(a, b, loose) !== 0; + } + + exports.gte = gte; + + function gte(a, b, loose) { + return compare(a, b, loose) >= 0; + } + + exports.lte = lte; + + function lte(a, b, loose) { + return compare(a, b, loose) <= 0; + } + + exports.cmp = cmp; + + function cmp(a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + return a === b; + + case '!==': + if (typeof a === 'object') a = a.version; + if (typeof b === 'object') b = b.version; + return a !== b; + + case '': + case '=': + case '==': + return eq(a, b, loose); + + case '!=': + return neq(a, b, loose); + + case '>': + return gt(a, b, loose); + + case '>=': + return gte(a, b, loose); + + case '<': + return lt(a, b, loose); + + case '<=': + return lte(a, b, loose); + + default: + throw new TypeError('Invalid operator: ' + op); + } + } + + exports.Comparator = Comparator; + + function Comparator(comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp; + } else { + comp = comp.value; + } + } + + if (!(this instanceof Comparator)) { + return new Comparator(comp, options); + } + + debug('comparator', comp, options); + this.options = options; + this.loose = !!options.loose; + this.parse(comp); + + if (this.semver === ANY) { + this.value = ''; + } else { + this.value = this.operator + this.semver.version; + } + + debug('comp', this); + } + + var ANY = {}; + + Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var m = comp.match(r); + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp); + } + + this.operator = m[1]; + + if (this.operator === '=') { + this.operator = ''; + } // if it literally is just '>' or '' then allow anything. + + + if (!m[2]) { + this.semver = ANY; + } else { + this.semver = new SemVer(m[2], this.options.loose); + } + }; + + Comparator.prototype.toString = function () { + return this.value; + }; + + Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose); + + if (this.semver === ANY) { + return true; + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options); + } + + return cmp(version, this.operator, this.semver, this.options); + }; + + Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required'); + } + + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + var rangeTmp; + + if (this.operator === '') { + rangeTmp = new Range(comp.value, options); + return satisfies(this.value, rangeTmp, options); + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options); + return satisfies(comp.semver, rangeTmp, options); + } + + var sameDirectionIncreasing = (this.operator === '>=' || this.operator === '>') && (comp.operator === '>=' || comp.operator === '>'); + var sameDirectionDecreasing = (this.operator === '<=' || this.operator === '<') && (comp.operator === '<=' || comp.operator === '<'); + var sameSemVer = this.semver.version === comp.semver.version; + var differentDirectionsInclusive = (this.operator === '>=' || this.operator === '<=') && (comp.operator === '>=' || comp.operator === '<='); + var oppositeDirectionsLessThan = cmp(this.semver, '<', comp.semver, options) && (this.operator === '>=' || this.operator === '>') && (comp.operator === '<=' || comp.operator === '<'); + var oppositeDirectionsGreaterThan = cmp(this.semver, '>', comp.semver, options) && (this.operator === '<=' || this.operator === '<') && (comp.operator === '>=' || comp.operator === '>'); + return sameDirectionIncreasing || sameDirectionDecreasing || sameSemVer && differentDirectionsInclusive || oppositeDirectionsLessThan || oppositeDirectionsGreaterThan; + }; + + exports.Range = Range; + + function Range(range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + }; + } + + if (range instanceof Range) { + if (range.loose === !!options.loose && range.includePrerelease === !!options.includePrerelease) { + return range; + } else { + return new Range(range.raw, options); + } + } + + if (range instanceof Comparator) { + return new Range(range.value, options); + } + + if (!(this instanceof Range)) { + return new Range(range, options); + } + + this.options = options; + this.loose = !!options.loose; + this.includePrerelease = !!options.includePrerelease; // First, split based on boolean or || + + this.raw = range; + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()); + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length; + }); + + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range); + } + + this.format(); + } + + Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim(); + }).join('||').trim(); + return this.range; + }; + + Range.prototype.toString = function () { + return this.range; + }; + + Range.prototype.parseRange = function (range) { + var loose = this.options.loose; + range = range.trim(); // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE]; + range = range.replace(hr, hyphenReplace); + debug('hyphen replace', range); // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace); + debug('comparator trim', range, re[COMPARATORTRIM]); // `~ 1.2.3` => `~1.2.3` + + range = range.replace(re[TILDETRIM], tildeTrimReplace); // `^ 1.2.3` => `^1.2.3` + + range = range.replace(re[CARETTRIM], caretTrimReplace); // normalize spaces + + range = range.split(/\s+/).join(' '); // At this point, the range is completely trimmed and + // ready to be split into comparators. + + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR]; + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options); + }, this).join(' ').split(/\s+/); + + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe); + }); + } + + set = set.map(function (comp) { + return new Comparator(comp, this.options); + }, this); + return set; + }; + + Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required'); + } + + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options); + }); + }); + }); + }); + }; // Mostly just for testing and legacy API reasons + + + exports.toComparators = toComparators; + + function toComparators(range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value; + }).join(' ').trim().split(' '); + }); + } // comprised of xranges, tildes, stars, and gtlt's at this point. + // already replaced the hyphen ranges + // turn into a set of JUST comparators. + + + function parseComparator(comp, options) { + debug('comp', comp, options); + comp = replaceCarets(comp, options); + debug('caret', comp); + comp = replaceTildes(comp, options); + debug('tildes', comp); + comp = replaceXRanges(comp, options); + debug('xrange', comp); + comp = replaceStars(comp, options); + debug('stars', comp); + return comp; + } + + function isX(id) { + return !id || id.toLowerCase() === 'x' || id === '*'; + } // ~, ~> --> * (any, kinda silly) + // ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 + // ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 + // ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 + // ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 + // ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 + + + function replaceTildes(comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options); + }).join(' '); + } + + function replaceTilde(comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } else if (pr) { + debug('replaceTilde pr', pr); + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0'; + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; + } + + debug('tilde return', ret); + return ret; + }); + } // ^ --> * (any, kinda silly) + // ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 + // ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 + // ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 + // ^1.2.3 --> >=1.2.3 <2.0.0 + // ^1.2.0 --> >=1.2.0 <2.0.0 + + + function replaceCarets(comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options); + }).join(' '); + } + + function replaceCaret(comp, options) { + debug('caret', comp, options); + var r = options.loose ? re[CARETLOOSE] : re[CARET]; + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr); + var ret; + + if (isX(M)) { + ret = ''; + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0'; + } + } else if (pr) { + debug('replaceCaret pr', pr); + + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + m + '.' + (+p + 1); + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + M + '.' + (+m + 1) + '.0'; + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + ' <' + (+M + 1) + '.0.0'; + } + } else { + debug('no pr'); + + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + m + '.' + (+p + 1); + } else { + ret = '>=' + M + '.' + m + '.' + p + ' <' + M + '.' + (+m + 1) + '.0'; + } + } else { + ret = '>=' + M + '.' + m + '.' + p + ' <' + (+M + 1) + '.0.0'; + } + } + + debug('caret return', ret); + return ret; + }); + } + + function replaceXRanges(comp, options) { + debug('replaceXRanges', comp, options); + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options); + }).join(' '); + } + + function replaceXRange(comp, options) { + comp = comp.trim(); + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE]; + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr); + var xM = isX(M); + var xm = xM || isX(m); + var xp = xm || isX(p); + var anyX = xp; + + if (gtlt === '=' && anyX) { + gtlt = ''; + } + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0'; + } else { + // nothing is forbidden + ret = '*'; + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0; + } + + p = 0; + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>='; + + if (xm) { + M = +M + 1; + m = 0; + p = 0; + } else { + m = +m + 1; + p = 0; + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<'; + + if (xm) { + M = +M + 1; + } else { + m = +m + 1; + } + } + + ret = gtlt + M + '.' + m + '.' + p; + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0'; + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0'; + } + + debug('xRange return', ret); + return ret; + }); + } // Because * is AND-ed with everything else in the comparator, + // and '' means "any version", just remove the *s entirely. + + + function replaceStars(comp, options) { + debug('replaceStars', comp, options); // Looseness is ignored here. star is always as loose as it gets! + + return comp.trim().replace(re[STAR], ''); + } // This function is passed to string.replace(re[HYPHENRANGE]) + // M, m, patch, prerelease, build + // 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 + // 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do + // 1.2 - 3.4 => >=1.2.0 <3.5.0 + + + function hyphenReplace($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = ''; + } else if (isX(fm)) { + from = '>=' + fM + '.0.0'; + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0'; + } else { + from = '>=' + from; + } + + if (isX(tM)) { + to = ''; + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0'; + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0'; + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr; + } else { + to = '<=' + to; + } + + return (from + ' ' + to).trim(); + } // if ANY of the sets match ALL of its comparators, then pass + + + Range.prototype.test = function (version) { + if (!version) { + return false; + } + + if (typeof version === 'string') { + version = new SemVer(version, this.options); + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true; + } + } + + return false; + }; + + function testSet(set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false; + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver); + + if (set[i].semver === ANY) { + continue; + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver; + + if (allowed.major === version.major && allowed.minor === version.minor && allowed.patch === version.patch) { + return true; + } + } + } // Version has a -pre, but it's not one of the ones we like. + + + return false; + } + + return true; + } + + exports.satisfies = satisfies; + + function satisfies(version, range, options) { + try { + range = new Range(range, options); + } catch (er) { + return false; + } + + return range.test(version); + } + + exports.maxSatisfying = maxSatisfying; + + function maxSatisfying(versions, range, options) { + var max = null; + var maxSV = null; + + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null; + } + + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v; + maxSV = new SemVer(max, options); + } + } + }); + return max; + } + + exports.minSatisfying = minSatisfying; + + function minSatisfying(versions, range, options) { + var min = null; + var minSV = null; + + try { + var rangeObj = new Range(range, options); + } catch (er) { + return null; + } + + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v; + minSV = new SemVer(min, options); + } + } + }); + return min; + } + + exports.minVersion = minVersion; + + function minVersion(range, loose) { + range = new Range(range, loose); + var minver = new SemVer('0.0.0'); + + if (range.test(minver)) { + return minver; + } + + minver = new SemVer('0.0.0-0'); + + if (range.test(minver)) { + return minver; + } + + minver = null; + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version); + + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++; + } else { + compver.prerelease.push(0); + } + + compver.raw = compver.format(); + + /* fallthrough */ + + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver; + } + + break; + + case '<': + case '<=': + /* Ignore maximum versions */ + break; + + /* istanbul ignore next */ + + default: + throw new Error('Unexpected operation: ' + comparator.operator); + } + }); + } + + if (minver && range.test(minver)) { + return minver; + } + + return null; + } + + exports.validRange = validRange; + + function validRange(range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*'; + } catch (er) { + return null; + } + } // Determine if version is less than all the versions possible in the range + + + exports.ltr = ltr; + + function ltr(version, range, options) { + return outside(version, range, '<', options); + } // Determine if version is greater than all the versions possible in the range. + + + exports.gtr = gtr; + + function gtr(version, range, options) { + return outside(version, range, '>', options); + } + + exports.outside = outside; + + function outside(version, range, hilo, options) { + version = new SemVer(version, options); + range = new Range(range, options); + var gtfn, ltefn, ltfn, comp, ecomp; + + switch (hilo) { + case '>': + gtfn = gt; + ltefn = lte; + ltfn = lt; + comp = '>'; + ecomp = '>='; + break; + + case '<': + gtfn = lt; + ltefn = gte; + ltfn = gt; + comp = '<'; + ecomp = '<='; + break; + + default: + throw new TypeError('Must provide a hilo val of "<" or ">"'); + } // If it satisifes the range it is not outside + + + if (satisfies(version, range, options)) { + return false; + } // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i]; + var high = null; + var low = null; + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0'); + } + + high = high || comparator; + low = low || comparator; + + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator; + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator; + } + }); // If the edge version comparator has a operator then our version + // isn't outside it + + if (high.operator === comp || high.operator === ecomp) { + return false; + } // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + + + if ((!low.operator || low.operator === comp) && ltefn(version, low.semver)) { + return false; + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false; + } + } + + return true; + } + + exports.prerelease = prerelease; + + function prerelease(version, options) { + var parsed = parse(version, options); + return parsed && parsed.prerelease.length ? parsed.prerelease : null; + } + + exports.intersects = intersects; + + function intersects(r1, r2, options) { + r1 = new Range(r1, options); + r2 = new Range(r2, options); + return r1.intersects(r2); + } + + exports.coerce = coerce; + + function coerce(version) { + if (version instanceof SemVer) { + return version; + } + + if (typeof version !== 'string') { + return null; + } + + var match = version.match(re[COERCE]); + + if (match == null) { + return null; + } + + return parse(match[1] + '.' + (match[2] || '0') + '.' + (match[3] || '0')); + } +}); + +var hasOwnProperty$3 = Object.prototype.hasOwnProperty; +var pseudomap = PseudoMap; + +function PseudoMap(set) { + if (!(this instanceof PseudoMap)) // whyyyyyyy + throw new TypeError("Constructor PseudoMap requires 'new'"); + this.clear(); + + if (set) { + if (set instanceof PseudoMap || typeof Map === 'function' && set instanceof Map) set.forEach(function (value, key) { + this.set(key, value); + }, this);else if (Array.isArray(set)) set.forEach(function (kv) { + this.set(kv[0], kv[1]); + }, this);else throw new TypeError('invalid argument'); + } +} + +PseudoMap.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + Object.keys(this._data).forEach(function (k) { + if (k !== 'size') fn.call(thisp, this._data[k].value, this._data[k].key); + }, this); +}; + +PseudoMap.prototype.has = function (k) { + return !!find(this._data, k); +}; + +PseudoMap.prototype.get = function (k) { + var res = find(this._data, k); + return res && res.value; +}; + +PseudoMap.prototype.set = function (k, v) { + set(this._data, k, v); +}; + +PseudoMap.prototype.delete = function (k) { + var res = find(this._data, k); + + if (res) { + delete this._data[res._index]; + this._data.size--; + } +}; + +PseudoMap.prototype.clear = function () { + var data = Object.create(null); + data.size = 0; + Object.defineProperty(this, '_data', { + value: data, + enumerable: false, + configurable: true, + writable: false + }); +}; + +Object.defineProperty(PseudoMap.prototype, 'size', { + get: function () { + return this._data.size; + }, + set: function (n) {}, + enumerable: true, + configurable: true +}); + +PseudoMap.prototype.values = PseudoMap.prototype.keys = PseudoMap.prototype.entries = function () { + throw new Error('iterators are not implemented in this version'); +}; // Either identical, or both NaN + + +function same(a, b) { + return a === b || a !== a && b !== b; +} + +function Entry(k, v, i) { + this.key = k; + this.value = v; + this._index = i; +} + +function find(data, k) { + for (var i = 0, s = '_' + k, key = s; hasOwnProperty$3.call(data, key); key = s + i++) { + if (same(data[key].key, k)) return data[key]; + } +} + +function set(data, k, v) { + for (var i = 0, s = '_' + k, key = s; hasOwnProperty$3.call(data, key); key = s + i++) { + if (same(data[key].key, k)) { + data[key].value = v; + return; + } + } + + data.size++; + data[key] = new Entry(k, v, key); +} + +var map = createCommonjsModule(function (module) { + if (process.env.npm_package_name === 'pseudomap' && process.env.npm_lifecycle_script === 'test') process.env.TEST_PSEUDOMAP = 'true'; + + if (typeof Map === 'function' && !process.env.TEST_PSEUDOMAP) { + module.exports = Map; + } else { + module.exports = pseudomap; + } +}); + +var yallist = Yallist; +Yallist.Node = Node; +Yallist.create = Yallist; + +function Yallist(list) { + var self = this; + + if (!(self instanceof Yallist)) { + self = new Yallist(); + } + + self.tail = null; + self.head = null; + self.length = 0; + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item); + }); + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]); + } + } + + return self; +} + +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list'); + } + + var next = node.next; + var prev = node.prev; + + if (next) { + next.prev = prev; + } + + if (prev) { + prev.next = next; + } + + if (node === this.head) { + this.head = next; + } + + if (node === this.tail) { + this.tail = prev; + } + + node.list.length--; + node.next = null; + node.prev = null; + node.list = null; +}; + +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return; + } + + if (node.list) { + node.list.removeNode(node); + } + + var head = this.head; + node.list = this; + node.next = head; + + if (head) { + head.prev = node; + } + + this.head = node; + + if (!this.tail) { + this.tail = node; + } + + this.length++; +}; + +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return; + } + + if (node.list) { + node.list.removeNode(node); + } + + var tail = this.tail; + node.list = this; + node.prev = tail; + + if (tail) { + tail.next = node; + } + + this.tail = node; + + if (!this.head) { + this.head = node; + } + + this.length++; +}; + +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push$1(this, arguments[i]); + } + + return this.length; +}; + +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]); + } + + return this.length; +}; + +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined; + } + + var res = this.tail.value; + this.tail = this.tail.prev; + + if (this.tail) { + this.tail.next = null; + } else { + this.head = null; + } + + this.length--; + return res; +}; + +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined; + } + + var res = this.head.value; + this.head = this.head.next; + + if (this.head) { + this.head.prev = null; + } else { + this.tail = null; + } + + this.length--; + return res; +}; + +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this); + walker = walker.next; + } +}; + +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this; + + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this); + walker = walker.prev; + } +}; + +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next; + } + + if (i === n && walker !== null) { + return walker.value; + } +}; + +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev; + } + + if (i === n && walker !== null) { + return walker.value; + } +}; + +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist(); + + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.next; + } + + return res; +}; + +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this; + var res = new Yallist(); + + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)); + walker = walker.prev; + } + + return res; +}; + +Yallist.prototype.reduce = function (fn, initial) { + var acc; + var walker = this.head; + + if (arguments.length > 1) { + acc = initial; + } else if (this.head) { + walker = this.head.next; + acc = this.head.value; + } else { + throw new TypeError('Reduce of empty list with no initial value'); + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i); + walker = walker.next; + } + + return acc; +}; + +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc; + var walker = this.tail; + + if (arguments.length > 1) { + acc = initial; + } else if (this.tail) { + walker = this.tail.prev; + acc = this.tail.value; + } else { + throw new TypeError('Reduce of empty list with no initial value'); + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i); + walker = walker.prev; + } + + return acc; +}; + +Yallist.prototype.toArray = function () { + var arr = new Array(this.length); + + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.next; + } + + return arr; +}; + +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length); + + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value; + walker = walker.prev; + } + + return arr; +}; + +Yallist.prototype.slice = function (from, to) { + to = to || this.length; + + if (to < 0) { + to += this.length; + } + + from = from || 0; + + if (from < 0) { + from += this.length; + } + + var ret = new Yallist(); + + if (to < from || to < 0) { + return ret; + } + + if (from < 0) { + from = 0; + } + + if (to > this.length) { + to = this.length; + } + + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next; + } + + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value); + } + + return ret; +}; + +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length; + + if (to < 0) { + to += this.length; + } + + from = from || 0; + + if (from < 0) { + from += this.length; + } + + var ret = new Yallist(); + + if (to < from || to < 0) { + return ret; + } + + if (from < 0) { + from = 0; + } + + if (to > this.length) { + to = this.length; + } + + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev; + } + + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value); + } + + return ret; +}; + +Yallist.prototype.reverse = function () { + var head = this.head; + var tail = this.tail; + + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev; + walker.prev = walker.next; + walker.next = p; + } + + this.head = tail; + this.tail = head; + return this; +}; + +function push$1(self, item) { + self.tail = new Node(item, self.tail, null, self); + + if (!self.head) { + self.head = self.tail; + } + + self.length++; +} + +function unshift(self, item) { + self.head = new Node(item, null, self.head, self); + + if (!self.tail) { + self.tail = self.head; + } + + self.length++; +} + +function Node(value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list); + } + + this.list = list; + this.value = value; + + if (prev) { + prev.next = this; + this.prev = prev; + } else { + this.prev = null; + } + + if (next) { + next.prev = this; + this.next = next; + } else { + this.next = null; + } +} + +var lruCache = LRUCache; // This will be a proper iterable 'Map' in engines that support it, +// or a fakey-fake PseudoMap in older versions. +// A linked list to keep track of recently-used-ness +// use symbols if possible, otherwise just _props + +var hasSymbol = typeof Symbol === 'function' && process.env._nodeLRUCacheForceNoSymbol !== '1'; +var makeSymbol; + +if (hasSymbol) { + makeSymbol = function (key) { + return Symbol(key); + }; +} else { + makeSymbol = function (key) { + return '_' + key; + }; +} + +var MAX = makeSymbol('max'); +var LENGTH = makeSymbol('length'); +var LENGTH_CALCULATOR = makeSymbol('lengthCalculator'); +var ALLOW_STALE = makeSymbol('allowStale'); +var MAX_AGE = makeSymbol('maxAge'); +var DISPOSE = makeSymbol('dispose'); +var NO_DISPOSE_ON_SET = makeSymbol('noDisposeOnSet'); +var LRU_LIST = makeSymbol('lruList'); +var CACHE = makeSymbol('cache'); + +function naiveLength() { + return 1; +} // lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. + + +function LRUCache(options) { + if (!(this instanceof LRUCache)) { + return new LRUCache(options); + } + + if (typeof options === 'number') { + options = { + max: options + }; + } + + if (!options) { + options = {}; + } + + var max = this[MAX] = options.max; // Kind of weird to have a default max of Infinity, but oh well. + + if (!max || !(typeof max === 'number') || max <= 0) { + this[MAX] = Infinity; + } + + var lc = options.length || naiveLength; + + if (typeof lc !== 'function') { + lc = naiveLength; + } + + this[LENGTH_CALCULATOR] = lc; + this[ALLOW_STALE] = options.stale || false; + this[MAX_AGE] = options.maxAge || 0; + this[DISPOSE] = options.dispose; + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false; + this.reset(); +} // resize the cache when the max changes. + + +Object.defineProperty(LRUCache.prototype, 'max', { + set: function (mL) { + if (!mL || !(typeof mL === 'number') || mL <= 0) { + mL = Infinity; + } + + this[MAX] = mL; + trim$2(this); + }, + get: function () { + return this[MAX]; + }, + enumerable: true +}); +Object.defineProperty(LRUCache.prototype, 'allowStale', { + set: function (allowStale) { + this[ALLOW_STALE] = !!allowStale; + }, + get: function () { + return this[ALLOW_STALE]; + }, + enumerable: true +}); +Object.defineProperty(LRUCache.prototype, 'maxAge', { + set: function (mA) { + if (!mA || !(typeof mA === 'number') || mA < 0) { + mA = 0; + } + + this[MAX_AGE] = mA; + trim$2(this); + }, + get: function () { + return this[MAX_AGE]; + }, + enumerable: true +}); // resize the cache when the lengthCalculator changes. + +Object.defineProperty(LRUCache.prototype, 'lengthCalculator', { + set: function (lC) { + if (typeof lC !== 'function') { + lC = naiveLength; + } + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC; + this[LENGTH] = 0; + this[LRU_LIST].forEach(function (hit) { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key); + this[LENGTH] += hit.length; + }, this); + } + + trim$2(this); + }, + get: function () { + return this[LENGTH_CALCULATOR]; + }, + enumerable: true +}); +Object.defineProperty(LRUCache.prototype, 'length', { + get: function () { + return this[LENGTH]; + }, + enumerable: true +}); +Object.defineProperty(LRUCache.prototype, 'itemCount', { + get: function () { + return this[LRU_LIST].length; + }, + enumerable: true +}); + +LRUCache.prototype.rforEach = function (fn, thisp) { + thisp = thisp || this; + + for (var walker = this[LRU_LIST].tail; walker !== null;) { + var prev = walker.prev; + forEachStep(this, fn, walker, thisp); + walker = prev; + } +}; + +function forEachStep(self, fn, node, thisp) { + var hit = node.value; + + if (isStale(self, hit)) { + del(self, node); + + if (!self[ALLOW_STALE]) { + hit = undefined; + } + } + + if (hit) { + fn.call(thisp, hit.value, hit.key, self); + } +} + +LRUCache.prototype.forEach = function (fn, thisp) { + thisp = thisp || this; + + for (var walker = this[LRU_LIST].head; walker !== null;) { + var next = walker.next; + forEachStep(this, fn, walker, thisp); + walker = next; + } +}; + +LRUCache.prototype.keys = function () { + return this[LRU_LIST].toArray().map(function (k) { + return k.key; + }, this); +}; + +LRUCache.prototype.values = function () { + return this[LRU_LIST].toArray().map(function (k) { + return k.value; + }, this); +}; + +LRUCache.prototype.reset = function () { + if (this[DISPOSE] && this[LRU_LIST] && this[LRU_LIST].length) { + this[LRU_LIST].forEach(function (hit) { + this[DISPOSE](hit.key, hit.value); + }, this); + } + + this[CACHE] = new map(); // hash of items by key + + this[LRU_LIST] = new yallist(); // list of items in order of use recency + + this[LENGTH] = 0; // length of items in the list +}; + +LRUCache.prototype.dump = function () { + return this[LRU_LIST].map(function (hit) { + if (!isStale(this, hit)) { + return { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }; + } + }, this).toArray().filter(function (h) { + return h; + }); +}; + +LRUCache.prototype.dumpLru = function () { + return this[LRU_LIST]; +}; +/* istanbul ignore next */ + + +LRUCache.prototype.inspect = function (n, opts) { + var str = 'LRUCache {'; + var extras = false; + var as = this[ALLOW_STALE]; + + if (as) { + str += '\n allowStale: true'; + extras = true; + } + + var max = this[MAX]; + + if (max && max !== Infinity) { + if (extras) { + str += ','; + } + + str += '\n max: ' + util__default['default'].inspect(max, opts); + extras = true; + } + + var maxAge = this[MAX_AGE]; + + if (maxAge) { + if (extras) { + str += ','; + } + + str += '\n maxAge: ' + util__default['default'].inspect(maxAge, opts); + extras = true; + } + + var lc = this[LENGTH_CALCULATOR]; + + if (lc && lc !== naiveLength) { + if (extras) { + str += ','; + } + + str += '\n length: ' + util__default['default'].inspect(this[LENGTH], opts); + extras = true; + } + + var didFirst = false; + this[LRU_LIST].forEach(function (item) { + if (didFirst) { + str += ',\n '; + } else { + if (extras) { + str += ',\n'; + } + + didFirst = true; + str += '\n '; + } + + var key = util__default['default'].inspect(item.key).split('\n').join('\n '); + var val = { + value: item.value + }; + + if (item.maxAge !== maxAge) { + val.maxAge = item.maxAge; + } + + if (lc !== naiveLength) { + val.length = item.length; + } + + if (isStale(this, item)) { + val.stale = true; + } + + val = util__default['default'].inspect(val, opts).split('\n').join('\n '); + str += key + ' => ' + val; + }); + + if (didFirst || extras) { + str += '\n'; + } + + str += '}'; + return str; +}; + +LRUCache.prototype.set = function (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE]; + var now = maxAge ? Date.now() : 0; + var len = this[LENGTH_CALCULATOR](value, key); + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)); + return false; + } + + var node = this[CACHE].get(key); + var item = node.value; // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) { + this[DISPOSE](key, item.value); + } + } + + item.now = now; + item.maxAge = maxAge; + item.value = value; + this[LENGTH] += len - item.length; + item.length = len; + this.get(key); + trim$2(this); + return true; + } + + var hit = new Entry$1(key, value, len, now, maxAge); // oversized objects fall out of cache automatically. + + if (hit.length > this[MAX]) { + if (this[DISPOSE]) { + this[DISPOSE](key, value); + } + + return false; + } + + this[LENGTH] += hit.length; + this[LRU_LIST].unshift(hit); + this[CACHE].set(key, this[LRU_LIST].head); + trim$2(this); + return true; +}; + +LRUCache.prototype.has = function (key) { + if (!this[CACHE].has(key)) return false; + var hit = this[CACHE].get(key).value; + + if (isStale(this, hit)) { + return false; + } + + return true; +}; + +LRUCache.prototype.get = function (key) { + return get(this, key, true); +}; + +LRUCache.prototype.peek = function (key) { + return get(this, key, false); +}; + +LRUCache.prototype.pop = function () { + var node = this[LRU_LIST].tail; + if (!node) return null; + del(this, node); + return node.value; +}; + +LRUCache.prototype.del = function (key) { + del(this, this[CACHE].get(key)); +}; + +LRUCache.prototype.load = function (arr) { + // reset the cache + this.reset(); + var now = Date.now(); // A previous serialized cache has the most recent items first + + for (var l = arr.length - 1; l >= 0; l--) { + var hit = arr[l]; + var expiresAt = hit.e || 0; + + if (expiresAt === 0) { + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v); + } else { + var maxAge = expiresAt - now; // dont add already expired items + + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge); + } + } + } +}; + +LRUCache.prototype.prune = function () { + var self = this; + this[CACHE].forEach(function (value, key) { + get(self, key, false); + }); +}; + +function get(self, key, doUse) { + var node = self[CACHE].get(key); + + if (node) { + var hit = node.value; + + if (isStale(self, hit)) { + del(self, node); + if (!self[ALLOW_STALE]) hit = undefined; + } else { + if (doUse) { + self[LRU_LIST].unshiftNode(node); + } + } + + if (hit) hit = hit.value; + } + + return hit; +} + +function isStale(self, hit) { + if (!hit || !hit.maxAge && !self[MAX_AGE]) { + return false; + } + + var stale = false; + var diff = Date.now() - hit.now; + + if (hit.maxAge) { + stale = diff > hit.maxAge; + } else { + stale = self[MAX_AGE] && diff > self[MAX_AGE]; + } + + return stale; +} + +function trim$2(self) { + if (self[LENGTH] > self[MAX]) { + for (var walker = self[LRU_LIST].tail; self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + var prev = walker.prev; + del(self, walker); + walker = prev; + } + } +} + +function del(self, node) { + if (node) { + var hit = node.value; + + if (self[DISPOSE]) { + self[DISPOSE](hit.key, hit.value); + } + + self[LENGTH] -= hit.length; + self[CACHE].delete(hit.key); + self[LRU_LIST].removeNode(node); + } +} // classy, since V8 prefers predictable objects. + + +function Entry$1(key, value, length, now, maxAge) { + this.key = key; + this.value = value; + this.length = length; + this.now = now; + this.maxAge = maxAge || 0; +} + +var sigmund_1 = sigmund; + +function sigmund(subject, maxSessions) { + maxSessions = maxSessions || 10; + var notes = []; + var analysis = ''; + var RE = RegExp; + + function psychoAnalyze(subject, session) { + if (session > maxSessions) return; + + if (typeof subject === 'function' || typeof subject === 'undefined') { + return; + } + + if (typeof subject !== 'object' || !subject || subject instanceof RE) { + analysis += subject; + return; + } + + if (notes.indexOf(subject) !== -1 || session === maxSessions) return; + notes.push(subject); + analysis += '{'; + Object.keys(subject).forEach(function (issue, _, __) { + // pseudo-private values. skip those. + if (issue.charAt(0) === '_') return; + var to = typeof subject[issue]; + if (to === 'function' || to === 'undefined') return; + analysis += issue; + psychoAnalyze(subject[issue], session + 1); + }); + } + + psychoAnalyze(subject, 0); + return analysis; +} // vim: set softtabstop=4 shiftwidth=4: + +var fnmatch = createCommonjsModule(function (module, exports) { + // Based on minimatch.js by isaacs + var platform = typeof process === "object" ? process.platform : "win32"; + if (module) module.exports = minimatch;else exports.minimatch = minimatch; + minimatch.Minimatch = Minimatch; + var cache = minimatch.cache = new lruCache({ + max: 100 + }), + GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {}; + var qmark = "[^/]" // * => any number of characters + , + star = qmark + "*?" // ** when dots are allowed. Anything goes, except .. and . + // not (^ or / followed by one or two dots followed by $ or /), + // followed by anything, any number of times. + , + twoStarDot = "(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?" // not a ^ or / followed by a dot, + // followed by anything, any number of times. + , + twoStarNoDot = "(?:(?!(?:\\\/|^)\\.).)*?" // characters that need to be escaped in RegExp. + , + reSpecials = charSet("().*{}+?[]^$\\!"); // "abc" -> { a:true, b:true, c:true } + + function charSet(s) { + return s.split("").reduce(function (set, c) { + set[c] = true; + return set; + }, {}); + } // normalizes slashes. + + + var slashSplit = /\/+/; + minimatch.monkeyPatch = monkeyPatch; + + function monkeyPatch() { + var desc = Object.getOwnPropertyDescriptor(String.prototype, "match"); + var orig = desc.value; + + desc.value = function (p) { + if (p instanceof Minimatch) return p.match(this); + return orig.call(this, p); + }; + + Object.defineProperty(String.prototype, desc); + } + + minimatch.filter = filter; + + function filter(pattern, options) { + options = options || {}; + return function (p, i, list) { + return minimatch(p, pattern, options); + }; + } + + function ext(a, b) { + a = a || {}; + b = b || {}; + var t = {}; + Object.keys(b).forEach(function (k) { + t[k] = b[k]; + }); + Object.keys(a).forEach(function (k) { + t[k] = a[k]; + }); + return t; + } + + minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return minimatch; + var orig = minimatch; + + var m = function minimatch(p, pattern, options) { + return orig.minimatch(p, pattern, ext(def, options)); + }; + + m.Minimatch = function Minimatch(pattern, options) { + return new orig.Minimatch(pattern, ext(def, options)); + }; + + return m; + }; + + Minimatch.defaults = function (def) { + if (!def || !Object.keys(def).length) return Minimatch; + return minimatch.defaults(def).Minimatch; + }; + + function minimatch(p, pattern, options) { + if (typeof pattern !== "string") { + throw new TypeError("glob pattern string required"); + } + + if (!options) options = {}; // shortcut: comments match nothing. + + if (!options.nocomment && pattern.charAt(0) === "#") { + return false; + } // "" only matches "" + + + if (pattern.trim() === "") return p === ""; + return new Minimatch(pattern, options).match(p); + } + + function Minimatch(pattern, options) { + if (!(this instanceof Minimatch)) { + return new Minimatch(pattern, options, cache); + } + + if (typeof pattern !== "string") { + throw new TypeError("glob pattern string required"); + } + + if (!options) options = {}; // windows: need to use /, not \ + // On other platforms, \ is a valid (albeit bad) filename char. + + if (platform === "win32") { + pattern = pattern.split("\\").join("/"); + } // lru storage. + // these things aren't particularly big, but walking down the string + // and turning it into a regexp can get pretty costly. + + + var cacheKey = pattern + "\n" + sigmund_1(options); + var cached = minimatch.cache.get(cacheKey); + if (cached) return cached; + minimatch.cache.set(cacheKey, this); + this.options = options; + this.set = []; + this.pattern = pattern; + this.regexp = null; + this.negate = false; + this.comment = false; + this.empty = false; // make the set of regexps etc. + + this.make(); + } + + Minimatch.prototype.make = make; + + function make() { + // don't do it more than once. + if (this._made) return; + var pattern = this.pattern; + var options = this.options; // empty patterns and comments match nothing. + + if (!options.nocomment && pattern.charAt(0) === "#") { + this.comment = true; + return; + } + + if (!pattern) { + this.empty = true; + return; + } // step 1: figure out negation, etc. + + + this.parseNegate(); // step 2: expand braces + + var set = this.globSet = this.braceExpand(); + if (options.debug) console.error(this.pattern, set); // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + + set = this.globParts = set.map(function (s) { + return s.split(slashSplit); + }); + if (options.debug) console.error(this.pattern, set); // glob --> regexps + + set = set.map(function (s, si, set) { + return s.map(this.parse, this); + }, this); + if (options.debug) console.error(this.pattern, set); // filter out everything that didn't compile properly. + + set = set.filter(function (s) { + return -1 === s.indexOf(false); + }); + if (options.debug) console.error(this.pattern, set); + this.set = set; + } + + Minimatch.prototype.parseNegate = parseNegate; + + function parseNegate() { + var pattern = this.pattern, + negate = false, + options = this.options, + negateOffset = 0; + if (options.nonegate) return; + + for (var i = 0, l = pattern.length; i < l && pattern.charAt(i) === "!"; i++) { + negate = !negate; + negateOffset++; + } + + if (negateOffset) this.pattern = pattern.substr(negateOffset); + this.negate = negate; + } // Brace expansion: + // a{b,c}d -> abd acd + // a{b,}c -> abc ac + // a{0..3}d -> a0d a1d a2d a3d + // a{b,c{d,e}f}g -> abg acdfg acefg + // a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg + // + // Invalid sets are not expanded. + // a{2..}b -> a{2..}b + // a{b}c -> a{b}c + + + minimatch.braceExpand = function (pattern, options) { + return new Minimatch(pattern, options).braceExpand(); + }; + + Minimatch.prototype.braceExpand = braceExpand; + + function braceExpand(pattern, options) { + options = options || this.options; + pattern = typeof pattern === "undefined" ? this.pattern : pattern; + + if (typeof pattern === "undefined") { + throw new Error("undefined pattern"); + } + + if (options.nobrace || !pattern.match(/\{.*\}/)) { + // shortcut. no need to expand. + return [pattern]; + } + + var escaping = false; // examples and comments refer to this crazy pattern: + // a{b,c{d,e},{f,g}h}x{y,z} + // expected: + // abxy + // abxz + // acdxy + // acdxz + // acexy + // acexz + // afhxy + // afhxz + // aghxy + // aghxz + // everything before the first \{ is just a prefix. + // So, we pluck that off, and work with the rest, + // and then prepend it to everything we find. + + if (pattern.charAt(0) !== "{") { + // console.error(pattern) + var prefix = null; + + for (var i = 0, l = pattern.length; i < l; i++) { + var c = pattern.charAt(i); // console.error(i, c) + + if (c === "\\") { + escaping = !escaping; + } else if (c === "{" && !escaping) { + prefix = pattern.substr(0, i); + break; + } + } // actually no sets, all { were escaped. + + + if (prefix === null) { + // console.error("no sets") + return [pattern]; + } + + var tail = braceExpand(pattern.substr(i), options); + return tail.map(function (t) { + return prefix + t; + }); + } // now we have something like: + // {b,c{d,e},{f,g}h}x{y,z} + // walk through the set, expanding each part, until + // the set ends. then, we'll expand the suffix. + // If the set only has a single member, then'll put the {} back + // first, handle numeric sets, since they're easier + + + var numset = pattern.match(/^\{(-?[0-9]+)\.\.(-?[0-9]+)\}/); + + if (numset) { + // console.error("numset", numset[1], numset[2]) + var suf = braceExpand(pattern.substr(numset[0].length), options), + start = +numset[1], + end = +numset[2], + inc = start > end ? -1 : 1, + set = []; + + for (var i = start; i != end + inc; i += inc) { + // append all the suffixes + for (var ii = 0, ll = suf.length; ii < ll; ii++) { + set.push(i + suf[ii]); + } + } + + return set; + } // ok, walk through the set + // We hope, somewhat optimistically, that there + // will be a } at the end. + // If the closing brace isn't found, then the pattern is + // interpreted as braceExpand("\\" + pattern) so that + // the leading \{ will be interpreted literally. + + + var i = 1 // skip the \{ + , + depth = 1, + set = [], + member = "", + escaping = false; + + function addMember() { + set.push(member); + member = ""; + } // console.error("Entering for") + + + FOR: for (i = 1, l = pattern.length; i < l; i++) { + var c = pattern.charAt(i); // console.error("", i, c) + + if (escaping) { + escaping = false; + member += "\\" + c; + } else { + switch (c) { + case "\\": + escaping = true; + continue; + + case "{": + depth++; + member += "{"; + continue; + + case "}": + depth--; // if this closes the actual set, then we're done + + if (depth === 0) { + addMember(); // pluck off the close-brace + + i++; + break FOR; + } else { + member += c; + continue; + } + + case ",": + if (depth === 1) { + addMember(); + } else { + member += c; + } + + continue; + + default: + member += c; + continue; + } // switch + + } // else + + } // for + // now we've either finished the set, and the suffix is + // pattern.substr(i), or we have *not* closed the set, + // and need to escape the leading brace + + + if (depth !== 0) { + // console.error("didn't close", pattern) + return braceExpand("\\" + pattern, options); + } // x{y,z} -> ["xy", "xz"] + // console.error("set", set) + // console.error("suffix", pattern.substr(i)) + + + var suf = braceExpand(pattern.substr(i), options); // ["b", "c{d,e}","{f,g}h"] -> + // [["b"], ["cd", "ce"], ["fh", "gh"]] + + var addBraces = set.length === 1; // console.error("set pre-expanded", set) + + set = set.map(function (p) { + return braceExpand(p, options); + }); // console.error("set expanded", set) + // [["b"], ["cd", "ce"], ["fh", "gh"]] -> + // ["b", "cd", "ce", "fh", "gh"] + + set = set.reduce(function (l, r) { + return l.concat(r); + }); + + if (addBraces) { + set = set.map(function (s) { + return "{" + s + "}"; + }); + } // now attach the suffixes. + + + var ret = []; + + for (var i = 0, l = set.length; i < l; i++) { + for (var ii = 0, ll = suf.length; ii < ll; ii++) { + ret.push(set[i] + suf[ii]); + } + } + + return ret; + } // parse a component of the expanded set. + // At this point, no pattern may contain "/" in it + // so we're going to return a 2d array, where each entry is the full + // pattern, split on '/', and then turned into a regular expression. + // A regexp is made at the end which joins each array with an + // escaped /, and another full one which joins each regexp with |. + // + // Following the lead of Bash 4.1, note that "**" only has special meaning + // when it is the *only* thing in a path portion. Otherwise, any series + // of * is equivalent to a single *. Globstar behavior is enabled by + // default, and can be disabled by setting options.noglobstar. + + + Minimatch.prototype.parse = parse; + var SUBPARSE = {}; + + function parse(pattern, isSub) { + var options = this.options; // shortcuts + + if (!options.noglobstar && pattern === "**") return GLOBSTAR; + if (pattern === "") return ""; + var re = "", + hasMagic = !!options.nocase, + escaping = false // ? => one single character + , + patternListStack = [], + plType, + stateChar, + inClass = false, + reClassStart = -1, + classStart = -1 // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + , + patternStart = pattern.charAt(0) === "." ? "" // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? "(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))" : "(?!\\.)"; + + function clearStateChar() { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case "*": + re += star; + hasMagic = true; + break; + + case "?": + re += qmark; + hasMagic = true; + break; + + default: + re += "\\" + stateChar; + break; + } + + stateChar = false; + } + } + + for (var i = 0, len = pattern.length, c; i < len && (c = pattern.charAt(i)); i++) { + if (options.debug) { + console.error("%s\t%s %s %j", pattern, i, re, c); + } // skip over any that are escaped. + + + if (escaping && reSpecials[c]) { + re += "\\" + c; + escaping = false; + continue; + } + + switch (c) { + case "/": + // completely not allowed, even escaped. + // Should already be path-split by now. + return false; + + case "\\": + clearStateChar(); + escaping = true; + continue; + // the various stateChar values + // for the "extglob" stuff. + + case "?": + case "*": + case "+": + case "@": + case "!": + if (options.debug) { + console.error("%s\t%s %s %j <-- stateChar", pattern, i, re, c); + } // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + + + if (inClass) { + if (c === "!" && i === classStart + 1) c = "^"; + re += c; + continue; + } // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + + + clearStateChar(); + stateChar = c; // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + + if (options.noext) clearStateChar(); + continue; + + case "(": + if (inClass) { + re += "("; + continue; + } + + if (!stateChar) { + re += "\\("; + continue; + } + + plType = stateChar; + patternListStack.push({ + type: plType, + start: i - 1, + reStart: re.length + }); // negation is (?:(?!js)[^/]*) + + re += stateChar === "!" ? "(?:(?!" : "(?:"; + stateChar = false; + continue; + + case ")": + if (inClass || !patternListStack.length) { + re += "\\)"; + continue; + } + + hasMagic = true; + re += ")"; + plType = patternListStack.pop().type; // negation is (?:(?!js)[^/]*) + // The others are (?:) + + switch (plType) { + case "!": + re += "[^/]*?)"; + break; + + case "?": + case "+": + case "*": + re += plType; + // the default anyway + } + + continue; + + case "|": + if (inClass || !patternListStack.length || escaping) { + re += "\\|"; + escaping = false; + continue; + } + + re += "|"; + continue; + // these are mostly the same in regexp and glob + + case "[": + // swallow any state-tracking char before the [ + clearStateChar(); + + if (inClass) { + re += "\\" + c; + continue; + } + + inClass = true; + classStart = i; + reClassStart = re.length; + re += c; + continue; + + case "]": + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += "\\" + c; + escaping = false; + continue; + } // finish up the class. + + + hasMagic = true; + inClass = false; + re += c; + continue; + + default: + // swallow any state char that wasn't consumed + clearStateChar(); + + if (escaping) { + // no need + escaping = false; + } else if (reSpecials[c] && !(c === "^" && inClass)) { + re += "\\"; + } + + re += c; + } // switch + + } // for + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + + + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + var cs = pattern.substr(classStart + 1), + sp = this.parse(cs, SUBPARSE); + re = re.substr(0, reClassStart) + "\\[" + sp[0]; + hasMagic = hasMagic || sp[1]; + } // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + + + var pl; + + while (pl = patternListStack.pop()) { + var tail = re.slice(pl.reStart + 3); // maybe some even number of \, then maybe 1 \, followed by a | + + tail = tail.replace(/((?:\\{2})*)(\\?)\|/g, function (_, $1, $2) { + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = "\\"; + } // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + + + return $1 + $1 + $2 + "|"; + }); // console.error("tail=%j\n %s", tail, tail) + + var t = pl.type === "*" ? star : pl.type === "?" ? qmark : "\\" + pl.type; + hasMagic = true; + re = re.slice(0, pl.reStart) + t + "\\(" + tail; + } // handle trailing things that only matter at the very end. + + + clearStateChar(); + + if (escaping) { + // trailing \\ + re += "\\\\"; + } // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + + + var addPatternStart = false; + + switch (re.charAt(0)) { + case ".": + case "[": + case "(": + addPatternStart = true; + } // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + + + if (re !== "" && hasMagic) re = "(?=.)" + re; + if (addPatternStart) re = patternStart + re; // parsing just a piece of a larger pattern. + + if (isSub === SUBPARSE) { + return [re, hasMagic]; + } // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + + + if (!hasMagic) { + return globUnescape(pattern); + } + + var flags = options.nocase ? "i" : "", + regExp = new RegExp("^" + re + "$", flags); + regExp._glob = pattern; + regExp._src = re; + return regExp; + } + + minimatch.makeRe = function (pattern, options) { + return new Minimatch(pattern, options || {}).makeRe(); + }; + + Minimatch.prototype.makeRe = makeRe; + + function makeRe() { + if (this.regexp || this.regexp === false) return this.regexp; // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + + var set = this.set; + if (!set.length) return this.regexp = false; + var options = this.options; + var twoStar = options.noglobstar ? star : options.dot ? twoStarDot : twoStarNoDot, + flags = options.nocase ? "i" : ""; + var re = set.map(function (pattern) { + return pattern.map(function (p) { + return p === GLOBSTAR ? twoStar : typeof p === "string" ? regExpEscape(p) : p._src; + }).join("\\\/"); + }).join("|"); // must match entire pattern + // ending in a * or ** will make it less strict. + + re = "^(?:" + re + ")$"; // can match anything, as long as it's not this. + + if (this.negate) re = "^(?!" + re + ").*$"; + + try { + return this.regexp = new RegExp(re, flags); + } catch (ex) { + return this.regexp = false; + } + } + + minimatch.match = function (list, pattern, options) { + var mm = new Minimatch(pattern, options); + list = list.filter(function (f) { + return mm.match(f); + }); + + if (options.nonull && !list.length) { + list.push(pattern); + } + + return list; + }; + + Minimatch.prototype.match = match; + + function match(f, partial) { + // console.error("match", f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false; + if (this.empty) return f === ""; + if (f === "/" && partial) return true; + var options = this.options; // windows: need to use /, not \ + // On other platforms, \ is a valid (albeit bad) filename char. + + if (platform === "win32") { + f = f.split("\\").join("/"); + } // treat the test path as a set of pathparts. + + + f = f.split(slashSplit); + + if (options.debug) { + console.error(this.pattern, "split", f); + } // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + + var set = this.set; // console.error(this.pattern, "set", set) + + for (var i = 0, l = set.length; i < l; i++) { + var pattern = set[i]; + var hit = this.matchOne(f, pattern, partial); + + if (hit) { + if (options.flipNegate) return true; + return !this.negate; + } + } // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + + + if (options.flipNegate) return false; + return this.negate; + } // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + + + Minimatch.prototype.matchOne = function (file, pattern, partial) { + var options = this.options; + + if (options.debug) { + console.error("matchOne", { + "this": this, + file: file, + pattern: pattern + }); + } + + if (options.matchBase && pattern.length === 1) { + file = path__default['default'].basename(file.join("/")).split("/"); + } + + if (options.debug) { + console.error("matchOne", file.length, pattern.length); + } + + for (var fi = 0, pi = 0, fl = file.length, pl = pattern.length; fi < fl && pi < pl; fi++, pi++) { + if (options.debug) { + console.error("matchOne loop"); + } + + var p = pattern[pi], + f = file[fi]; + + if (options.debug) { + console.error(pattern, p, f); + } // should be impossible. + // some invalid regexp stuff in the set. + + + if (p === false) return false; + + if (p === GLOBSTAR) { + if (options.debug) console.error('GLOBSTAR', [pattern, p, f]); // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + + var fr = fi, + pr = pi + 1; + + if (pr === pl) { + if (options.debug) console.error('** at the end'); // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + + for (; fi < fl; fi++) { + if (file[fi] === "." || file[fi] === ".." || !options.dot && file[fi].charAt(0) === ".") return false; + } + + return true; + } // ok, let's see if we can swallow whatever we can. + + + WHILE: while (fr < fl) { + var swallowee = file[fr]; + + if (options.debug) { + console.error('\nglobstar while', file, fr, pattern, pr, swallowee); + } // XXX remove this slice. Just pass the start index. + + + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + if (options.debug) console.error('globstar found match!', fr, fl, swallowee); // found a match. + + return true; + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === "." || swallowee === ".." || !options.dot && swallowee.charAt(0) === ".") { + if (options.debug) console.error("dot detected!", file, fr, pattern, pr); + break WHILE; + } // ** swallows a segment, and continue. + + + if (options.debug) console.error('globstar swallow a segment, and continue'); + fr++; + } + } // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + + + if (partial) { + // ran out of file + // console.error("\n>>> no match, partial?", file, fr, pattern, pr) + if (fr === fl) return true; + } + + return false; + } // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + + + var hit; + + if (typeof p === "string") { + if (options.nocase) { + hit = f.toLowerCase() === p.toLowerCase(); + } else { + hit = f === p; + } + + if (options.debug) { + console.error("string match", p, f, hit); + } + } else { + hit = f.match(p); + + if (options.debug) { + console.error("pattern match", p, f, hit); + } + } + + if (!hit) return false; + } // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + // now either we fell off the end of the pattern, or we're done. + + + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true; + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial; + } else if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + var emptyFileEnd = fi === fl - 1 && file[fi] === ""; + return emptyFileEnd; + } // should be unreachable. + + + throw new Error("wtf?"); + }; // replace stuff like \* with * + + + function globUnescape(s) { + return s.replace(/\\(.)/g, "$1"); + } + + function regExpEscape(s) { + return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); + } +}); + +var ini = createCommonjsModule(function (module, exports) { + + var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) { + 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) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + var __generator = this && this.__generator || function (thisArg, body) { + var _ = { + label: 0, + sent: function () { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, + f, + y, + t, + g; + return g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + + switch (op[0]) { + case 0: + case 1: + t = op; + break; + + case 4: + _.label++; + return { + value: op[1], + done: false + }; + + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + + case 7: + op = _.ops.pop(); + + _.trys.pop(); + + continue; + + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + + if (t && _.label < t[2]) { + _.label = t[2]; + + _.ops.push(op); + + break; + } + + if (t[2]) _.ops.pop(); + + _.trys.pop(); + + continue; + } + + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } + }; + + var __importStar = this && this.__importStar || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var fs = __importStar(fs__default['default']); + /** + * define the possible values: + * section: [section] + * param: key=value + * comment: ;this is a comment + */ + + + var regex = { + section: /^\s*\[(([^#;]|\\#|\\;)+)\]\s*([#;].*)?$/, + param: /^\s*([\w\.\-\_]+)\s*[=:]\s*(.*?)\s*([#;].*)?$/, + comment: /^\s*[#;].*$/ + }; + /** + * Parses an .ini file + * @param file The location of the .ini file + */ + + function parse(file) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 + /*return*/ + , new Promise(function (resolve, reject) { + fs.readFile(file, 'utf8', function (err, data) { + if (err) { + reject(err); + return; + } + + resolve(parseString(data)); + }); + })]; + }); + }); + } + + exports.parse = parse; + + function parseSync(file) { + return parseString(fs.readFileSync(file, 'utf8')); + } + + exports.parseSync = parseSync; + + function parseString(data) { + var sectionBody = {}; + var sectionName = null; + var value = [[sectionName, sectionBody]]; + var lines = data.split(/\r\n|\r|\n/); + lines.forEach(function (line) { + var match; + + if (regex.comment.test(line)) { + return; + } + + if (regex.param.test(line)) { + match = line.match(regex.param); + sectionBody[match[1]] = match[2]; + } else if (regex.section.test(line)) { + match = line.match(regex.section); + sectionName = match[1]; + sectionBody = {}; + value.push([sectionName, sectionBody]); + } + }); + return value; + } + + exports.parseString = parseString; +}); + +var name$1 = "editorconfig"; +var version$1 = "0.15.3"; +var description$1 = "EditorConfig File Locator and Interpreter for Node.js"; +var keywords = [ + "editorconfig", + "core" +]; +var main$1 = "src/index.js"; +var contributors = [ + "Hong Xu (topbug.net)", + "Jed Mao (https://github.com/jedmao/)", + "Trey Hunner (http://treyhunner.com)" +]; +var directories = { + bin: "./bin", + lib: "./lib" +}; +var scripts$1 = { + clean: "rimraf dist", + prebuild: "npm run clean", + build: "tsc", + pretest: "npm run lint && npm run build && npm run copy && cmake .", + test: "ctest .", + "pretest:ci": "npm run pretest", + "test:ci": "ctest -VV --output-on-failure .", + lint: "npm run eclint && npm run tslint", + eclint: "eclint check --indent_size ignore \"src/**\"", + tslint: "tslint --project tsconfig.json --exclude package.json", + copy: "cpy .npmignore LICENSE README.md CHANGELOG.md dist && cpy bin/* dist/bin && cpy src/lib/fnmatch*.* dist/src/lib", + prepub: "npm run lint && npm run build && npm run copy", + pub: "npm publish ./dist" +}; +var repository$1 = { + type: "git", + url: "git://github.com/editorconfig/editorconfig-core-js.git" +}; +var bugs = "https://github.com/editorconfig/editorconfig-core-js/issues"; +var author$1 = "EditorConfig Team"; +var license$1 = "MIT"; +var dependencies$1 = { + commander: "^2.19.0", + "lru-cache": "^4.1.5", + semver: "^5.6.0", + sigmund: "^1.0.1" +}; +var devDependencies$1 = { + "@types/mocha": "^5.2.6", + "@types/node": "^10.12.29", + "@types/semver": "^5.5.0", + "cpy-cli": "^2.0.0", + eclint: "^2.8.1", + mocha: "^5.2.0", + rimraf: "^2.6.3", + should: "^13.2.3", + tslint: "^5.13.1", + typescript: "^3.3.3333" +}; +var _package$2 = { + name: name$1, + version: version$1, + description: description$1, + keywords: keywords, + main: main$1, + contributors: contributors, + directories: directories, + scripts: scripts$1, + repository: repository$1, + bugs: bugs, + author: author$1, + license: license$1, + dependencies: dependencies$1, + devDependencies: devDependencies$1 +}; + +var _package$3 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$1, + version: version$1, + description: description$1, + keywords: keywords, + main: main$1, + contributors: contributors, + directories: directories, + scripts: scripts$1, + repository: repository$1, + bugs: bugs, + author: author$1, + license: license$1, + dependencies: dependencies$1, + devDependencies: devDependencies$1, + 'default': _package$2 +}); + +var require$$4 = getCjsExportFromNamespace(_package$3); + +var src = createCommonjsModule(function (module, exports) { + + var __awaiter = this && this.__awaiter || function (thisArg, _arguments, P, generator) { + 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) : new P(function (resolve) { + resolve(result.value); + }).then(fulfilled, rejected); + } + + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + var __generator = this && this.__generator || function (thisArg, body) { + var _ = { + label: 0, + sent: function () { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, + f, + y, + t, + g; + return g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g; + + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + + switch (op[0]) { + case 0: + case 1: + t = op; + break; + + case 4: + _.label++; + return { + value: op[1], + done: false + }; + + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + + case 7: + op = _.ops.pop(); + + _.trys.pop(); + + continue; + + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + + if (t && _.label < t[2]) { + _.label = t[2]; + + _.ops.push(op); + + break; + } + + if (t[2]) _.ops.pop(); + + _.trys.pop(); + + continue; + } + + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } + }; + + var __importStar = this && this.__importStar || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; + }; + + var __importDefault = this && this.__importDefault || function (mod) { + return mod && mod.__esModule ? mod : { + "default": mod + }; + }; + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + var fs = __importStar(fs__default['default']); + + var path = __importStar(path__default['default']); + + var semver = __importStar(semver$2); + + var fnmatch_1 = __importDefault(fnmatch); + + exports.parseString = ini.parseString; + + var package_json_1 = __importDefault(require$$4); + + var knownProps = { + end_of_line: true, + indent_style: true, + indent_size: true, + insert_final_newline: true, + trim_trailing_whitespace: true, + charset: true + }; + + function fnmatch$1(filepath, glob) { + var matchOptions = { + matchBase: true, + dot: true, + noext: true + }; + glob = glob.replace(/\*\*/g, '{*,**/**/**}'); + return fnmatch_1.default(filepath, glob, matchOptions); + } + + function getConfigFileNames(filepath, options) { + var paths = []; + + do { + filepath = path.dirname(filepath); + paths.push(path.join(filepath, options.config)); + } while (filepath !== options.root); + + return paths; + } + + function processMatches(matches, version) { + // Set indent_size to 'tab' if indent_size is unspecified and + // indent_style is set to 'tab'. + if ('indent_style' in matches && matches.indent_style === 'tab' && !('indent_size' in matches) && semver.gte(version, '0.10.0')) { + matches.indent_size = 'tab'; + } // Set tab_width to indent_size if indent_size is specified and + // tab_width is unspecified + + + if ('indent_size' in matches && !('tab_width' in matches) && matches.indent_size !== 'tab') { + matches.tab_width = matches.indent_size; + } // Set indent_size to tab_width if indent_size is 'tab' + + + if ('indent_size' in matches && 'tab_width' in matches && matches.indent_size === 'tab') { + matches.indent_size = matches.tab_width; + } + + return matches; + } + + function processOptions(options, filepath) { + if (options === void 0) { + options = {}; + } + + return { + config: options.config || '.editorconfig', + version: options.version || package_json_1.default.version, + root: path.resolve(options.root || path.parse(filepath).root) + }; + } + + function buildFullGlob(pathPrefix, glob) { + switch (glob.indexOf('/')) { + case -1: + glob = '**/' + glob; + break; + + case 0: + glob = glob.substring(1); + break; + } + + return path.join(pathPrefix, glob); + } + + function extendProps(props, options) { + if (props === void 0) { + props = {}; + } + + if (options === void 0) { + options = {}; + } + + for (var key in options) { + if (options.hasOwnProperty(key)) { + var value = options[key]; + var key2 = key.toLowerCase(); + var value2 = value; + + if (knownProps[key2]) { + value2 = value.toLowerCase(); + } + + try { + value2 = JSON.parse(value); + } catch (e) {} + + if (typeof value === 'undefined' || value === null) { + // null and undefined are values specific to JSON (no special meaning + // in editorconfig) & should just be returned as regular strings. + value2 = String(value); + } + + props[key2] = value2; + } + } + + return props; + } + + function parseFromConfigs(configs, filepath, options) { + return processMatches(configs.reverse().reduce(function (matches, file) { + var pathPrefix = path.dirname(file.name); + file.contents.forEach(function (section) { + var glob = section[0]; + var options2 = section[1]; + + if (!glob) { + return; + } + + var fullGlob = buildFullGlob(pathPrefix, glob); + + if (!fnmatch$1(filepath, fullGlob)) { + return; + } + + matches = extendProps(matches, options2); + }); + return matches; + }, {}), options.version); + } + + function getConfigsForFiles(files) { + var configs = []; + + for (var i in files) { + if (files.hasOwnProperty(i)) { + var file = files[i]; + var contents = ini.parseString(file.contents); + configs.push({ + name: file.name, + contents: contents + }); + + if ((contents[0][1].root || '').toLowerCase() === 'true') { + break; + } + } + } + + return configs; + } + + function readConfigFiles(filepaths) { + return __awaiter(this, void 0, void 0, function () { + return __generator(this, function (_a) { + return [2 + /*return*/ + , Promise.all(filepaths.map(function (name) { + return new Promise(function (resolve) { + fs.readFile(name, 'utf8', function (err, data) { + resolve({ + name: name, + contents: err ? '' : data + }); + }); + }); + }))]; + }); + }); + } + + function readConfigFilesSync(filepaths) { + var files = []; + var file; + filepaths.forEach(function (filepath) { + try { + file = fs.readFileSync(filepath, 'utf8'); + } catch (e) { + file = ''; + } + + files.push({ + name: filepath, + contents: file + }); + }); + return files; + } + + function opts(filepath, options) { + if (options === void 0) { + options = {}; + } + + var resolvedFilePath = path.resolve(filepath); + return [resolvedFilePath, processOptions(options, resolvedFilePath)]; + } + + function parseFromFiles(filepath, files, options) { + if (options === void 0) { + options = {}; + } + + return __awaiter(this, void 0, void 0, function () { + var _a, resolvedFilePath, processedOptions; + + return __generator(this, function (_b) { + _a = opts(filepath, options), resolvedFilePath = _a[0], processedOptions = _a[1]; + return [2 + /*return*/ + , files.then(getConfigsForFiles).then(function (configs) { + return parseFromConfigs(configs, resolvedFilePath, processedOptions); + })]; + }); + }); + } + + exports.parseFromFiles = parseFromFiles; + + function parseFromFilesSync(filepath, files, options) { + if (options === void 0) { + options = {}; + } + + var _a = opts(filepath, options), + resolvedFilePath = _a[0], + processedOptions = _a[1]; + + return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions); + } + + exports.parseFromFilesSync = parseFromFilesSync; + + function parse(_filepath, _options) { + if (_options === void 0) { + _options = {}; + } + + return __awaiter(this, void 0, void 0, function () { + var _a, resolvedFilePath, processedOptions, filepaths; + + return __generator(this, function (_b) { + _a = opts(_filepath, _options), resolvedFilePath = _a[0], processedOptions = _a[1]; + filepaths = getConfigFileNames(resolvedFilePath, processedOptions); + return [2 + /*return*/ + , readConfigFiles(filepaths).then(getConfigsForFiles).then(function (configs) { + return parseFromConfigs(configs, resolvedFilePath, processedOptions); + })]; + }); + }); + } + + exports.parse = parse; + + function parseSync(_filepath, _options) { + if (_options === void 0) { + _options = {}; + } + + var _a = opts(_filepath, _options), + resolvedFilePath = _a[0], + processedOptions = _a[1]; + + var filepaths = getConfigFileNames(resolvedFilePath, processedOptions); + var files = readConfigFilesSync(filepaths); + return parseFromConfigs(getConfigsForFiles(files), resolvedFilePath, processedOptions); + } + + exports.parseSync = parseSync; +}); + +var editorconfigToPrettier = editorConfigToPrettier; + +function removeUnset(editorConfig) { + const result = {}; + const keys = Object.keys(editorConfig); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + + if (editorConfig[key] === "unset") { + continue; + } + + result[key] = editorConfig[key]; + } + + return result; +} + +function editorConfigToPrettier(editorConfig) { + if (!editorConfig) { + return null; + } + + editorConfig = removeUnset(editorConfig); + + if (Object.keys(editorConfig).length === 0) { + return null; + } + + const result = {}; + + if (editorConfig.indent_style) { + result.useTabs = editorConfig.indent_style === "tab"; + } + + if (editorConfig.indent_size === "tab") { + result.useTabs = true; + } + + if (result.useTabs && editorConfig.tab_width) { + result.tabWidth = editorConfig.tab_width; + } else if (editorConfig.indent_style === "space" && editorConfig.indent_size && editorConfig.indent_size !== "tab") { + result.tabWidth = editorConfig.indent_size; + } else if (editorConfig.tab_width !== undefined) { + result.tabWidth = editorConfig.tab_width; + } + + if (editorConfig.max_line_length && editorConfig.max_line_length !== "off") { + result.printWidth = editorConfig.max_line_length; + } + + if (editorConfig.quote_type === "single") { + result.singleQuote = true; + } else if (editorConfig.quote_type === "double") { + result.singleQuote = false; + } + + if (["cr", "crlf", "lf"].indexOf(editorConfig.end_of_line) !== -1) { + result.endOfLine = editorConfig.end_of_line; + } + + return result; +} + +// https://github.com/kirstein/find-project-root/blob/master/index.js + + +const MARKERS = [".git", ".hg"]; + +const markerExists = directory => MARKERS.some(mark => fs__default['default'].existsSync(path__default['default'].join(directory, mark))); + +function findProjectRoot(directory) { + while (!markerExists(directory)) { + const parentDirectory = path__default['default'].resolve(directory, ".."); + + if (parentDirectory === directory) { + break; + } + + directory = parentDirectory; + } + + return directory; +} + +var findProjectRoot_1 = findProjectRoot; + +const jsonStringifyMem = fn => mem_1(fn, { + cacheKey: JSON.stringify +}); + +const maybeParse = (filePath, parse) => filePath && parse(filePath, { + root: findProjectRoot_1(path__default['default'].dirname(path__default['default'].resolve(filePath))) +}); + +const editorconfigAsyncNoCache = async (filePath) => editorconfigToPrettier(await maybeParse(filePath, src.parse)); + +const editorconfigAsyncWithCache = jsonStringifyMem(editorconfigAsyncNoCache); + +const editorconfigSyncNoCache = filePath => editorconfigToPrettier(maybeParse(filePath, src.parseSync)); + +const editorconfigSyncWithCache = jsonStringifyMem(editorconfigSyncNoCache); + +function getLoadFunction(opts) { + if (!opts.editorconfig) { + return () => null; + } + + if (opts.sync) { + return opts.cache ? editorconfigSyncWithCache : editorconfigSyncNoCache; + } + + return opts.cache ? editorconfigAsyncWithCache : editorconfigAsyncNoCache; +} + +function clearCache() { + mem_1.clear(editorconfigSyncWithCache); + mem_1.clear(editorconfigAsyncWithCache); +} + +var resolveConfigEditorconfig = { + getLoadFunction, + clearCache +}; + +const getExplorerMemoized = mem_1(opts => { + const cosmiconfig = thirdParty["cosmiconfig" + (opts.sync ? "Sync" : "")]; + const explorer = cosmiconfig("prettier", { + cache: opts.cache, + transform: result => { + if (result && result.config) { + if (typeof result.config === "string") { + const dir = path__default['default'].dirname(result.filepath); + const modulePath = resolve_1(result.config, { + paths: [dir] + }); + result.config = require(modulePath); + } + + if (typeof result.config !== "object") { + throw new Error("Config is only allowed to be an object, " + `but received ${typeof result.config} in "${result.filepath}"`); + } + + delete result.config.$schema; + } + + return result; + }, + searchPlaces: ["package.json", ".prettierrc", ".prettierrc.json", ".prettierrc.yaml", ".prettierrc.yml", ".prettierrc.json5", ".prettierrc.js", ".prettierrc.cjs", "prettier.config.js", "prettier.config.cjs", ".prettierrc.toml"], + loaders: { + ".toml": loadToml, + ".json5": loadJson5 + } + }); + return explorer; +}, { + cacheKey: JSON.stringify +}); +/** @param {{ cache: boolean, sync: boolean }} opts */ + +function getExplorer(opts) { + // Normalize opts before passing to a memoized function + opts = Object.assign({ + sync: false, + cache: false + }, opts); + return getExplorerMemoized(opts); +} + +function _resolveConfig(filePath, opts, sync) { + opts = Object.assign({ + useCache: true + }, opts); + const loadOpts = { + cache: !!opts.useCache, + sync: !!sync, + editorconfig: !!opts.editorconfig + }; + const { + load, + search + } = getExplorer(loadOpts); + const loadEditorConfig = resolveConfigEditorconfig.getLoadFunction(loadOpts); + const arr = [opts.config ? load(opts.config) : search(filePath), loadEditorConfig(filePath)]; + + const unwrapAndMerge = ([result, editorConfigured]) => { + const merged = Object.assign({}, editorConfigured, mergeOverrides(result, filePath)); + ["plugins", "pluginSearchDirs"].forEach(optionName => { + if (Array.isArray(merged[optionName])) { + merged[optionName] = merged[optionName].map(value => typeof value === "string" && value.startsWith(".") // relative path + ? path__default['default'].resolve(path__default['default'].dirname(result.filepath), value) : value); + } + }); + + if (!result && !editorConfigured) { + return null; + } + + return merged; + }; + + if (loadOpts.sync) { + return unwrapAndMerge(arr); + } + + return Promise.all(arr).then(unwrapAndMerge); +} + +const resolveConfig = (filePath, opts) => _resolveConfig(filePath, opts, false); + +resolveConfig.sync = (filePath, opts) => _resolveConfig(filePath, opts, true); + +function clearCache$1() { + mem_1.clear(getExplorerMemoized); + resolveConfigEditorconfig.clearCache(); +} + +async function resolveConfigFile(filePath) { + const { + search + } = getExplorer({ + sync: false + }); + const result = await search(filePath); + return result ? result.filepath : null; +} + +resolveConfigFile.sync = filePath => { + const { + search + } = getExplorer({ + sync: true + }); + const result = search(filePath); + return result ? result.filepath : null; +}; + +function mergeOverrides(configResult, filePath) { + const { + config, + filepath: configPath + } = configResult || {}; + + const _ref = config || {}, + { + overrides + } = _ref, + options = _objectWithoutPropertiesLoose(_ref, ["overrides"]); + + if (filePath && overrides) { + const relativeFilePath = path__default['default'].relative(path__default['default'].dirname(configPath), filePath); + + for (const override of overrides) { + if (pathMatchesGlobs(relativeFilePath, override.files, override.excludeFiles)) { + Object.assign(options, override.options); + } + } + } + + return options; +} // Based on eslint: https://github.com/eslint/eslint/blob/master/lib/config/config-ops.js + + +function pathMatchesGlobs(filePath, patterns, excludedPatterns) { + const patternList = [].concat(patterns); + const excludedPatternList = [].concat(excludedPatterns || []); + const opts = { + matchBase: true, + dot: true + }; + return patternList.some(pattern => minimatch_1(filePath, pattern, opts)) && !excludedPatternList.some(excludedPattern => minimatch_1(filePath, excludedPattern, opts)); +} + +var resolveConfig_1 = { + resolveConfig, + resolveConfigFile, + clearCache: clearCache$1 +}; + +// A simple implementation of make-array +function make_array(subject) { + return Array.isArray(subject) ? subject : [subject]; +} + +const REGEX_BLANK_LINE = /^\s+$/; +const REGEX_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +const REGEX_LEADING_EXCAPED_HASH = /^\\#/; +const SLASH = '/'; +const KEY_IGNORE = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore') +/* istanbul ignore next */ +: 'node-ignore'; + +const define = (object, key, value) => Object.defineProperty(object, key, { + value +}); + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression +// The cases are complicated, see test cases for details + +const sanitizeRange = range => range.replace(REGEX_REGEXP_RANGE, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but +// fatal for JavaScript regular expression, so eliminate it. +: ''); // > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` +// '`foo/`' should not continue with the '`..`' + + +const DEFAULT_REPLACER_PREFIX = [// > Trailing spaces are ignored unless they are quoted with backslash ("\") +[// (a\ ) -> (a ) +// (a ) -> (a) +// (a \ ) -> (a ) +/\\?\s+$/, match => match.indexOf('\\') === 0 ? ' ' : ''], // replace (\ ) with ' ' +[/\\\s/g, () => ' '], // Escape metacharacters +// which is written down by users but means special for regular expressions. +// > There are 12 characters with special meanings: +// > - the backslash \, +// > - the caret ^, +// > - the dollar sign $, +// > - the period or dot ., +// > - the vertical bar or pipe symbol |, +// > - the question mark ?, +// > - the asterisk or star *, +// > - the plus sign +, +// > - the opening parenthesis (, +// > - the closing parenthesis ), +// > - and the opening square bracket [, +// > - the opening curly brace {, +// > These special characters are often called "metacharacters". +[/[\\^$.|*+(){]/g, match => `\\${match}`], [// > [abc] matches any character inside the brackets +// > (in this case a, b, or c); +/\[([^\]/]*)($|\])/g, (match, p1, p2) => p2 === ']' ? `[${sanitizeRange(p1)}]` : `\\${match}`], [// > a question mark (?) matches a single character +/(?!\\)\?/g, () => '[^/]'], // leading slash +[// > A leading slash matches the beginning of the pathname. +// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". +// A leading slash matches the beginning of the pathname +/^\//, () => '^'], // replace special metacharacter slash after the leading slash +[/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories. +// > For example, "**/foo" matches file or directory "foo" anywhere, +// > the same as pattern "foo". +// > "**/foo/bar" matches file or directory "bar" anywhere that is directly +// > under directory "foo". +// Notice that the '*'s have been replaced as '\\*' +/^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo' +() => '^(?:.*\\/)?']]; +const DEFAULT_REPLACER_SUFFIX = [// starting +[// there will be no leading '/' +// (which has been replaced by section "leading slash") +// If starts with '**', adding a '^' to the regular expression also works +/^(?=[^^])/, function startingReplacer() { + return !/\/(?!$)/.test(this) // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^'; +}], // two globstars +[// Use lookahead assertions so that we could match more than one `'/**'` +/\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories +// should not use '*', or it will be replaced by the next replacer +// Check if it is not the last `'/**'` +(match, index, str) => index + 6 < str.length // case: /**/ +// > A slash followed by two consecutive asterisks then a slash matches +// > zero or more directories. +// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. +// '/**/' +? '(?:\\/[^\\/]+)*' // case: /** +// > A trailing `"/**"` matches everything inside. +// #21: everything inside but it should not include the current folder +: '\\/.+'], // intermediate wildcards +[// Never replace escaped '*' +// ignore rule '\*' will match the path '*' +// 'abc.*/' -> go +// 'abc.*' -> skip this rule +/(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js' +// '*.js' doesn't match 'abc' +(match, p1) => `${p1}[^\\/]*`], // trailing wildcard +[/(\^|\\\/)?\\\*$/, (match, p1) => { + const prefix = p1 // '\^': + // '/*' does not match '' + // '/*' does not match everything + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + return `${prefix}(?=$|\\/$)`; +}], [// unescape +/\\\\\\/g, () => '\\']]; +const POSITIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // 'f' +// matches +// - /f(end) +// - /f/ +// - (start)f(end) +// - (start)f/ +// doesn't match +// - oof +// - foo +// pseudo: +// -> (^|/)f(/|$) +// ending +[// 'js' will not match 'js.' +// 'ab' will not match 'abc' +/(?:[^*/])$/, // 'js*' will not match 'a.js' +// 'js/' will not match 'a.js' +// 'js' will match 'a.js' and 'a.js/' +match => `${match}(?=$|\\/)`], ...DEFAULT_REPLACER_SUFFIX]; +const NEGATIVE_REPLACERS = [...DEFAULT_REPLACER_PREFIX, // #24, #38 +// The MISSING rule of [gitignore docs](https://git-scm.com/docs/gitignore) +// A negative pattern without a trailing wildcard should not +// re-include the things inside that directory. +// eg: +// ['node_modules/*', '!node_modules'] +// should ignore `node_modules/a.js` +[/(?:[^*])$/, match => `${match}(?=$|\\/$)`], ...DEFAULT_REPLACER_SUFFIX]; // A simple cache, because an ignore rule only has only one certain meaning + +const cache = Object.create(null); // @param {pattern} + +const make_regex = (pattern, negative, ignorecase) => { + const r = cache[pattern]; + + if (r) { + return r; + } + + const replacers = negative ? NEGATIVE_REPLACERS : POSITIVE_REPLACERS; + const source = replacers.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern); + return cache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source); +}; // > A blank line matches no files, so it can serve as a separator for readability. + + +const checkPattern = pattern => pattern && typeof pattern === 'string' && !REGEX_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment. +&& pattern.indexOf('#') !== 0; + +const createRule = (pattern, ignorecase) => { + const origin = pattern; + let negative = false; // > An optional prefix "!" which negates the pattern; + + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + + pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_LEADING_EXCAPED_HASH, '#'); + const regex = make_regex(pattern, negative, ignorecase); + return { + origin, + pattern, + negative, + regex + }; +}; + +class IgnoreBase { + constructor({ + ignorecase = true + } = {}) { + this._rules = []; + this._ignorecase = ignorecase; + define(this, KEY_IGNORE, true); + + this._initCache(); + } + + _initCache() { + this._cache = Object.create(null); + } // @param {Array.|string|Ignore} pattern + + + add(pattern) { + this._added = false; + + if (typeof pattern === 'string') { + pattern = pattern.split(/\r?\n/g); + } + + make_array(pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore, + // making the behavior changed. + + if (this._added) { + this._initCache(); + } + + return this; + } // legacy + + + addPattern(pattern) { + return this.add(pattern); + } + + _addPattern(pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignorecase); + this._added = true; + + this._rules.push(rule); + } + } + + filter(paths) { + return make_array(paths).filter(path => this._filter(path)); + } + + createFilter() { + return path => this._filter(path); + } + + ignores(path) { + return !this._filter(path); + } // @returns `Boolean` true if the `path` is NOT ignored + + + _filter(path, slices) { + if (!path) { + return false; + } + + if (path in this._cache) { + return this._cache[path]; + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH); + } + + slices.pop(); + return this._cache[path] = slices.length // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + // If the path contains a parent directory, check the parent first + ? this._filter(slices.join(SLASH) + SLASH, slices) && this._test(path) // Or only test the path + : this._test(path); + } // @returns {Boolean} true if a file is NOT ignored + + + _test(path) { + // Explicitly define variable type by setting matched to `0` + let matched = 0; + + this._rules.forEach(rule => { + // if matched = true, then we only test negative rules + // if matched = false, then we test non-negative rules + if (!(matched ^ rule.negative)) { + matched = rule.negative ^ rule.regex.test(path); + } + }); + + return !matched; + } + +} // Windows +// -------------------------------------------------------------- + +/* istanbul ignore if */ + + +if ( // Detect `process` so that it can run in browsers. +typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) { + const filter = IgnoreBase.prototype._filter; + /* eslint no-control-regex: "off" */ + + const make_posix = str => /^\\\\\?\\/.test(str) || /[^\x00-\x80]+/.test(str) ? str : str.replace(/\\/g, '/'); + + IgnoreBase.prototype._filter = function filterWin32(path, slices) { + path = make_posix(path); + return filter.call(this, path, slices); + }; +} + +var ignore = options => new IgnoreBase(options); + +/** + * @param {string} filename + * @returns {Promise} + */ + + +function getFileContentOrNull(filename) { + return new Promise((resolve, reject) => { + fs__default['default'].readFile(filename, "utf8", (error, data) => { + if (error && error.code !== "ENOENT") { + reject(createError(filename, error)); + } else { + resolve(error ? null : data); + } + }); + }); +} +/** + * @param {string} filename + * @returns {null | string} + */ + + +getFileContentOrNull.sync = function (filename) { + try { + return fs__default['default'].readFileSync(filename, "utf8"); + } catch (error) { + if (error && error.code === "ENOENT") { + return null; + } + + throw createError(filename, error); + } +}; + +function createError(filename, error) { + return new Error(`Unable to read ${filename}: ${error.message}`); +} + +var getFileContentOrNull_1 = getFileContentOrNull; + +/** + * @param {string?} ignorePath + * @param {boolean?} withNodeModules + */ + + +async function createIgnorer(ignorePath, withNodeModules) { + const ignoreContent = ignorePath ? await getFileContentOrNull_1(path__default['default'].resolve(ignorePath)) : null; + return _createIgnorer(ignoreContent, withNodeModules); +} +/** + * @param {string?} ignorePath + * @param {boolean?} withNodeModules + */ + + +createIgnorer.sync = function (ignorePath, withNodeModules) { + const ignoreContent = !ignorePath ? null : getFileContentOrNull_1.sync(path__default['default'].resolve(ignorePath)); + return _createIgnorer(ignoreContent, withNodeModules); +}; +/** + * @param {null | string} ignoreContent + * @param {boolean?} withNodeModules + */ + + +function _createIgnorer(ignoreContent, withNodeModules) { + const ignorer = ignore().add(ignoreContent || ""); + + if (!withNodeModules) { + ignorer.add("node_modules"); + } + + return ignorer; +} + +var createIgnorer_1 = createIgnorer; + +/** + * @typedef {{ ignorePath?: string, withNodeModules?: boolean, plugins: object }} FileInfoOptions + * @typedef {{ ignored: boolean, inferredParser: string | null }} FileInfoResult + */ + +/** + * @param {string} filePath + * @param {FileInfoOptions} opts + * @returns {Promise} + * + * Please note that prettier.getFileInfo() expects opts.plugins to be an array of paths, + * not an object. A transformation from this array to an object is automatically done + * internally by the method wrapper. See withPlugins() in index.js. + */ + + +async function getFileInfo(filePath, opts) { + if (typeof filePath !== "string") { + throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``); + } + + const ignorer = await createIgnorer_1(opts.ignorePath, opts.withNodeModules); + return _getFileInfo({ + ignorer, + filePath, + plugins: opts.plugins, + resolveConfig: opts.resolveConfig, + ignorePath: opts.ignorePath, + sync: false + }); +} +/** + * @param {string} filePath + * @param {FileInfoOptions} opts + * @returns {FileInfoResult} + */ + + +getFileInfo.sync = function (filePath, opts) { + if (typeof filePath !== "string") { + throw new TypeError(`expect \`filePath\` to be a string, got \`${typeof filePath}\``); + } + + const ignorer = createIgnorer_1.sync(opts.ignorePath, opts.withNodeModules); + return _getFileInfo({ + ignorer, + filePath, + plugins: opts.plugins, + resolveConfig: opts.resolveConfig, + ignorePath: opts.ignorePath, + sync: true + }); +}; + +function getFileParser(resolvedConfig, filePath, plugins) { + if (resolvedConfig && resolvedConfig.parser) { + return resolvedConfig.parser; + } + + const inferredParser = options$1.inferParser(filePath, plugins); + + if (inferredParser) { + return inferredParser; + } + + return null; +} + +function _getFileInfo({ + ignorer, + filePath, + plugins, + resolveConfig = false, + ignorePath, + sync = false +}) { + const normalizedFilePath = normalizeFilePath(filePath, ignorePath); + const fileInfo = { + ignored: ignorer.ignores(normalizedFilePath), + inferredParser: null + }; + + if (fileInfo.ignored) { + return fileInfo; + } + + let resolvedConfig; + + if (resolveConfig) { + if (sync) { + resolvedConfig = resolveConfig_1.resolveConfig.sync(filePath); + } else { + return resolveConfig_1.resolveConfig(filePath).then(resolvedConfig => { + fileInfo.inferredParser = getFileParser(resolvedConfig, filePath, plugins); + return fileInfo; + }); + } + } + + fileInfo.inferredParser = getFileParser(resolvedConfig, filePath, plugins); + return fileInfo; +} + +function normalizeFilePath(filePath, ignorePath) { + return ignorePath ? path__default['default'].relative(path__default['default'].dirname(ignorePath), filePath) : filePath; +} + +var getFileInfo_1 = getFileInfo; + +const { + getMaxContinuousCount: getMaxContinuousCount$1, + getStringWidth: getStringWidth$2, + getAlignmentSize: getAlignmentSize$2, + getIndentSize: getIndentSize$1, + skip: skip$1, + skipWhitespace: skipWhitespace$1, + skipSpaces: skipSpaces$2, + skipNewline: skipNewline$2, + skipToLineEnd: skipToLineEnd$1, + skipEverythingButNewLine: skipEverythingButNewLine$1, + skipInlineComment: skipInlineComment$1, + skipTrailingComment: skipTrailingComment$1, + hasNewline: hasNewline$2, + hasNewlineInRange: hasNewlineInRange$1, + hasSpaces: hasSpaces$1, + isNextLineEmpty: isNextLineEmpty$1, + isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1, + isPreviousLineEmpty: isPreviousLineEmpty$2, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, + makeString: makeString$1, + addLeadingComment: addLeadingComment$2, + addDanglingComment: addDanglingComment$2, + addTrailingComment: addTrailingComment$2 +} = util; +var utilShared = { + getMaxContinuousCount: getMaxContinuousCount$1, + getStringWidth: getStringWidth$2, + getAlignmentSize: getAlignmentSize$2, + getIndentSize: getIndentSize$1, + skip: skip$1, + skipWhitespace: skipWhitespace$1, + skipSpaces: skipSpaces$2, + skipNewline: skipNewline$2, + skipToLineEnd: skipToLineEnd$1, + skipEverythingButNewLine: skipEverythingButNewLine$1, + skipInlineComment: skipInlineComment$1, + skipTrailingComment: skipTrailingComment$1, + hasNewline: hasNewline$2, + hasNewlineInRange: hasNewlineInRange$1, + hasSpaces: hasSpaces$1, + isNextLineEmpty: isNextLineEmpty$1, + isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$1, + isPreviousLineEmpty: isPreviousLineEmpty$2, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1, + makeString: makeString$1, + addLeadingComment: addLeadingComment$2, + addDanglingComment: addDanglingComment$2, + addTrailingComment: addTrailingComment$2 +}; + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +var _listCacheClear = listCacheClear; + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || value !== value && other !== other; +} + +var eq_1 = eq; + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + +function assocIndexOf(array, key) { + var length = array.length; + + while (length--) { + if (eq_1(array[length][0], key)) { + return length; + } + } + + return -1; +} + +var _assocIndexOf = assocIndexOf; + +/** Used for built-in method references. */ + +var arrayProto = Array.prototype; +/** Built-in value references. */ + +var splice = arrayProto.splice; +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + +function listCacheDelete(key) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + if (index < 0) { + return false; + } + + var lastIndex = data.length - 1; + + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + + --this.size; + return true; +} + +var _listCacheDelete = listCacheDelete; + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + +function listCacheGet(key) { + var data = this.__data__, + index = _assocIndexOf(data, key); + return index < 0 ? undefined : data[index][1]; +} + +var _listCacheGet = listCacheGet; + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +function listCacheHas(key) { + return _assocIndexOf(this.__data__, key) > -1; +} + +var _listCacheHas = listCacheHas; + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ + +function listCacheSet(key, value) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + + return this; +} + +var _listCacheSet = listCacheSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + this.clear(); + + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} // Add methods to `ListCache`. + + +ListCache.prototype.clear = _listCacheClear; +ListCache.prototype['delete'] = _listCacheDelete; +ListCache.prototype.get = _listCacheGet; +ListCache.prototype.has = _listCacheHas; +ListCache.prototype.set = _listCacheSet; +var _ListCache = ListCache; + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + +function stackClear() { + this.__data__ = new _ListCache(); + this.size = 0; +} + +var _stackClear = stackClear; + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + this.size = data.size; + return result; +} + +var _stackDelete = stackDelete; + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +var _stackGet = stackGet; + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +var _stackHas = stackHas; + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +var isObject_1 = isObject; + +/** `Object#toString` result references. */ + +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ + +function isFunction(value) { + if (!isObject_1(value)) { + return false; + } // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + + + var tag = _baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +var isFunction_1 = isFunction; + +/** Used to detect overreaching core-js shims. */ + +var coreJsData = _root['__core-js_shared__']; +var _coreJsData = coreJsData; + +/** Used to detect methods masquerading as native. */ + +var maskSrcKey = function () { + var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); + return uid ? 'Symbol(src)_1.' + uid : ''; +}(); +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ + + +function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func; +} + +var _isMasked = isMasked; + +/** Used for built-in method references. */ +var funcProto = Function.prototype; +/** Used to resolve the decompiled source of functions. */ + +var funcToString = funcProto.toString; +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ + +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + + try { + return func + ''; + } catch (e) {} + } + + return ''; +} + +var _toSource = toSource; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; +/** Used to detect host constructors (Safari). */ + +var reIsHostCtor = /^\[object .+?Constructor\]$/; +/** Used for built-in method references. */ + +var funcProto$1 = Function.prototype, + objectProto$3 = Object.prototype; +/** Used to resolve the decompiled source of functions. */ + +var funcToString$1 = funcProto$1.toString; +/** Used to check objects for own properties. */ + +var hasOwnProperty$4 = objectProto$3.hasOwnProperty; +/** Used to detect if a method is native. */ + +var reIsNative = RegExp('^' + funcToString$1.call(hasOwnProperty$4).replace(reRegExpChar, '\\$&').replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'); +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ + +function baseIsNative(value) { + if (!isObject_1(value) || _isMasked(value)) { + return false; + } + + var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; + return pattern.test(_toSource(value)); +} + +var _baseIsNative = baseIsNative; + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +var _getValue = getValue; + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ + +function getNative(object, key) { + var value = _getValue(object, key); + return _baseIsNative(value) ? value : undefined; +} + +var _getNative = getNative; + +/* Built-in method references that are verified to be native. */ + +var Map$1 = _getNative(_root, 'Map'); +var _Map = Map$1; + +/* Built-in method references that are verified to be native. */ + +var nativeCreate = _getNative(Object, 'create'); +var _nativeCreate = nativeCreate; + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + +function hashClear() { + this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; + this.size = 0; +} + +var _hashClear = hashClear; + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +var _hashDelete = hashDelete; + +/** Used to stand-in for `undefined` hash values. */ + +var HASH_UNDEFINED = '__lodash_hash_undefined__'; +/** Used for built-in method references. */ + +var objectProto$4 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$5 = objectProto$4.hasOwnProperty; +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + +function hashGet(key) { + var data = this.__data__; + + if (_nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + + return hasOwnProperty$5.call(data, key) ? data[key] : undefined; +} + +var _hashGet = hashGet; + +/** Used for built-in method references. */ + +var objectProto$5 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$6 = objectProto$5.hasOwnProperty; +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +function hashHas(key) { + var data = this.__data__; + return _nativeCreate ? data[key] !== undefined : hasOwnProperty$6.call(data, key); +} + +var _hashHas = hashHas; + +/** Used to stand-in for `undefined` hash values. */ + +var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ + +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = _nativeCreate && value === undefined ? HASH_UNDEFINED$1 : value; + return this; +} + +var _hashSet = hashSet; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + this.clear(); + + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} // Add methods to `Hash`. + + +Hash.prototype.clear = _hashClear; +Hash.prototype['delete'] = _hashDelete; +Hash.prototype.get = _hashGet; +Hash.prototype.has = _hashHas; +Hash.prototype.set = _hashSet; +var _Hash = Hash; + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ + +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new _Hash(), + 'map': new (_Map || _ListCache)(), + 'string': new _Hash() + }; +} + +var _mapCacheClear = mapCacheClear; + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean' ? value !== '__proto__' : value === null; +} + +var _isKeyable = isKeyable; + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ + +function getMapData(map, key) { + var data = map.__data__; + return _isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; +} + +var _getMapData = getMapData; + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ + +function mapCacheDelete(key) { + var result = _getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +var _mapCacheDelete = mapCacheDelete; + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ + +function mapCacheGet(key) { + return _getMapData(this, key).get(key); +} + +var _mapCacheGet = mapCacheGet; + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + +function mapCacheHas(key) { + return _getMapData(this, key).has(key); +} + +var _mapCacheHas = mapCacheHas; + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ + +function mapCacheSet(key, value) { + var data = _getMapData(this, key), + size = data.size; + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +var _mapCacheSet = mapCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + this.clear(); + + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} // Add methods to `MapCache`. + + +MapCache.prototype.clear = _mapCacheClear; +MapCache.prototype['delete'] = _mapCacheDelete; +MapCache.prototype.get = _mapCacheGet; +MapCache.prototype.has = _mapCacheHas; +MapCache.prototype.set = _mapCacheSet; +var _MapCache = MapCache; + +/** Used as the size to enable large array optimizations. */ + +var LARGE_ARRAY_SIZE = 200; +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ + +function stackSet(key, value) { + var data = this.__data__; + + if (data instanceof _ListCache) { + var pairs = data.__data__; + + if (!_Map || pairs.length < LARGE_ARRAY_SIZE - 1) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + + data = this.__data__ = new _MapCache(pairs); + } + + data.set(key, value); + this.size = data.size; + return this; +} + +var _stackSet = stackSet; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ + +function Stack(entries) { + var data = this.__data__ = new _ListCache(entries); + this.size = data.size; +} // Add methods to `Stack`. + + +Stack.prototype.clear = _stackClear; +Stack.prototype['delete'] = _stackDelete; +Stack.prototype.get = _stackGet; +Stack.prototype.has = _stackHas; +Stack.prototype.set = _stackSet; +var _Stack = Stack; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ + +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + + return this; +} + +var _setCacheAdd = setCacheAdd; + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +var _setCacheHas = setCacheHas; + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ + +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + this.__data__ = new _MapCache(); + + while (++index < length) { + this.add(values[index]); + } +} // Add methods to `SetCache`. + + +SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; +SetCache.prototype.has = _setCacheHas; +var _SetCache = SetCache; + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + + return false; +} + +var _arraySome = arraySome; + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +var _cacheHas = cacheHas; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ + +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } // Check that cyclic values are equal. + + + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + + var index = -1, + result = true, + seen = bitmask & COMPARE_UNORDERED_FLAG ? new _SetCache() : undefined; + stack.set(array, other); + stack.set(other, array); // Ignore non-index properties. + + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); + } + + if (compared !== undefined) { + if (compared) { + continue; + } + + result = false; + break; + } // Recursively compare arrays (susceptible to call stack limits). + + + if (seen) { + if (!_arraySome(other, function (othValue, othIndex) { + if (!_cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + result = false; + break; + } + } + + stack['delete'](array); + stack['delete'](other); + return result; +} + +var _equalArrays = equalArrays; + +/** Built-in value references. */ + +var Uint8Array = _root.Uint8Array; +var _Uint8Array = Uint8Array; + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + map.forEach(function (value, key) { + result[++index] = [key, value]; + }); + return result; +} + +var _mapToArray = mapToArray; + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + set.forEach(function (value) { + result[++index] = value; + }); + return result; +} + +var _setToArray = setToArray; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; +/** `Object#toString` result references. */ + +var boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + mapTag = '[object Map]', + numberTag = '[object Number]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]'; +/** Used to convert symbols to primitives and strings. */ + +var symbolProto = _Symbol ? _Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { + return false; + } + + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if (object.byteLength != other.byteLength || !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { + return false; + } + + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq_1(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == other + ''; + + case mapTag: + var convert = _mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = _setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } // Assume cyclic values are equal. + + + var stacked = stack.get(object); + + if (stacked) { + return stacked == other; + } + + bitmask |= COMPARE_UNORDERED_FLAG$1; // Recursively compare objects (susceptible to call stack limits). + + stack.set(object, other); + var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + + } + + return false; +} + +var _equalByTag = equalByTag; + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); +} + +var _baseGetAllKeys = baseGetAllKeys; + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + + return result; +} + +var _arrayFilter = arrayFilter; + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +var stubArray_1 = stubArray; + +/** Used for built-in method references. */ + +var objectProto$6 = Object.prototype; +/** Built-in value references. */ + +var propertyIsEnumerable$1 = objectProto$6.propertyIsEnumerable; +/* Built-in method references for those with the same name as other `lodash` methods. */ + +var nativeGetSymbols = Object.getOwnPropertySymbols; +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ + +var getSymbols = !nativeGetSymbols ? stubArray_1 : function (object) { + if (object == null) { + return []; + } + + object = Object(object); + return _arrayFilter(nativeGetSymbols(object), function (symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); +}; +var _getSymbols = getSymbols; + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + + return result; +} + +var _baseTimes = baseTimes; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +var stubFalse_1 = stubFalse; + +var isBuffer_1 = createCommonjsModule(function (module, exports) { + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + /** Detect free variable `module`. */ + + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + /** Detect the popular CommonJS extension `module.exports`. */ + + var moduleExports = freeModule && freeModule.exports === freeExports; + /** Built-in value references. */ + + var Buffer = moduleExports ? _root.Buffer : undefined; + /* Built-in method references for those with the same name as other `lodash` methods. */ + + var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + /** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + + var isBuffer = nativeIsBuffer || stubFalse_1; + module.exports = isBuffer; +}); + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$2 = 9007199254740991; +/** Used to detect unsigned integer values. */ + +var reIsUint = /^(?:0|[1-9]\d*)$/; +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ + +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER$2 : length; + return !!length && (type == 'number' || type != 'symbol' && reIsUint.test(value)) && value > -1 && value % 1 == 0 && value < length; +} + +var _isIndex = isIndex; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$3 = 9007199254740991; +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ + +function isLength(value) { + return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$3; +} + +var isLength_1 = isLength; + +/** `Object#toString` result references. */ + +var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + funcTag$1 = '[object Function]', + mapTag$1 = '[object Map]', + numberTag$1 = '[object Number]', + objectTag = '[object Object]', + regexpTag$1 = '[object RegExp]', + setTag$1 = '[object Set]', + stringTag$1 = '[object String]', + weakMapTag = '[object WeakMap]'; +var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$1 = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; +/** Used to identify `toStringTag` values of typed arrays. */ + +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag$1] = typedArrayTags[boolTag$1] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag$1] = typedArrayTags[errorTag$1] = typedArrayTags[funcTag$1] = typedArrayTags[mapTag$1] = typedArrayTags[numberTag$1] = typedArrayTags[objectTag] = typedArrayTags[regexpTag$1] = typedArrayTags[setTag$1] = typedArrayTags[stringTag$1] = typedArrayTags[weakMapTag] = false; +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + +function baseIsTypedArray(value) { + return isObjectLike_1(value) && isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; +} + +var _baseIsTypedArray = baseIsTypedArray; + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function (value) { + return func(value); + }; +} + +var _baseUnary = baseUnary; + +var _nodeUtil = createCommonjsModule(function (module, exports) { + /** Detect free variable `exports`. */ + var freeExports = exports && !exports.nodeType && exports; + /** Detect free variable `module`. */ + + var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + /** Detect the popular CommonJS extension `module.exports`. */ + + var moduleExports = freeModule && freeModule.exports === freeExports; + /** Detect free variable `process` from Node.js. */ + + var freeProcess = moduleExports && _freeGlobal.process; + /** Used to access faster Node.js helpers. */ + + var nodeUtil = function () { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } // Legacy `process.binding('util')` for Node.js < 10. + + + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }(); + + module.exports = nodeUtil; +}); + +/* Node.js helper references. */ + +var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + +var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; +var isTypedArray_1 = isTypedArray; + +/** Used for built-in method references. */ + +var objectProto$7 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$7 = objectProto$7.hasOwnProperty; +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ + +function arrayLikeKeys(value, inherited) { + var isArr = isArray_1(value), + isArg = !isArr && isArguments_1(value), + isBuff = !isArr && !isArg && isBuffer_1(value), + isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? _baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$7.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. + isBuff && (key == 'offset' || key == 'parent') || // PhantomJS 2 has enumerable non-index properties on typed arrays. + isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset') || // Skip index properties. + _isIndex(key, length)))) { + result.push(key); + } + } + + return result; +} + +var _arrayLikeKeys = arrayLikeKeys; + +/** Used for built-in method references. */ +var objectProto$8 = Object.prototype; +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ + +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = typeof Ctor == 'function' && Ctor.prototype || objectProto$8; + return value === proto; +} + +var _isPrototype = isPrototype; + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function (arg) { + return func(transform(arg)); + }; +} + +var _overArg = overArg; + +/* Built-in method references for those with the same name as other `lodash` methods. */ + +var nativeKeys = _overArg(Object.keys, Object); +var _nativeKeys = nativeKeys; + +/** Used for built-in method references. */ + +var objectProto$9 = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$8 = objectProto$9.hasOwnProperty; +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ + +function baseKeys(object) { + if (!_isPrototype(object)) { + return _nativeKeys(object); + } + + var result = []; + + for (var key in Object(object)) { + if (hasOwnProperty$8.call(object, key) && key != 'constructor') { + result.push(key); + } + } + + return result; +} + +var _baseKeys = baseKeys; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ + +function isArrayLike(value) { + return value != null && isLength_1(value.length) && !isFunction_1(value); +} + +var isArrayLike_1 = isArrayLike; + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ + +function keys(object) { + return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); +} + +var keys_1 = keys; + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ + +function getAllKeys(object) { + return _baseGetAllKeys(object, keys_1, _getSymbols); +} + +var _getAllKeys = getAllKeys; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$2 = 1; +/** Used for built-in method references. */ + +var objectProto$a = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$9 = objectProto$a.hasOwnProperty; +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = _getAllKeys(object), + objLength = objProps.length, + othProps = _getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + + var index = objLength; + + while (index--) { + var key = objProps[index]; + + if (!(isPartial ? key in other : hasOwnProperty$9.call(other, key))) { + return false; + } + } // Check that cyclic values are equal. + + + var objStacked = stack.get(object); + var othStacked = stack.get(other); + + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + + var result = true; + stack.set(object, other); + stack.set(other, object); + var skipCtor = isPartial; + + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); + } // Recursively compare objects (susceptible to call stack limits). + + + if (!(compared === undefined ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { + result = false; + break; + } + + skipCtor || (skipCtor = key == 'constructor'); + } + + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. + + if (objCtor != othCtor && 'constructor' in object && 'constructor' in other && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + + stack['delete'](object); + stack['delete'](other); + return result; +} + +var _equalObjects = equalObjects; + +/* Built-in method references that are verified to be native. */ + +var DataView = _getNative(_root, 'DataView'); +var _DataView = DataView; + +/* Built-in method references that are verified to be native. */ + +var Promise$1 = _getNative(_root, 'Promise'); +var _Promise = Promise$1; + +/* Built-in method references that are verified to be native. */ + +var Set$1 = _getNative(_root, 'Set'); +var _Set = Set$1; + +/* Built-in method references that are verified to be native. */ + +var WeakMap$1 = _getNative(_root, 'WeakMap'); +var _WeakMap = WeakMap$1; + +/** `Object#toString` result references. */ + +var mapTag$2 = '[object Map]', + objectTag$1 = '[object Object]', + promiseTag = '[object Promise]', + setTag$2 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; +var dataViewTag$2 = '[object DataView]'; +/** Used to detect maps, sets, and weakmaps. */ + +var dataViewCtorString = _toSource(_DataView), + mapCtorString = _toSource(_Map), + promiseCtorString = _toSource(_Promise), + setCtorString = _toSource(_Set), + weakMapCtorString = _toSource(_WeakMap); +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ + +var getTag = _baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + +if (_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$2 || _Map && getTag(new _Map()) != mapTag$2 || _Promise && getTag(_Promise.resolve()) != promiseTag || _Set && getTag(new _Set()) != setTag$2 || _WeakMap && getTag(new _WeakMap()) != weakMapTag$1) { + getTag = function (value) { + var result = _baseGetTag(value), + Ctor = result == objectTag$1 ? value.constructor : undefined, + ctorString = Ctor ? _toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag$2; + + case mapCtorString: + return mapTag$2; + + case promiseCtorString: + return promiseTag; + + case setCtorString: + return setTag$2; + + case weakMapCtorString: + return weakMapTag$1; + } + } + + return result; + }; +} + +var _getTag = getTag; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$3 = 1; +/** `Object#toString` result references. */ + +var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + objectTag$2 = '[object Object]'; +/** Used for built-in method references. */ + +var objectProto$b = Object.prototype; +/** Used to check objects for own properties. */ + +var hasOwnProperty$a = objectProto$b.hasOwnProperty; +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ + +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray_1(object), + othIsArr = isArray_1(other), + objTag = objIsArr ? arrayTag$1 : _getTag(object), + othTag = othIsArr ? arrayTag$1 : _getTag(other); + objTag = objTag == argsTag$2 ? objectTag$2 : objTag; + othTag = othTag == argsTag$2 ? objectTag$2 : othTag; + var objIsObj = objTag == objectTag$2, + othIsObj = othTag == objectTag$2, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer_1(object)) { + if (!isBuffer_1(other)) { + return false; + } + + objIsArr = true; + objIsObj = false; + } + + if (isSameTag && !objIsObj) { + stack || (stack = new _Stack()); + return objIsArr || isTypedArray_1(object) ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$a.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$a.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + stack || (stack = new _Stack()); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + + if (!isSameTag) { + return false; + } + + stack || (stack = new _Stack()); + return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +var _baseIsEqualDeep = baseIsEqualDeep; + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ + +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + + if (value == null || other == null || !isObjectLike_1(value) && !isObjectLike_1(other)) { + return value !== value && other !== other; + } + + return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +var _baseIsEqual = baseIsEqual; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ + +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + + object = Object(object); + + while (index--) { + var data = matchData[index]; + + if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { + return false; + } + } + + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new _Stack(); + + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + + if (!(result === undefined ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) : result)) { + return false; + } + } + } + + return true; +} + +var _baseIsMatch = baseIsMatch; + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ + +function isStrictComparable(value) { + return value === value && !isObject_1(value); +} + +var _isStrictComparable = isStrictComparable; + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ + +function getMatchData(object) { + var result = keys_1(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + result[length] = [key, value, _isStrictComparable(value)]; + } + + return result; +} + +var _getMatchData = getMatchData; + +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function (object) { + if (object == null) { + return false; + } + + return object[key] === srcValue && (srcValue !== undefined || key in Object(object)); + }; +} + +var _matchesStrictComparable = matchesStrictComparable; + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ + +function baseMatches(source) { + var matchData = _getMatchData(source); + + if (matchData.length == 1 && matchData[0][2]) { + return _matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + + return function (object) { + return object === source || _baseIsMatch(object, source, matchData); + }; +} + +var _baseMatches = baseMatches; + +/** `Object#toString` result references. */ + +var symbolTag$1 = '[object Symbol]'; +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + +function isSymbol(value) { + return typeof value == 'symbol' || isObjectLike_1(value) && _baseGetTag(value) == symbolTag$1; +} + +var isSymbol_1 = isSymbol; + +/** Used to match property names within property paths. */ + +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ + +function isKey(value, object) { + if (isArray_1(value)) { + return false; + } + + var type = typeof value; + + if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol_1(value)) { + return true; + } + + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); +} + +var _isKey = isKey; + +/** Error message constants. */ + +var FUNC_ERROR_TEXT = 'Expected a function'; +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + +function memoize(func, resolver) { + if (typeof func != 'function' || resolver != null && typeof resolver != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + + var memoized = function () { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + + memoized.cache = new (memoize.Cache || _MapCache)(); + return memoized; +} // Expose `MapCache`. + + +memoize.Cache = _MapCache; +var memoize_1 = memoize; + +/** Used as the maximum memoize cache size. */ + +var MAX_MEMOIZE_SIZE = 500; +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ + +function memoizeCapped(func) { + var result = memoize_1(func, function (key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + + return key; + }); + var cache = result.cache; + return result; +} + +var _memoizeCapped = memoizeCapped; + +/** Used to match property names within property paths. */ + +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; +/** Used to match backslashes in property paths. */ + +var reEscapeChar = /\\(\\)?/g; +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ + +var stringToPath = _memoizeCapped(function (string) { + var result = []; + + if (string.charCodeAt(0) === 46 + /* . */ + ) { + result.push(''); + } + + string.replace(rePropName, function (match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : number || match); + }); + return result; +}); +var _stringToPath = stringToPath; + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + + return result; +} + +var _arrayMap = arrayMap; + +/** Used as references for various `Number` constants. */ + +var INFINITY = 1 / 0; +/** Used to convert symbols to primitives and strings. */ + +var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, + symbolToString = symbolProto$1 ? symbolProto$1.toString : undefined; +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ + +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + + if (isArray_1(value)) { + // Recursively convert values (susceptible to call stack limits). + return _arrayMap(value, baseToString) + ''; + } + + if (isSymbol_1(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + + var result = value + ''; + return result == '0' && 1 / value == -INFINITY ? '-0' : result; +} + +var _baseToString = baseToString; + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ + +function toString(value) { + return value == null ? '' : _baseToString(value); +} + +var toString_1 = toString; + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ + +function castPath(value, object) { + if (isArray_1(value)) { + return value; + } + + return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); +} + +var _castPath = castPath; + +/** Used as references for various `Number` constants. */ + +var INFINITY$1 = 1 / 0; +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + +function toKey(value) { + if (typeof value == 'string' || isSymbol_1(value)) { + return value; + } + + var result = value + ''; + return result == '0' && 1 / value == -INFINITY$1 ? '-0' : result; +} + +var _toKey = toKey; + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ + +function baseGet(object, path) { + path = _castPath(path, object); + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[_toKey(path[index++])]; + } + + return index && index == length ? object : undefined; +} + +var _baseGet = baseGet; + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + +function get$1(object, path, defaultValue) { + var result = object == null ? undefined : _baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +var get_1 = get$1; + +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} + +var _baseHasIn = baseHasIn; + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ + +function hasPath(object, path, hasFunc) { + path = _castPath(path, object); + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = _toKey(path[index]); + + if (!(result = object != null && hasFunc(object, key))) { + break; + } + + object = object[key]; + } + + if (result || ++index != length) { + return result; + } + + length = object == null ? 0 : object.length; + return !!length && isLength_1(length) && _isIndex(key, length) && (isArray_1(object) || isArguments_1(object)); +} + +var _hasPath = hasPath; + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + +function hasIn(object, path) { + return object != null && _hasPath(object, path, _baseHasIn); +} + +var hasIn_1 = hasIn; + +/** Used to compose bitmasks for value comparisons. */ + +var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ + +function baseMatchesProperty(path, srcValue) { + if (_isKey(path) && _isStrictComparable(srcValue)) { + return _matchesStrictComparable(_toKey(path), srcValue); + } + + return function (object) { + var objValue = get_1(object, path); + return objValue === undefined && objValue === srcValue ? hasIn_1(object, path) : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; +} + +var _baseMatchesProperty = baseMatchesProperty; + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +var identity_1 = identity; + +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function (object) { + return object == null ? undefined : object[key]; + }; +} + +var _baseProperty = baseProperty; + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ + +function basePropertyDeep(path) { + return function (object) { + return _baseGet(object, path); + }; +} + +var _basePropertyDeep = basePropertyDeep; + +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ + +function property(path) { + return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); +} + +var property_1 = property; + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + + if (value == null) { + return identity_1; + } + + if (typeof value == 'object') { + return isArray_1(value) ? _baseMatchesProperty(value[0], value[1]) : _baseMatches(value); + } + + return property_1(value); +} + +var _baseIteratee = baseIteratee; + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; + } + } + + return -1; +} + +var _baseFindIndex = baseFindIndex; + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +var _baseIsNaN = baseIsNaN; + +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + + return -1; +} + +var _strictIndexOf = strictIndexOf; + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + +function baseIndexOf(array, value, fromIndex) { + return value === value ? _strictIndexOf(array, value, fromIndex) : _baseFindIndex(array, _baseIsNaN, fromIndex); +} + +var _baseIndexOf = baseIndexOf; + +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + +function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && _baseIndexOf(array, value, 0) > -1; +} + +var _arrayIncludes = arrayIncludes; + +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + + return false; +} + +var _arrayIncludesWith = arrayIncludesWith; + +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() {// No operation performed. +} + +var noop_1 = noop; + +/** Used as references for various `Number` constants. */ + +var INFINITY$2 = 1 / 0; +/** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + +var createSet = !(_Set && 1 / _setToArray(new _Set([, -0]))[1] == INFINITY$2) ? noop_1 : function (values) { + return new _Set(values); +}; +var _createSet = createSet; + +/** Used as the size to enable large array optimizations. */ + +var LARGE_ARRAY_SIZE$1 = 200; +/** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ + +function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = _arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = _arrayIncludesWith; + } else if (length >= LARGE_ARRAY_SIZE$1) { + var set = iteratee ? null : _createSet(array); + + if (set) { + return _setToArray(set); + } + + isCommon = false; + includes = _cacheHas; + seen = new _SetCache(); + } else { + seen = iteratee ? [] : result; + } + + outer: while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + value = comparator || value !== 0 ? value : 0; + + if (isCommon && computed === computed) { + var seenIndex = seen.length; + + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + + if (iteratee) { + seen.push(computed); + } + + result.push(value); + } else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + + result.push(value); + } + } + + return result; +} + +var _baseUniq = baseUniq; + +/** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + +function uniqBy(array, iteratee) { + return array && array.length ? _baseUniq(array, _baseIteratee(iteratee)) : []; +} + +var uniqBy_1 = uniqBy; + +/** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ +function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + + return accumulator; +} + +var _arrayAggregator = arrayAggregator; + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function (object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + + return object; + }; +} + +var _createBaseFor = createBaseFor; + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + +var baseFor = _createBaseFor(); +var _baseFor = baseFor; + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ + +function baseForOwn(object, iteratee) { + return object && _baseFor(object, iteratee, keys_1); +} + +var _baseForOwn = baseForOwn; + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + +function createBaseEach(eachFunc, fromRight) { + return function (collection, iteratee) { + if (collection == null) { + return collection; + } + + if (!isArrayLike_1(collection)) { + return eachFunc(collection, iteratee); + } + + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while (fromRight ? index-- : ++index < length) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + + return collection; + }; +} + +var _createBaseEach = createBaseEach; + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ + +var baseEach = _createBaseEach(_baseForOwn); +var _baseEach = baseEach; + +/** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + +function baseAggregator(collection, setter, iteratee, accumulator) { + _baseEach(collection, function (value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; +} + +var _baseAggregator = baseAggregator; + +/** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ + +function createAggregator(setter, initializer) { + return function (collection, iteratee) { + var func = isArray_1(collection) ? _arrayAggregator : _baseAggregator, + accumulator = initializer ? initializer() : {}; + return func(collection, setter, _baseIteratee(iteratee), accumulator); + }; +} + +var _createAggregator = createAggregator; + +/** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + +var partition = _createAggregator(function (result, value, key) { + result[key ? 0 : 1].push(value); +}, function () { + return [[], []]; +}); +var partition_1 = partition; + +var arrayUnion = (...arguments_) => { + return [...new Set([].concat(...arguments_))]; +}; + +/* + * merge2 + * https://github.com/teambition/merge2 + * + * Copyright (c) 2014-2020 Teambition + * Licensed under the MIT license. + */ + + +const PassThrough = stream__default['default'].PassThrough; +const slice = Array.prototype.slice; +var merge2_1 = merge2; + +function merge2() { + const streamsQueue = []; + const args = slice.call(arguments); + let merging = false; + let options = args[args.length - 1]; + + if (options && !Array.isArray(options) && options.pipe == null) { + args.pop(); + } else { + options = {}; + } + + const doEnd = options.end !== false; + const doPipeError = options.pipeError === true; + + if (options.objectMode == null) { + options.objectMode = true; + } + + if (options.highWaterMark == null) { + options.highWaterMark = 64 * 1024; + } + + const mergedStream = PassThrough(options); + + function addStream() { + for (let i = 0, len = arguments.length; i < len; i++) { + streamsQueue.push(pauseStreams(arguments[i], options)); + } + + mergeStream(); + return this; + } + + function mergeStream() { + if (merging) { + return; + } + + merging = true; + let streams = streamsQueue.shift(); + + if (!streams) { + process.nextTick(endStream); + return; + } + + if (!Array.isArray(streams)) { + streams = [streams]; + } + + let pipesCount = streams.length + 1; + + function next() { + if (--pipesCount > 0) { + return; + } + + merging = false; + mergeStream(); + } + + function pipe(stream) { + function onend() { + stream.removeListener('merge2UnpipeEnd', onend); + stream.removeListener('end', onend); + + if (doPipeError) { + stream.removeListener('error', onerror); + } + + next(); + } + + function onerror(err) { + mergedStream.emit('error', err); + } // skip ended stream + + + if (stream._readableState.endEmitted) { + return next(); + } + + stream.on('merge2UnpipeEnd', onend); + stream.on('end', onend); + + if (doPipeError) { + stream.on('error', onerror); + } + + stream.pipe(mergedStream, { + end: false + }); // compatible for old stream + + stream.resume(); + } + + for (let i = 0; i < streams.length; i++) { + pipe(streams[i]); + } + + next(); + } + + function endStream() { + merging = false; // emit 'queueDrain' when all streams merged. + + mergedStream.emit('queueDrain'); + + if (doEnd) { + mergedStream.end(); + } + } + + mergedStream.setMaxListeners(0); + mergedStream.add = addStream; + mergedStream.on('unpipe', function (stream) { + stream.emit('merge2UnpipeEnd'); + }); + + if (args.length) { + addStream.apply(null, args); + } + + return mergedStream; +} // check and pause streams for pipe. + + +function pauseStreams(streams, options) { + if (!Array.isArray(streams)) { + // Backwards-compat with old-style streams + if (!streams._readableState && streams.pipe) { + streams = streams.pipe(PassThrough(options)); + } + + if (!streams._readableState || !streams.pause || !streams.pipe) { + throw new Error('Only readable stream can be merged.'); + } + + streams.pause(); + } else { + for (let i = 0, len = streams.length; i < len; i++) { + streams[i] = pauseStreams(streams[i], options); + } + } + + return streams; +} + +var array$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.splitWhen = exports.flatten = void 0; + + function flatten(items) { + return items.reduce((collection, item) => [].concat(collection, item), []); + } + + exports.flatten = flatten; + + function splitWhen(items, predicate) { + const result = [[]]; + let groupIndex = 0; + + for (const item of items) { + if (predicate(item)) { + groupIndex++; + result[groupIndex] = []; + } else { + result[groupIndex].push(item); + } + } + + return result; + } + + exports.splitWhen = splitWhen; +}); + +var errno = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isEnoentCodeError = void 0; + + function isEnoentCodeError(error) { + return error.code === 'ENOENT'; + } + + exports.isEnoentCodeError = isEnoentCodeError; +}); + +var fs$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.createDirentFromStats = void 0; + + class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } + + } + + function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); + } + + exports.createDirentFromStats = createDirentFromStats; +}); + +var path_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.removeLeadingDotSegment = exports.escape = exports.makeAbsolute = exports.unixify = void 0; + const LEADING_DOT_SEGMENT_CHARACTERS_COUNT = 2; // ./ or .\\ + + const UNESCAPED_GLOB_SYMBOLS_RE = /(\\?)([()*?[\]{|}]|^!|[!+@](?=\())/g; + /** + * Designed to work only with simple paths: `dir\\file`. + */ + + function unixify(filepath) { + return filepath.replace(/\\/g, '/'); + } + + exports.unixify = unixify; + + function makeAbsolute(cwd, filepath) { + return path__default['default'].resolve(cwd, filepath); + } + + exports.makeAbsolute = makeAbsolute; + + function escape(pattern) { + return pattern.replace(UNESCAPED_GLOB_SYMBOLS_RE, '\\$2'); + } + + exports.escape = escape; + + function removeLeadingDotSegment(entry) { + // We do not use `startsWith` because this is 10x slower than current implementation for some cases. + // eslint-disable-next-line @typescript-eslint/prefer-string-starts-ends-with + if (entry.charAt(0) === '.') { + const secondCharactery = entry.charAt(1); + + if (secondCharactery === '/' || secondCharactery === '\\') { + return entry.slice(LEADING_DOT_SEGMENT_CHARACTERS_COUNT); + } + } + + return entry; + } + + exports.removeLeadingDotSegment = removeLeadingDotSegment; +}); + +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ +var isExtglob = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + + while (match = /(\\).|([@?!+*]\(.*\))/g.exec(str)) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; + +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var chars = { + '{': '}', + '(': ')', + '[': ']' +}; +var strictRegex = /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; +var relaxedRegex = /\\(.)|(^!|[*?{}()[\]]|\(\?)/; + +var isGlob = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var regex = strictRegex; + var match; // optionally relax regex + + if (options && options.strict === false) { + regex = relaxedRegex; + } + + while (match = regex.exec(str)) { + if (match[2]) return true; + var idx = match.index + match[0].length; // if an open bracket/brace/paren is escaped, + // set the index to the next closing character + + var open = match[1]; + var close = open ? chars[open] : null; + + if (open && close) { + var n = str.indexOf(close, idx); + + if (n !== -1) { + idx = n + 1; + } + } + + str = str.slice(idx); + } + + return false; +}; + +var pathPosixDirname = path__default['default'].posix.dirname; +var isWin32 = os__default['default'].platform() === 'win32'; +var slash = '/'; +var backslash = /\\/g; +var enclosure = /[\{\[].*[\/]*.*[\}\]]$/; +var globby = /(^|[^\\])([\{\[]|\([^\)]+$)/; +var escaped = /\\([\!\*\?\|\[\]\(\)\{\}])/g; +/** + * @param {string} str + * @param {Object} opts + * @param {boolean} [opts.flipBackslashes=true] + */ + +var globParent = function globParent(str, opts) { + var options = Object.assign({ + flipBackslashes: true + }, opts); // flip windows path separators + + if (options.flipBackslashes && isWin32 && str.indexOf(slash) < 0) { + str = str.replace(backslash, slash); + } // special case for strings ending in enclosure containing path separator + + + if (enclosure.test(str)) { + str += slash; + } // preserves full path in case of trailing path separator + + + str += 'a'; // remove path parts that are globby + + do { + str = pathPosixDirname(str); + } while (isGlob(str) || globby.test(str)); // remove escape chars and return result + + + return str.replace(escaped, '$1'); +}; + +var utils$1 = createCommonjsModule(function (module, exports) { + + exports.isInteger = num => { + if (typeof num === 'number') { + return Number.isInteger(num); + } + + if (typeof num === 'string' && num.trim() !== '') { + return Number.isInteger(Number(num)); + } + + return false; + }; + /** + * Find a node of the given type + */ + + + exports.find = (node, type) => node.nodes.find(node => node.type === type); + /** + * Find a node of the given type + */ + + + exports.exceedsLimit = (min, max, step = 1, limit) => { + if (limit === false) return false; + if (!exports.isInteger(min) || !exports.isInteger(max)) return false; + return (Number(max) - Number(min)) / Number(step) >= limit; + }; + /** + * Escape the given node with '\\' before node.value + */ + + + exports.escapeNode = (block, n = 0, type) => { + let node = block.nodes[n]; + if (!node) return; + + if (type && node.type === type || node.type === 'open' || node.type === 'close') { + if (node.escaped !== true) { + node.value = '\\' + node.value; + node.escaped = true; + } + } + }; + /** + * Returns true if the given brace node should be enclosed in literal braces + */ + + + exports.encloseBrace = node => { + if (node.type !== 'brace') return false; + + if (node.commas >> 0 + node.ranges >> 0 === 0) { + node.invalid = true; + return true; + } + + return false; + }; + /** + * Returns true if a brace node is invalid. + */ + + + exports.isInvalidBrace = block => { + if (block.type !== 'brace') return false; + if (block.invalid === true || block.dollar) return true; + + if (block.commas >> 0 + block.ranges >> 0 === 0) { + block.invalid = true; + return true; + } + + if (block.open !== true || block.close !== true) { + block.invalid = true; + return true; + } + + return false; + }; + /** + * Returns true if a node is an open or close node + */ + + + exports.isOpenOrClose = node => { + if (node.type === 'open' || node.type === 'close') { + return true; + } + + return node.open === true || node.close === true; + }; + /** + * Reduce an array of text nodes. + */ + + + exports.reduce = nodes => nodes.reduce((acc, node) => { + if (node.type === 'text') acc.push(node.value); + if (node.type === 'range') node.type = 'text'; + return acc; + }, []); + /** + * Flatten an array + */ + + + exports.flatten = (...args) => { + const result = []; + + const flat = arr => { + for (let i = 0; i < arr.length; i++) { + let ele = arr[i]; + Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele); + } + + return result; + }; + + flat(args); + return result; + }; +}); + +var stringify$1 = (ast, options = {}) => { + let stringify = (node, parent = {}) => { + let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let output = ''; + + if (node.value) { + if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) { + return '\\' + node.value; + } + + return node.value; + } + + if (node.value) { + return node.value; + } + + if (node.nodes) { + for (let child of node.nodes) { + output += stringify(child); + } + } + + return output; + }; + + return stringify(ast); +}; + +/*! + * is-number + * + * Copyright (c) 2014-present, Jon Schlinkert. + * Released under the MIT License. + */ + +var isNumber = function (num) { + if (typeof num === 'number') { + return num - num === 0; + } + + if (typeof num === 'string' && num.trim() !== '') { + return Number.isFinite ? Number.isFinite(+num) : isFinite(+num); + } + + return false; +}; + +const toRegexRange = (min, max, options) => { + if (isNumber(min) === false) { + throw new TypeError('toRegexRange: expected the first argument to be a number'); + } + + if (max === void 0 || min === max) { + return String(min); + } + + if (isNumber(max) === false) { + throw new TypeError('toRegexRange: expected the second argument to be a number.'); + } + + let opts = Object.assign({ + relaxZeros: true + }, options); + + if (typeof opts.strictZeros === 'boolean') { + opts.relaxZeros = opts.strictZeros === false; + } + + let relax = String(opts.relaxZeros); + let shorthand = String(opts.shorthand); + let capture = String(opts.capture); + let wrap = String(opts.wrap); + let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap; + + if (toRegexRange.cache.hasOwnProperty(cacheKey)) { + return toRegexRange.cache[cacheKey].result; + } + + let a = Math.min(min, max); + let b = Math.max(min, max); + + if (Math.abs(a - b) === 1) { + let result = min + '|' + max; + + if (opts.capture) { + return `(${result})`; + } + + if (opts.wrap === false) { + return result; + } + + return `(?:${result})`; + } + + let isPadded = hasPadding(min) || hasPadding(max); + let state = { + min, + max, + a, + b + }; + let positives = []; + let negatives = []; + + if (isPadded) { + state.isPadded = isPadded; + state.maxLen = String(state.max).length; + } + + if (a < 0) { + let newMin = b < 0 ? Math.abs(b) : 1; + negatives = splitToPatterns(newMin, Math.abs(a), state, opts); + a = state.a = 0; + } + + if (b >= 0) { + positives = splitToPatterns(a, b, state, opts); + } + + state.negatives = negatives; + state.positives = positives; + state.result = collatePatterns(negatives, positives); + + if (opts.capture === true) { + state.result = `(${state.result})`; + } else if (opts.wrap !== false && positives.length + negatives.length > 1) { + state.result = `(?:${state.result})`; + } + + toRegexRange.cache[cacheKey] = state; + return state.result; +}; + +function collatePatterns(neg, pos, options) { + let onlyNegative = filterPatterns(neg, pos, '-', false) || []; + let onlyPositive = filterPatterns(pos, neg, '', false) || []; + let intersected = filterPatterns(neg, pos, '-?', true) || []; + let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive); + return subpatterns.join('|'); +} + +function splitToRanges(min, max) { + let nines = 1; + let zeros = 1; + let stop = countNines(min, nines); + let stops = new Set([max]); + + while (min <= stop && stop <= max) { + stops.add(stop); + nines += 1; + stop = countNines(min, nines); + } + + stop = countZeros(max + 1, zeros) - 1; + + while (min < stop && stop <= max) { + stops.add(stop); + zeros += 1; + stop = countZeros(max + 1, zeros) - 1; + } + + stops = [...stops]; + stops.sort(compare$1); + return stops; +} +/** + * Convert a range to a regex pattern + * @param {Number} `start` + * @param {Number} `stop` + * @return {String} + */ + + +function rangeToPattern(start, stop, options) { + if (start === stop) { + return { + pattern: start, + count: [], + digits: 0 + }; + } + + let zipped = zip(start, stop); + let digits = zipped.length; + let pattern = ''; + let count = 0; + + for (let i = 0; i < digits; i++) { + let [startDigit, stopDigit] = zipped[i]; + + if (startDigit === stopDigit) { + pattern += startDigit; + } else if (startDigit !== '0' || stopDigit !== '9') { + pattern += toCharacterClass(startDigit, stopDigit); + } else { + count++; + } + } + + if (count) { + pattern += options.shorthand === true ? '\\d' : '[0-9]'; + } + + return { + pattern, + count: [count], + digits + }; +} + +function splitToPatterns(min, max, tok, options) { + let ranges = splitToRanges(min, max); + let tokens = []; + let start = min; + let prev; + + for (let i = 0; i < ranges.length; i++) { + let max = ranges[i]; + let obj = rangeToPattern(String(start), String(max), options); + let zeros = ''; + + if (!tok.isPadded && prev && prev.pattern === obj.pattern) { + if (prev.count.length > 1) { + prev.count.pop(); + } + + prev.count.push(obj.count[0]); + prev.string = prev.pattern + toQuantifier(prev.count); + start = max + 1; + continue; + } + + if (tok.isPadded) { + zeros = padZeros(max, tok, options); + } + + obj.string = zeros + obj.pattern + toQuantifier(obj.count); + tokens.push(obj); + start = max + 1; + prev = obj; + } + + return tokens; +} + +function filterPatterns(arr, comparison, prefix, intersection, options) { + let result = []; + + for (let ele of arr) { + let { + string + } = ele; // only push if _both_ are negative... + + if (!intersection && !contains(comparison, 'string', string)) { + result.push(prefix + string); + } // or _both_ are positive + + + if (intersection && contains(comparison, 'string', string)) { + result.push(prefix + string); + } + } + + return result; +} +/** + * Zip strings + */ + + +function zip(a, b) { + let arr = []; + + for (let i = 0; i < a.length; i++) arr.push([a[i], b[i]]); + + return arr; +} + +function compare$1(a, b) { + return a > b ? 1 : b > a ? -1 : 0; +} + +function contains(arr, key, val) { + return arr.some(ele => ele[key] === val); +} + +function countNines(min, len) { + return Number(String(min).slice(0, -len) + '9'.repeat(len)); +} + +function countZeros(integer, zeros) { + return integer - integer % Math.pow(10, zeros); +} + +function toQuantifier(digits) { + let [start = 0, stop = ''] = digits; + + if (stop || start > 1) { + return `{${start + (stop ? ',' + stop : '')}}`; + } + + return ''; +} + +function toCharacterClass(a, b, options) { + return `[${a}${b - a === 1 ? '' : '-'}${b}]`; +} + +function hasPadding(str) { + return /^-?(0+)\d/.test(str); +} + +function padZeros(value, tok, options) { + if (!tok.isPadded) { + return value; + } + + let diff = Math.abs(tok.maxLen - String(value).length); + let relax = options.relaxZeros !== false; + + switch (diff) { + case 0: + return ''; + + case 1: + return relax ? '0?' : '0'; + + case 2: + return relax ? '0{0,2}' : '00'; + + default: + { + return relax ? `0{0,${diff}}` : `0{${diff}}`; + } + } +} +/** + * Cache + */ + + +toRegexRange.cache = {}; + +toRegexRange.clearCache = () => toRegexRange.cache = {}; +/** + * Expose `toRegexRange` + */ + + +var toRegexRange_1 = toRegexRange; + +const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val); + +const transform = toNumber => { + return value => toNumber === true ? Number(value) : String(value); +}; + +const isValidValue = value => { + return typeof value === 'number' || typeof value === 'string' && value !== ''; +}; + +const isNumber$1 = num => Number.isInteger(+num); + +const zeros = input => { + let value = `${input}`; + let index = -1; + if (value[0] === '-') value = value.slice(1); + if (value === '0') return false; + + while (value[++index] === '0'); + + return index > 0; +}; + +const stringify$2 = (start, end, options) => { + if (typeof start === 'string' || typeof end === 'string') { + return true; + } + + return options.stringify === true; +}; + +const pad = (input, maxLength, toNumber) => { + if (maxLength > 0) { + let dash = input[0] === '-' ? '-' : ''; + if (dash) input = input.slice(1); + input = dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'); + } + + if (toNumber === false) { + return String(input); + } + + return input; +}; + +const toMaxLen = (input, maxLength) => { + let negative = input[0] === '-' ? '-' : ''; + + if (negative) { + input = input.slice(1); + maxLength--; + } + + while (input.length < maxLength) input = '0' + input; + + return negative ? '-' + input : input; +}; + +const toSequence = (parts, options) => { + parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0); + let prefix = options.capture ? '' : '?:'; + let positives = ''; + let negatives = ''; + let result; + + if (parts.positives.length) { + positives = parts.positives.join('|'); + } + + if (parts.negatives.length) { + negatives = `-(${prefix}${parts.negatives.join('|')})`; + } + + if (positives && negatives) { + result = `${positives}|${negatives}`; + } else { + result = positives || negatives; + } + + if (options.wrap) { + return `(${prefix}${result})`; + } + + return result; +}; + +const toRange = (a, b, isNumbers, options) => { + if (isNumbers) { + return toRegexRange_1(a, b, Object.assign({ + wrap: false + }, options)); + } + + let start = String.fromCharCode(a); + if (a === b) return start; + let stop = String.fromCharCode(b); + return `[${start}-${stop}]`; +}; + +const toRegex = (start, end, options) => { + if (Array.isArray(start)) { + let wrap = options.wrap === true; + let prefix = options.capture ? '' : '?:'; + return wrap ? `(${prefix}${start.join('|')})` : start.join('|'); + } + + return toRegexRange_1(start, end, options); +}; + +const rangeError = (...args) => { + return new RangeError('Invalid range arguments: ' + util__default['default'].inspect(...args)); +}; + +const invalidRange = (start, end, options) => { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; +}; + +const invalidStep = (step, options) => { + if (options.strictRanges === true) { + throw new TypeError(`Expected step "${step}" to be a number`); + } + + return []; +}; + +const fillNumbers = (start, end, step = 1, options = {}) => { + let a = Number(start); + let b = Number(end); + + if (!Number.isInteger(a) || !Number.isInteger(b)) { + if (options.strictRanges === true) throw rangeError([start, end]); + return []; + } // fix negative zero + + + if (a === 0) a = 0; + if (b === 0) b = 0; + let descending = a > b; + let startString = String(start); + let endString = String(end); + let stepString = String(step); + step = Math.max(Math.abs(step), 1); + let padded = zeros(startString) || zeros(endString) || zeros(stepString); + let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0; + let toNumber = padded === false && stringify$2(start, end, options) === false; + let format = options.transform || transform(toNumber); + + if (options.toRegex && step === 1) { + return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options); + } + + let parts = { + negatives: [], + positives: [] + }; + + let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num)); + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + if (options.toRegex === true && step > 1) { + push(a); + } else { + range.push(pad(format(a, index), maxLen, toNumber)); + } + + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return step > 1 ? toSequence(parts, options) : toRegex(range, null, Object.assign({ + wrap: false + }, options)); + } + + return range; +}; + +const fillLetters = (start, end, step = 1, options = {}) => { + if (!isNumber$1(start) && start.length > 1 || !isNumber$1(end) && end.length > 1) { + return invalidRange(start, end, options); + } + + let format = options.transform || (val => String.fromCharCode(val)); + + let a = `${start}`.charCodeAt(0); + let b = `${end}`.charCodeAt(0); + let descending = a > b; + let min = Math.min(a, b); + let max = Math.max(a, b); + + if (options.toRegex && step === 1) { + return toRange(min, max, false, options); + } + + let range = []; + let index = 0; + + while (descending ? a >= b : a <= b) { + range.push(format(a, index)); + a = descending ? a - step : a + step; + index++; + } + + if (options.toRegex === true) { + return toRegex(range, null, { + wrap: false, + options + }); + } + + return range; +}; + +const fill$2 = (start, end, step, options = {}) => { + if (end == null && isValidValue(start)) { + return [start]; + } + + if (!isValidValue(start) || !isValidValue(end)) { + return invalidRange(start, end, options); + } + + if (typeof step === 'function') { + return fill$2(start, end, 1, { + transform: step + }); + } + + if (isObject$1(step)) { + return fill$2(start, end, 0, step); + } + + let opts = Object.assign({}, options); + if (opts.capture === true) opts.wrap = true; + step = step || opts.step || 1; + + if (!isNumber$1(step)) { + if (step != null && !isObject$1(step)) return invalidStep(step, opts); + return fill$2(start, end, 1, step); + } + + if (isNumber$1(start) && isNumber$1(end)) { + return fillNumbers(start, end, step, opts); + } + + return fillLetters(start, end, Math.max(Math.abs(step), 1), opts); +}; + +var fillRange = fill$2; + +const compile = (ast, options = {}) => { + let walk = (node, parent = {}) => { + let invalidBlock = utils$1.isInvalidBrace(parent); + let invalidNode = node.invalid === true && options.escapeInvalid === true; + let invalid = invalidBlock === true || invalidNode === true; + let prefix = options.escapeInvalid === true ? '\\' : ''; + let output = ''; + + if (node.isOpen === true) { + return prefix + node.value; + } + + if (node.isClose === true) { + return prefix + node.value; + } + + if (node.type === 'open') { + return invalid ? prefix + node.value : '('; + } + + if (node.type === 'close') { + return invalid ? prefix + node.value : ')'; + } + + if (node.type === 'comma') { + return node.prev.type === 'comma' ? '' : invalid ? node.value : '|'; + } + + if (node.value) { + return node.value; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$1.reduce(node.nodes); + let range = fillRange(...args, Object.assign({}, options, { + wrap: false, + toRegex: true + })); + + if (range.length !== 0) { + return args.length > 1 && range.length > 1 ? `(${range})` : range; + } + } + + if (node.nodes) { + for (let child of node.nodes) { + output += walk(child, node); + } + } + + return output; + }; + + return walk(ast); +}; + +var compile_1 = compile; + +const append = (queue = '', stash = '', enclose = false) => { + let result = []; + queue = [].concat(queue); + stash = [].concat(stash); + if (!stash.length) return queue; + + if (!queue.length) { + return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash; + } + + for (let item of queue) { + if (Array.isArray(item)) { + for (let value of item) { + result.push(append(value, stash, enclose)); + } + } else { + for (let ele of stash) { + if (enclose === true && typeof ele === 'string') ele = `{${ele}}`; + result.push(Array.isArray(ele) ? append(item, ele, enclose) : item + ele); + } + } + } + + return utils$1.flatten(result); +}; + +const expand$1 = (ast, options = {}) => { + let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit; + + let walk = (node, parent = {}) => { + node.queue = []; + let p = parent; + let q = parent.queue; + + while (p.type !== 'brace' && p.type !== 'root' && p.parent) { + p = p.parent; + q = p.queue; + } + + if (node.invalid || node.dollar) { + q.push(append(q.pop(), stringify$1(node, options))); + return; + } + + if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) { + q.push(append(q.pop(), ['{}'])); + return; + } + + if (node.nodes && node.ranges > 0) { + let args = utils$1.reduce(node.nodes); + + if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) { + throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.'); + } + + let range = fillRange(...args, options); + + if (range.length === 0) { + range = stringify$1(node, options); + } + + q.push(append(q.pop(), range)); + node.nodes = []; + return; + } + + let enclose = utils$1.encloseBrace(node); + let queue = node.queue; + let block = node; + + while (block.type !== 'brace' && block.type !== 'root' && block.parent) { + block = block.parent; + queue = block.queue; + } + + for (let i = 0; i < node.nodes.length; i++) { + let child = node.nodes[i]; + + if (child.type === 'comma' && node.type === 'brace') { + if (i === 1) queue.push(''); + queue.push(''); + continue; + } + + if (child.type === 'close') { + q.push(append(q.pop(), queue, enclose)); + continue; + } + + if (child.value && child.type !== 'open') { + queue.push(append(queue.pop(), child.value)); + continue; + } + + if (child.nodes) { + walk(child, node); + } + } + + return queue; + }; + + return utils$1.flatten(walk(ast)); +}; + +var expand_1 = expand$1; + +var constants$2 = { + MAX_LENGTH: 1024 * 64, + // Digits + CHAR_0: '0', + + /* 0 */ + CHAR_9: '9', + + /* 9 */ + // Alphabet chars. + CHAR_UPPERCASE_A: 'A', + + /* A */ + CHAR_LOWERCASE_A: 'a', + + /* a */ + CHAR_UPPERCASE_Z: 'Z', + + /* Z */ + CHAR_LOWERCASE_Z: 'z', + + /* z */ + CHAR_LEFT_PARENTHESES: '(', + + /* ( */ + CHAR_RIGHT_PARENTHESES: ')', + + /* ) */ + CHAR_ASTERISK: '*', + + /* * */ + // Non-alphabetic chars. + CHAR_AMPERSAND: '&', + + /* & */ + CHAR_AT: '@', + + /* @ */ + CHAR_BACKSLASH: '\\', + + /* \ */ + CHAR_BACKTICK: '`', + + /* ` */ + CHAR_CARRIAGE_RETURN: '\r', + + /* \r */ + CHAR_CIRCUMFLEX_ACCENT: '^', + + /* ^ */ + CHAR_COLON: ':', + + /* : */ + CHAR_COMMA: ',', + + /* , */ + CHAR_DOLLAR: '$', + + /* . */ + CHAR_DOT: '.', + + /* . */ + CHAR_DOUBLE_QUOTE: '"', + + /* " */ + CHAR_EQUAL: '=', + + /* = */ + CHAR_EXCLAMATION_MARK: '!', + + /* ! */ + CHAR_FORM_FEED: '\f', + + /* \f */ + CHAR_FORWARD_SLASH: '/', + + /* / */ + CHAR_HASH: '#', + + /* # */ + CHAR_HYPHEN_MINUS: '-', + + /* - */ + CHAR_LEFT_ANGLE_BRACKET: '<', + + /* < */ + CHAR_LEFT_CURLY_BRACE: '{', + + /* { */ + CHAR_LEFT_SQUARE_BRACKET: '[', + + /* [ */ + CHAR_LINE_FEED: '\n', + + /* \n */ + CHAR_NO_BREAK_SPACE: '\u00A0', + + /* \u00A0 */ + CHAR_PERCENT: '%', + + /* % */ + CHAR_PLUS: '+', + + /* + */ + CHAR_QUESTION_MARK: '?', + + /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: '>', + + /* > */ + CHAR_RIGHT_CURLY_BRACE: '}', + + /* } */ + CHAR_RIGHT_SQUARE_BRACKET: ']', + + /* ] */ + CHAR_SEMICOLON: ';', + + /* ; */ + CHAR_SINGLE_QUOTE: '\'', + + /* ' */ + CHAR_SPACE: ' ', + + /* */ + CHAR_TAB: '\t', + + /* \t */ + CHAR_UNDERSCORE: '_', + + /* _ */ + CHAR_VERTICAL_LINE: '|', + + /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' + /* \uFEFF */ + +}; + +/** + * Constants + */ + + +const { + MAX_LENGTH: MAX_LENGTH$2, + CHAR_BACKSLASH, + + /* \ */ + CHAR_BACKTICK, + + /* ` */ + CHAR_COMMA: CHAR_COMMA$1, + + /* , */ + CHAR_DOT, + + /* . */ + CHAR_LEFT_PARENTHESES, + + /* ( */ + CHAR_RIGHT_PARENTHESES, + + /* ) */ + CHAR_LEFT_CURLY_BRACE, + + /* { */ + CHAR_RIGHT_CURLY_BRACE, + + /* } */ + CHAR_LEFT_SQUARE_BRACKET, + + /* [ */ + CHAR_RIGHT_SQUARE_BRACKET, + + /* ] */ + CHAR_DOUBLE_QUOTE, + + /* " */ + CHAR_SINGLE_QUOTE, + + /* ' */ + CHAR_NO_BREAK_SPACE, + CHAR_ZERO_WIDTH_NOBREAK_SPACE +} = constants$2; +/** + * parse + */ + +const parse$5 = (input, options = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + let opts = options || {}; + let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$2, opts.maxLength) : MAX_LENGTH$2; + + if (input.length > max) { + throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`); + } + + let ast = { + type: 'root', + input, + nodes: [] + }; + let stack = [ast]; + let block = ast; + let prev = ast; + let brackets = 0; + let length = input.length; + let index = 0; + let depth = 0; + let value; + /** + * Helpers + */ + + const advance = () => input[index++]; + + const push = node => { + if (node.type === 'text' && prev.type === 'dot') { + prev.type = 'text'; + } + + if (prev && prev.type === 'text' && node.type === 'text') { + prev.value += node.value; + return; + } + + block.nodes.push(node); + node.parent = block; + node.prev = prev; + prev = node; + return node; + }; + + push({ + type: 'bos' + }); + + while (index < length) { + block = stack[stack.length - 1]; + value = advance(); + /** + * Invalid chars + */ + + if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) { + continue; + } + /** + * Escaped chars + */ + + + if (value === CHAR_BACKSLASH) { + push({ + type: 'text', + value: (options.keepEscaping ? value : '') + advance() + }); + continue; + } + /** + * Right square bracket (literal): ']' + */ + + + if (value === CHAR_RIGHT_SQUARE_BRACKET) { + push({ + type: 'text', + value: '\\' + value + }); + continue; + } + /** + * Left square bracket: '[' + */ + + + if (value === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + let next; + + while (index < length && (next = advance())) { + value += next; + + if (next === CHAR_LEFT_SQUARE_BRACKET) { + brackets++; + continue; + } + + if (next === CHAR_BACKSLASH) { + value += advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET) { + brackets--; + + if (brackets === 0) { + break; + } + } + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Parentheses + */ + + + if (value === CHAR_LEFT_PARENTHESES) { + block = push({ + type: 'paren', + nodes: [] + }); + stack.push(block); + push({ + type: 'text', + value + }); + continue; + } + + if (value === CHAR_RIGHT_PARENTHESES) { + if (block.type !== 'paren') { + push({ + type: 'text', + value + }); + continue; + } + + block = stack.pop(); + push({ + type: 'text', + value + }); + block = stack[stack.length - 1]; + continue; + } + /** + * Quotes: '|"|` + */ + + + if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) { + let open = value; + let next; + + if (options.keepQuotes !== true) { + value = ''; + } + + while (index < length && (next = advance())) { + if (next === CHAR_BACKSLASH) { + value += next + advance(); + continue; + } + + if (next === open) { + if (options.keepQuotes === true) value += next; + break; + } + + value += next; + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Left curly brace: '{' + */ + + + if (value === CHAR_LEFT_CURLY_BRACE) { + depth++; + let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true; + let brace = { + type: 'brace', + open: true, + close: false, + dollar, + depth, + commas: 0, + ranges: 0, + nodes: [] + }; + block = push(brace); + stack.push(block); + push({ + type: 'open', + value + }); + continue; + } + /** + * Right curly brace: '}' + */ + + + if (value === CHAR_RIGHT_CURLY_BRACE) { + if (block.type !== 'brace') { + push({ + type: 'text', + value + }); + continue; + } + + let type = 'close'; + block = stack.pop(); + block.close = true; + push({ + type, + value + }); + depth--; + block = stack[stack.length - 1]; + continue; + } + /** + * Comma: ',' + */ + + + if (value === CHAR_COMMA$1 && depth > 0) { + if (block.ranges > 0) { + block.ranges = 0; + let open = block.nodes.shift(); + block.nodes = [open, { + type: 'text', + value: stringify$1(block) + }]; + } + + push({ + type: 'comma', + value + }); + block.commas++; + continue; + } + /** + * Dot: '.' + */ + + + if (value === CHAR_DOT && depth > 0 && block.commas === 0) { + let siblings = block.nodes; + + if (depth === 0 || siblings.length === 0) { + push({ + type: 'text', + value + }); + continue; + } + + if (prev.type === 'dot') { + block.range = []; + prev.value += value; + prev.type = 'range'; + + if (block.nodes.length !== 3 && block.nodes.length !== 5) { + block.invalid = true; + block.ranges = 0; + prev.type = 'text'; + continue; + } + + block.ranges++; + block.args = []; + continue; + } + + if (prev.type === 'range') { + siblings.pop(); + let before = siblings[siblings.length - 1]; + before.value += prev.value + value; + prev = before; + block.ranges--; + continue; + } + + push({ + type: 'dot', + value + }); + continue; + } + /** + * Text + */ + + + push({ + type: 'text', + value + }); + } // Mark imbalanced braces and brackets as invalid + + + do { + block = stack.pop(); + + if (block.type !== 'root') { + block.nodes.forEach(node => { + if (!node.nodes) { + if (node.type === 'open') node.isOpen = true; + if (node.type === 'close') node.isClose = true; + if (!node.nodes) node.type = 'text'; + node.invalid = true; + } + }); // get the location of the block on parent.nodes (block's siblings) + + let parent = stack[stack.length - 1]; + let index = parent.nodes.indexOf(block); // replace the (invalid) block with it's nodes + + parent.nodes.splice(index, 1, ...block.nodes); + } + } while (stack.length > 0); + + push({ + type: 'eos' + }); + return ast; +}; + +var parse_1 = parse$5; + +/** + * Expand the given pattern or create a regex-compatible string. + * + * ```js + * const braces = require('braces'); + * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)'] + * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c'] + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {String} + * @api public + */ + + +const braces = (input, options = {}) => { + let output = []; + + if (Array.isArray(input)) { + for (let pattern of input) { + let result = braces.create(pattern, options); + + if (Array.isArray(result)) { + output.push(...result); + } else { + output.push(result); + } + } + } else { + output = [].concat(braces.create(input, options)); + } + + if (options && options.expand === true && options.nodupes === true) { + output = [...new Set(output)]; + } + + return output; +}; +/** + * Parse the given `str` with the given `options`. + * + * ```js + * // braces.parse(pattern, [, options]); + * const ast = braces.parse('a/{b,c}/d'); + * console.log(ast); + * ``` + * @param {String} pattern Brace pattern to parse + * @param {Object} options + * @return {Object} Returns an AST + * @api public + */ + + +braces.parse = (input, options = {}) => parse_1(input, options); +/** + * Creates a braces string from an AST, or an AST node. + * + * ```js + * const braces = require('braces'); + * let ast = braces.parse('foo/{a,b}/bar'); + * console.log(stringify(ast.nodes[2])); //=> '{a,b}' + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + + +braces.stringify = (input, options = {}) => { + if (typeof input === 'string') { + return stringify$1(braces.parse(input, options), options); + } + + return stringify$1(input, options); +}; +/** + * Compiles a brace pattern into a regex-compatible, optimized string. + * This method is called by the main [braces](#braces) function by default. + * + * ```js + * const braces = require('braces'); + * console.log(braces.compile('a/{b,c}/d')); + * //=> ['a/(b|c)/d'] + * ``` + * @param {String} `input` Brace pattern or AST. + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + + +braces.compile = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + return compile_1(input, options); +}; +/** + * Expands a brace pattern into an array. This method is called by the + * main [braces](#braces) function when `options.expand` is true. Before + * using this method it's recommended that you read the [performance notes](#performance)) + * and advantages of using [.compile](#compile) instead. + * + * ```js + * const braces = require('braces'); + * console.log(braces.expand('a/{b,c}/d')); + * //=> ['a/b/d', 'a/c/d']; + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + + +braces.expand = (input, options = {}) => { + if (typeof input === 'string') { + input = braces.parse(input, options); + } + + let result = expand_1(input, options); // filter out empty strings if specified + + if (options.noempty === true) { + result = result.filter(Boolean); + } // filter out duplicates if specified + + + if (options.nodupes === true) { + result = [...new Set(result)]; + } + + return result; +}; +/** + * Processes a brace pattern and returns either an expanded array + * (if `options.expand` is true), a highly optimized regex-compatible string. + * This method is called by the main [braces](#braces) function. + * + * ```js + * const braces = require('braces'); + * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}')) + * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)' + * ``` + * @param {String} `pattern` Brace pattern + * @param {Object} `options` + * @return {Array} Returns an array of expanded values. + * @api public + */ + + +braces.create = (input, options = {}) => { + if (input === '' || input.length < 3) { + return [input]; + } + + return options.expand !== true ? braces.compile(input, options) : braces.expand(input, options); +}; +/** + * Expose "braces" + */ + + +var braces_1 = braces; + +const WIN_SLASH = '\\\\/'; +const WIN_NO_SLASH = `[^${WIN_SLASH}]`; +/** + * Posix glob regex + */ + +const DOT_LITERAL = '\\.'; +const PLUS_LITERAL = '\\+'; +const QMARK_LITERAL = '\\?'; +const SLASH_LITERAL = '\\/'; +const ONE_CHAR = '(?=.)'; +const QMARK = '[^/]'; +const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`; +const START_ANCHOR = `(?:^|${SLASH_LITERAL})`; +const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`; +const NO_DOT = `(?!${DOT_LITERAL})`; +const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`; +const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`; +const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`; +const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`; +const STAR = `${QMARK}*?`; +const POSIX_CHARS = { + DOT_LITERAL, + PLUS_LITERAL, + QMARK_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + QMARK, + END_ANCHOR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK_NO_DOT, + STAR, + START_ANCHOR +}; +/** + * Windows glob regex + */ + +const WINDOWS_CHARS = Object.assign({}, POSIX_CHARS, { + SLASH_LITERAL: `[${WIN_SLASH}]`, + QMARK: WIN_NO_SLASH, + STAR: `${WIN_NO_SLASH}*?`, + DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, + NO_DOT: `(?!${DOT_LITERAL})`, + NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, + NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, + QMARK_NO_DOT: `[^.${WIN_SLASH}]`, + START_ANCHOR: `(?:^|[${WIN_SLASH}])`, + END_ANCHOR: `(?:[${WIN_SLASH}]|$)` +}); +/** + * POSIX Bracket Regex + */ + +const POSIX_REGEX_SOURCE = { + alnum: 'a-zA-Z0-9', + alpha: 'a-zA-Z', + ascii: '\\x00-\\x7F', + blank: ' \\t', + cntrl: '\\x00-\\x1F\\x7F', + digit: '0-9', + graph: '\\x21-\\x7E', + lower: 'a-z', + print: '\\x20-\\x7E ', + punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~', + space: ' \\t\\r\\n\\v\\f', + upper: 'A-Z', + word: 'A-Za-z0-9_', + xdigit: 'A-Fa-f0-9' +}; +var constants$3 = { + MAX_LENGTH: 1024 * 64, + POSIX_REGEX_SOURCE, + // regular expressions + REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g, + REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/, + REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/, + REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g, + REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g, + REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g, + // Replace globs with equivalent patterns to reduce parsing time. + REPLACEMENTS: { + '***': '*', + '**/**': '**', + '**/**/**': '**' + }, + // Digits + CHAR_0: 48, + + /* 0 */ + CHAR_9: 57, + + /* 9 */ + // Alphabet chars. + CHAR_UPPERCASE_A: 65, + + /* A */ + CHAR_LOWERCASE_A: 97, + + /* a */ + CHAR_UPPERCASE_Z: 90, + + /* Z */ + CHAR_LOWERCASE_Z: 122, + + /* z */ + CHAR_LEFT_PARENTHESES: 40, + + /* ( */ + CHAR_RIGHT_PARENTHESES: 41, + + /* ) */ + CHAR_ASTERISK: 42, + + /* * */ + // Non-alphabetic chars. + CHAR_AMPERSAND: 38, + + /* & */ + CHAR_AT: 64, + + /* @ */ + CHAR_BACKWARD_SLASH: 92, + + /* \ */ + CHAR_CARRIAGE_RETURN: 13, + + /* \r */ + CHAR_CIRCUMFLEX_ACCENT: 94, + + /* ^ */ + CHAR_COLON: 58, + + /* : */ + CHAR_COMMA: 44, + + /* , */ + CHAR_DOT: 46, + + /* . */ + CHAR_DOUBLE_QUOTE: 34, + + /* " */ + CHAR_EQUAL: 61, + + /* = */ + CHAR_EXCLAMATION_MARK: 33, + + /* ! */ + CHAR_FORM_FEED: 12, + + /* \f */ + CHAR_FORWARD_SLASH: 47, + + /* / */ + CHAR_GRAVE_ACCENT: 96, + + /* ` */ + CHAR_HASH: 35, + + /* # */ + CHAR_HYPHEN_MINUS: 45, + + /* - */ + CHAR_LEFT_ANGLE_BRACKET: 60, + + /* < */ + CHAR_LEFT_CURLY_BRACE: 123, + + /* { */ + CHAR_LEFT_SQUARE_BRACKET: 91, + + /* [ */ + CHAR_LINE_FEED: 10, + + /* \n */ + CHAR_NO_BREAK_SPACE: 160, + + /* \u00A0 */ + CHAR_PERCENT: 37, + + /* % */ + CHAR_PLUS: 43, + + /* + */ + CHAR_QUESTION_MARK: 63, + + /* ? */ + CHAR_RIGHT_ANGLE_BRACKET: 62, + + /* > */ + CHAR_RIGHT_CURLY_BRACE: 125, + + /* } */ + CHAR_RIGHT_SQUARE_BRACKET: 93, + + /* ] */ + CHAR_SEMICOLON: 59, + + /* ; */ + CHAR_SINGLE_QUOTE: 39, + + /* ' */ + CHAR_SPACE: 32, + + /* */ + CHAR_TAB: 9, + + /* \t */ + CHAR_UNDERSCORE: 95, + + /* _ */ + CHAR_VERTICAL_LINE: 124, + + /* | */ + CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, + + /* \uFEFF */ + SEP: path__default['default'].sep, + + /** + * Create EXTGLOB_CHARS + */ + extglobChars(chars) { + return { + '!': { + type: 'negate', + open: '(?:(?!(?:', + close: `))${chars.STAR})` + }, + '?': { + type: 'qmark', + open: '(?:', + close: ')?' + }, + '+': { + type: 'plus', + open: '(?:', + close: ')+' + }, + '*': { + type: 'star', + open: '(?:', + close: ')*' + }, + '@': { + type: 'at', + open: '(?:', + close: ')' + } + }; + }, + + /** + * Create GLOB_CHARS + */ + globChars(win32) { + return win32 === true ? WINDOWS_CHARS : POSIX_CHARS; + } + +}; + +var utils$2 = createCommonjsModule(function (module, exports) { + + const win32 = process.platform === 'win32'; + const { + REGEX_BACKSLASH, + REGEX_REMOVE_BACKSLASH, + REGEX_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_GLOBAL + } = constants$3; + + exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val); + + exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str); + + exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str); + + exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1'); + + exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/'); + + exports.removeBackslashes = str => { + return str.replace(REGEX_REMOVE_BACKSLASH, match => { + return match === '\\' ? '' : match; + }); + }; + + exports.supportsLookbehinds = () => { + const segs = process.version.slice(1).split('.').map(Number); + + if (segs.length === 3 && segs[0] >= 9 || segs[0] === 8 && segs[1] >= 10) { + return true; + } + + return false; + }; + + exports.isWindows = options => { + if (options && typeof options.windows === 'boolean') { + return options.windows; + } + + return win32 === true || path__default['default'].sep === '\\'; + }; + + exports.escapeLast = (input, char, lastIdx) => { + const idx = input.lastIndexOf(char, lastIdx); + if (idx === -1) return input; + if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1); + return `${input.slice(0, idx)}\\${input.slice(idx)}`; + }; + + exports.removePrefix = (input, state = {}) => { + let output = input; + + if (output.startsWith('./')) { + output = output.slice(2); + state.prefix = './'; + } + + return output; + }; + + exports.wrapOutput = (input, state = {}, options = {}) => { + const prepend = options.contains ? '' : '^'; + const append = options.contains ? '' : '$'; + let output = `${prepend}(?:${input})${append}`; + + if (state.negated === true) { + output = `(?:^(?!${output}).*$)`; + } + + return output; + }; +}); + +const { + CHAR_ASTERISK, + + /* * */ + CHAR_AT, + + /* @ */ + CHAR_BACKWARD_SLASH, + + /* \ */ + CHAR_COMMA: CHAR_COMMA$2, + + /* , */ + CHAR_DOT: CHAR_DOT$1, + + /* . */ + CHAR_EXCLAMATION_MARK, + + /* ! */ + CHAR_FORWARD_SLASH, + + /* / */ + CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, + + /* { */ + CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, + + /* ( */ + CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, + + /* [ */ + CHAR_PLUS: CHAR_PLUS$1, + + /* + */ + CHAR_QUESTION_MARK, + + /* ? */ + CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, + + /* } */ + CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, + + /* ) */ + CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 + /* ] */ + +} = constants$3; + +const isPathSeparator = code => { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +}; + +const depth = token => { + if (token.isPrefix !== true) { + token.depth = token.isGlobstar ? Infinity : 1; + } +}; +/** + * Quickly scans a glob pattern and returns an object with a handful of + * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists), + * `glob` (the actual pattern), and `negated` (true if the path starts with `!`). + * + * ```js + * const pm = require('picomatch'); + * console.log(pm.scan('foo/bar/*.js')); + * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' } + * ``` + * @param {String} `str` + * @param {Object} `options` + * @return {Object} Returns an object with tokens and regex source string. + * @api public + */ + + +const scan = (input, options) => { + const opts = options || {}; + const length = input.length - 1; + const scanToEnd = opts.parts === true || opts.scanToEnd === true; + const slashes = []; + const tokens = []; + const parts = []; + let str = input; + let index = -1; + let start = 0; + let lastIndex = 0; + let isBrace = false; + let isBracket = false; + let isGlob = false; + let isExtglob = false; + let isGlobstar = false; + let braceEscaped = false; + let backslashes = false; + let negated = false; + let finished = false; + let braces = 0; + let prev; + let code; + let token = { + value: '', + depth: 0, + isGlob: false + }; + + const eos = () => index >= length; + + const peek = () => str.charCodeAt(index + 1); + + const advance = () => { + prev = code; + return str.charCodeAt(++index); + }; + + while (index < length) { + code = advance(); + let next; + + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + + if (code === CHAR_LEFT_CURLY_BRACE$1) { + braceEscaped = true; + } + + continue; + } + + if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) { + braces++; + + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (code === CHAR_LEFT_CURLY_BRACE$1) { + braces++; + continue; + } + + if (braceEscaped !== true && code === CHAR_DOT$1 && (code = advance()) === CHAR_DOT$1) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (braceEscaped !== true && code === CHAR_COMMA$2) { + isBrace = token.isBrace = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_RIGHT_CURLY_BRACE$1) { + braces--; + + if (braces === 0) { + braceEscaped = false; + isBrace = token.isBrace = true; + finished = true; + break; + } + } + } + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_FORWARD_SLASH) { + slashes.push(index); + tokens.push(token); + token = { + value: '', + depth: 0, + isGlob: false + }; + if (finished === true) continue; + + if (prev === CHAR_DOT$1 && index === start + 1) { + start += 2; + continue; + } + + lastIndex = index + 1; + continue; + } + + if (opts.noext !== true) { + const isExtglobChar = code === CHAR_PLUS$1 || code === CHAR_AT || code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK || code === CHAR_EXCLAMATION_MARK; + + if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES$1) { + isGlob = token.isGlob = true; + isExtglob = token.isExtglob = true; + finished = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES$1) { + isGlob = token.isGlob = true; + finished = true; + break; + } + } + + continue; + } + + break; + } + } + + if (code === CHAR_ASTERISK) { + if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_QUESTION_MARK) { + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + + if (code === CHAR_LEFT_SQUARE_BRACKET$1) { + while (eos() !== true && (next = advance())) { + if (next === CHAR_BACKWARD_SLASH) { + backslashes = token.backslashes = true; + advance(); + continue; + } + + if (next === CHAR_RIGHT_SQUARE_BRACKET$1) { + isBracket = token.isBracket = true; + isGlob = token.isGlob = true; + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + } + + if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) { + negated = token.negated = true; + start++; + continue; + } + + if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES$1) { + isGlob = token.isGlob = true; + + if (scanToEnd === true) { + while (eos() !== true && (code = advance())) { + if (code === CHAR_LEFT_PARENTHESES$1) { + backslashes = token.backslashes = true; + code = advance(); + continue; + } + + if (code === CHAR_RIGHT_PARENTHESES$1) { + finished = true; + break; + } + } + + continue; + } + + break; + } + + if (isGlob === true) { + finished = true; + + if (scanToEnd === true) { + continue; + } + + break; + } + } + + if (opts.noext === true) { + isExtglob = false; + isGlob = false; + } + + let base = str; + let prefix = ''; + let glob = ''; + + if (start > 0) { + prefix = str.slice(0, start); + str = str.slice(start); + lastIndex -= start; + } + + if (base && isGlob === true && lastIndex > 0) { + base = str.slice(0, lastIndex); + glob = str.slice(lastIndex); + } else if (isGlob === true) { + base = ''; + glob = str; + } else { + base = str; + } + + if (base && base !== '' && base !== '/' && base !== str) { + if (isPathSeparator(base.charCodeAt(base.length - 1))) { + base = base.slice(0, -1); + } + } + + if (opts.unescape === true) { + if (glob) glob = utils$2.removeBackslashes(glob); + + if (base && backslashes === true) { + base = utils$2.removeBackslashes(base); + } + } + + const state = { + prefix, + input, + start, + base, + glob, + isBrace, + isBracket, + isGlob, + isExtglob, + isGlobstar, + negated + }; + + if (opts.tokens === true) { + state.maxDepth = 0; + + if (!isPathSeparator(code)) { + tokens.push(token); + } + + state.tokens = tokens; + } + + if (opts.parts === true || opts.tokens === true) { + let prevIndex; + + for (let idx = 0; idx < slashes.length; idx++) { + const n = prevIndex ? prevIndex + 1 : start; + const i = slashes[idx]; + const value = input.slice(n, i); + + if (opts.tokens) { + if (idx === 0 && start !== 0) { + tokens[idx].isPrefix = true; + tokens[idx].value = prefix; + } else { + tokens[idx].value = value; + } + + depth(tokens[idx]); + state.maxDepth += tokens[idx].depth; + } + + if (idx !== 0 || value !== '') { + parts.push(value); + } + + prevIndex = i; + } + + if (prevIndex && prevIndex + 1 < input.length) { + const value = input.slice(prevIndex + 1); + parts.push(value); + + if (opts.tokens) { + tokens[tokens.length - 1].value = value; + depth(tokens[tokens.length - 1]); + state.maxDepth += tokens[tokens.length - 1].depth; + } + } + + state.slashes = slashes; + state.parts = parts; + } + + return state; +}; + +var scan_1 = scan; + +/** + * Constants + */ + + +const { + MAX_LENGTH: MAX_LENGTH$3, + POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, + REGEX_NON_SPECIAL_CHARS, + REGEX_SPECIAL_CHARS_BACKREF, + REPLACEMENTS +} = constants$3; +/** + * Helpers + */ + +const expandRange = (args, options) => { + if (typeof options.expandRange === 'function') { + return options.expandRange(...args, options); + } + + args.sort(); + const value = `[${args.join('-')}]`; + + try { + /* eslint-disable-next-line no-new */ + new RegExp(value); + } catch (ex) { + return args.map(v => utils$2.escapeRegex(v)).join('..'); + } + + return value; +}; +/** + * Create the message for a syntax error + */ + + +const syntaxError$1 = (type, char) => { + return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`; +}; +/** + * Parse the given input string. + * @param {String} input + * @param {Object} options + * @return {Object} + */ + + +const parse$6 = (input, options) => { + if (typeof input !== 'string') { + throw new TypeError('Expected a string'); + } + + input = REPLACEMENTS[input] || input; + const opts = Object.assign({}, options); + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3; + let len = input.length; + + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + const bos = { + type: 'bos', + value: '', + output: opts.prepend || '' + }; + const tokens = [bos]; + const capture = opts.capture ? '' : '?:'; + const win32 = utils$2.isWindows(options); // create constants based on platform, for windows or posix + + const PLATFORM_CHARS = constants$3.globChars(win32); + const EXTGLOB_CHARS = constants$3.extglobChars(PLATFORM_CHARS); + const { + DOT_LITERAL, + PLUS_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOT_SLASH, + NO_DOTS_SLASH, + QMARK, + QMARK_NO_DOT, + STAR, + START_ANCHOR + } = PLATFORM_CHARS; + + const globstar = opts => { + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const nodot = opts.dot ? '' : NO_DOT; + const qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT; + let star = opts.bash === true ? globstar(opts) : STAR; + + if (opts.capture) { + star = `(${star})`; + } // minimatch options support + + + if (typeof opts.noext === 'boolean') { + opts.noextglob = opts.noext; + } + + const state = { + input, + index: -1, + start: 0, + dot: opts.dot === true, + consumed: '', + output: '', + prefix: '', + backtrack: false, + negated: false, + brackets: 0, + braces: 0, + parens: 0, + quotes: 0, + globstar: false, + tokens + }; + input = utils$2.removePrefix(input, state); + len = input.length; + const extglobs = []; + const braces = []; + const stack = []; + let prev = bos; + let value; + /** + * Tokenizing helpers + */ + + const eos = () => state.index === len - 1; + + const peek = state.peek = (n = 1) => input[state.index + n]; + + const advance = state.advance = () => input[++state.index]; + + const remaining = () => input.slice(state.index + 1); + + const consume = (value = '', num = 0) => { + state.consumed += value; + state.index += num; + }; + + const append = token => { + state.output += token.output != null ? token.output : token.value; + consume(token.value); + }; + + const negate = () => { + let count = 1; + + while (peek() === '!' && (peek(2) !== '(' || peek(3) === '?')) { + advance(); + state.start++; + count++; + } + + if (count % 2 === 0) { + return false; + } + + state.negated = true; + state.start++; + return true; + }; + + const increment = type => { + state[type]++; + stack.push(type); + }; + + const decrement = type => { + state[type]--; + stack.pop(); + }; + /** + * Push tokens onto the tokens array. This helper speeds up + * tokenizing by 1) helping us avoid backtracking as much as possible, + * and 2) helping us avoid creating extra tokens when consecutive + * characters are plain text. This improves performance and simplifies + * lookbehinds. + */ + + + const push = tok => { + if (prev.type === 'globstar') { + const isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace'); + const isExtglob = tok.extglob === true || extglobs.length && (tok.type === 'pipe' || tok.type === 'paren'); + + if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) { + state.output = state.output.slice(0, -prev.output.length); + prev.type = 'star'; + prev.value = '*'; + prev.output = star; + state.output += prev.output; + } + } + + if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) { + extglobs[extglobs.length - 1].inner += tok.value; + } + + if (tok.value || tok.output) append(tok); + + if (prev && prev.type === 'text' && tok.type === 'text') { + prev.value += tok.value; + prev.output = (prev.output || '') + tok.value; + return; + } + + tok.prev = prev; + tokens.push(tok); + prev = tok; + }; + + const extglobOpen = (type, value) => { + const token = Object.assign({}, EXTGLOB_CHARS[value], { + conditions: 1, + inner: '' + }); + token.prev = prev; + token.parens = state.parens; + token.output = state.output; + const output = (opts.capture ? '(' : '') + token.open; + increment('parens'); + push({ + type, + value, + output: state.output ? '' : ONE_CHAR + }); + push({ + type: 'paren', + extglob: true, + value: advance(), + output + }); + extglobs.push(token); + }; + + const extglobClose = token => { + let output = token.close + (opts.capture ? ')' : ''); + + if (token.type === 'negate') { + let extglobStar = star; + + if (token.inner && token.inner.length > 1 && token.inner.includes('/')) { + extglobStar = globstar(opts); + } + + if (extglobStar !== star || eos() || /^\)+$/.test(remaining())) { + output = token.close = `)$))${extglobStar}`; + } + + if (token.prev.type === 'bos' && eos()) { + state.negatedExtglob = true; + } + } + + push({ + type: 'paren', + extglob: true, + value, + output + }); + decrement('parens'); + }; + /** + * Fast paths + */ + + + if (opts.fastpaths !== false && !/(^[*!]|[/()[\]{}"])/.test(input)) { + let backslashes = false; + let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => { + if (first === '\\') { + backslashes = true; + return m; + } + + if (first === '?') { + if (esc) { + return esc + first + (rest ? QMARK.repeat(rest.length) : ''); + } + + if (index === 0) { + return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : ''); + } + + return QMARK.repeat(chars.length); + } + + if (first === '.') { + return DOT_LITERAL.repeat(chars.length); + } + + if (first === '*') { + if (esc) { + return esc + first + (rest ? star : ''); + } + + return star; + } + + return esc ? m : `\\${m}`; + }); + + if (backslashes === true) { + if (opts.unescape === true) { + output = output.replace(/\\/g, ''); + } else { + output = output.replace(/\\+/g, m => { + return m.length % 2 === 0 ? '\\\\' : m ? '\\' : ''; + }); + } + } + + if (output === input && opts.contains === true) { + state.output = input; + return state; + } + + state.output = utils$2.wrapOutput(output, state, options); + return state; + } + /** + * Tokenize input until we reach end-of-string + */ + + + while (!eos()) { + value = advance(); + + if (value === '\u0000') { + continue; + } + /** + * Escaped characters + */ + + + if (value === '\\') { + const next = peek(); + + if (next === '/' && opts.bash !== true) { + continue; + } + + if (next === '.' || next === ';') { + continue; + } + + if (!next) { + value += '\\'; + push({ + type: 'text', + value + }); + continue; + } // collapse slashes to reduce potential for exploits + + + const match = /^\\+/.exec(remaining()); + let slashes = 0; + + if (match && match[0].length > 2) { + slashes = match[0].length; + state.index += slashes; + + if (slashes % 2 !== 0) { + value += '\\'; + } + } + + if (opts.unescape === true) { + value = advance() || ''; + } else { + value += advance() || ''; + } + + if (state.brackets === 0) { + push({ + type: 'text', + value + }); + continue; + } + } + /** + * If we're inside a regex character class, continue + * until we reach the closing bracket. + */ + + + if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) { + if (opts.posix !== false && value === ':') { + const inner = prev.value.slice(1); + + if (inner.includes('[')) { + prev.posix = true; + + if (inner.includes(':')) { + const idx = prev.value.lastIndexOf('['); + const pre = prev.value.slice(0, idx); + const rest = prev.value.slice(idx + 2); + const posix = POSIX_REGEX_SOURCE$1[rest]; + + if (posix) { + prev.value = pre + posix; + state.backtrack = true; + advance(); + + if (!bos.output && tokens.indexOf(prev) === 1) { + bos.output = ONE_CHAR; + } + + continue; + } + } + } + } + + if (value === '[' && peek() !== ':' || value === '-' && peek() === ']') { + value = `\\${value}`; + } + + if (value === ']' && (prev.value === '[' || prev.value === '[^')) { + value = `\\${value}`; + } + + if (opts.posix === true && value === '!' && prev.value === '[') { + value = '^'; + } + + prev.value += value; + append({ + value + }); + continue; + } + /** + * If we're inside a quoted string, continue + * until we reach the closing double quote. + */ + + + if (state.quotes === 1 && value !== '"') { + value = utils$2.escapeRegex(value); + prev.value += value; + append({ + value + }); + continue; + } + /** + * Double quotes + */ + + + if (value === '"') { + state.quotes = state.quotes === 1 ? 0 : 1; + + if (opts.keepQuotes === true) { + push({ + type: 'text', + value + }); + } + + continue; + } + /** + * Parentheses + */ + + + if (value === '(') { + increment('parens'); + push({ + type: 'paren', + value + }); + continue; + } + + if (value === ')') { + if (state.parens === 0 && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError$1('opening', '(')); + } + + const extglob = extglobs[extglobs.length - 1]; + + if (extglob && state.parens === extglob.parens + 1) { + extglobClose(extglobs.pop()); + continue; + } + + push({ + type: 'paren', + value, + output: state.parens ? ')' : '\\)' + }); + decrement('parens'); + continue; + } + /** + * Square brackets + */ + + + if (value === '[') { + if (opts.nobracket === true || !remaining().includes(']')) { + if (opts.nobracket !== true && opts.strictBrackets === true) { + throw new SyntaxError(syntaxError$1('closing', ']')); + } + + value = `\\${value}`; + } else { + increment('brackets'); + } + + push({ + type: 'bracket', + value + }); + continue; + } + + if (value === ']') { + if (opts.nobracket === true || prev && prev.type === 'bracket' && prev.value.length === 1) { + push({ + type: 'text', + value, + output: `\\${value}` + }); + continue; + } + + if (state.brackets === 0) { + if (opts.strictBrackets === true) { + throw new SyntaxError(syntaxError$1('opening', '[')); + } + + push({ + type: 'text', + value, + output: `\\${value}` + }); + continue; + } + + decrement('brackets'); + const prevValue = prev.value.slice(1); + + if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) { + value = `/${value}`; + } + + prev.value += value; + append({ + value + }); // when literal brackets are explicitly disabled + // assume we should match with a regex character class + + if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) { + continue; + } + + const escaped = utils$2.escapeRegex(prev.value); + state.output = state.output.slice(0, -prev.value.length); // when literal brackets are explicitly enabled + // assume we should escape the brackets to match literal characters + + if (opts.literalBrackets === true) { + state.output += escaped; + prev.value = escaped; + continue; + } // when the user specifies nothing, try to match both + + + prev.value = `(${capture}${escaped}|${prev.value})`; + state.output += prev.value; + continue; + } + /** + * Braces + */ + + + if (value === '{' && opts.nobrace !== true) { + increment('braces'); + const open = { + type: 'brace', + value, + output: '(', + outputIndex: state.output.length, + tokensIndex: state.tokens.length + }; + braces.push(open); + push(open); + continue; + } + + if (value === '}') { + const brace = braces[braces.length - 1]; + + if (opts.nobrace === true || !brace) { + push({ + type: 'text', + value, + output: value + }); + continue; + } + + let output = ')'; + + if (brace.dots === true) { + const arr = tokens.slice(); + const range = []; + + for (let i = arr.length - 1; i >= 0; i--) { + tokens.pop(); + + if (arr[i].type === 'brace') { + break; + } + + if (arr[i].type !== 'dots') { + range.unshift(arr[i].value); + } + } + + output = expandRange(range, opts); + state.backtrack = true; + } + + if (brace.comma !== true && brace.dots !== true) { + const out = state.output.slice(0, brace.outputIndex); + const toks = state.tokens.slice(brace.tokensIndex); + brace.value = brace.output = '\\{'; + value = output = '\\}'; + state.output = out; + + for (const t of toks) { + state.output += t.output || t.value; + } + } + + push({ + type: 'brace', + value, + output + }); + decrement('braces'); + braces.pop(); + continue; + } + /** + * Pipes + */ + + + if (value === '|') { + if (extglobs.length > 0) { + extglobs[extglobs.length - 1].conditions++; + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Commas + */ + + + if (value === ',') { + let output = value; + const brace = braces[braces.length - 1]; + + if (brace && stack[stack.length - 1] === 'braces') { + brace.comma = true; + output = '|'; + } + + push({ + type: 'comma', + value, + output + }); + continue; + } + /** + * Slashes + */ + + + if (value === '/') { + // if the beginning of the glob is "./", advance the start + // to the current index, and don't add the "./" characters + // to the state. This greatly simplifies lookbehinds when + // checking for BOS characters like "!" and "." (not "./") + if (prev.type === 'dot' && state.index === state.start + 1) { + state.start = state.index + 1; + state.consumed = ''; + state.output = ''; + tokens.pop(); + prev = bos; // reset "prev" to the first token + + continue; + } + + push({ + type: 'slash', + value, + output: SLASH_LITERAL + }); + continue; + } + /** + * Dots + */ + + + if (value === '.') { + if (state.braces > 0 && prev.type === 'dot') { + if (prev.value === '.') prev.output = DOT_LITERAL; + const brace = braces[braces.length - 1]; + prev.type = 'dots'; + prev.output += value; + prev.value += value; + brace.dots = true; + continue; + } + + if (state.braces + state.parens === 0 && prev.type !== 'bos' && prev.type !== 'slash') { + push({ + type: 'text', + value, + output: DOT_LITERAL + }); + continue; + } + + push({ + type: 'dot', + value, + output: DOT_LITERAL + }); + continue; + } + /** + * Question marks + */ + + + if (value === '?') { + const isGroup = prev && prev.value === '('; + + if (!isGroup && opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('qmark', value); + continue; + } + + if (prev && prev.type === 'paren') { + const next = peek(); + let output = value; + + if (next === '<' && !utils$2.supportsLookbehinds()) { + throw new Error('Node.js v10 or higher is required for regex lookbehinds'); + } + + if (prev.value === '(' && !/[!=<:]/.test(next) || next === '<' && !/<([!=]|\w+>)/.test(remaining())) { + output = `\\${value}`; + } + + push({ + type: 'text', + value, + output + }); + continue; + } + + if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) { + push({ + type: 'qmark', + value, + output: QMARK_NO_DOT + }); + continue; + } + + push({ + type: 'qmark', + value, + output: QMARK + }); + continue; + } + /** + * Exclamation + */ + + + if (value === '!') { + if (opts.noextglob !== true && peek() === '(') { + if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) { + extglobOpen('negate', value); + continue; + } + } + + if (opts.nonegate !== true && state.index === 0) { + negate(); + continue; + } + } + /** + * Plus + */ + + + if (value === '+') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + extglobOpen('plus', value); + continue; + } + + if (prev && prev.value === '(' || opts.regex === false) { + push({ + type: 'plus', + value, + output: PLUS_LITERAL + }); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace') || state.parens > 0) { + push({ + type: 'plus', + value + }); + continue; + } + + push({ + type: 'plus', + value: PLUS_LITERAL + }); + continue; + } + /** + * Plain text + */ + + + if (value === '@') { + if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') { + push({ + type: 'at', + extglob: true, + value, + output: '' + }); + continue; + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Plain text + */ + + + if (value !== '*') { + if (value === '$' || value === '^') { + value = `\\${value}`; + } + + const match = REGEX_NON_SPECIAL_CHARS.exec(remaining()); + + if (match) { + value += match[0]; + state.index += match[0].length; + } + + push({ + type: 'text', + value + }); + continue; + } + /** + * Stars + */ + + + if (prev && (prev.type === 'globstar' || prev.star === true)) { + prev.type = 'star'; + prev.star = true; + prev.value += value; + prev.output = star; + state.backtrack = true; + state.globstar = true; + consume(value); + continue; + } + + let rest = remaining(); + + if (opts.noextglob !== true && /^\([^?]/.test(rest)) { + extglobOpen('star', value); + continue; + } + + if (prev.type === 'star') { + if (opts.noglobstar === true) { + consume(value); + continue; + } + + const prior = prev.prev; + const before = prior.prev; + const isStart = prior.type === 'slash' || prior.type === 'bos'; + const afterStar = before && (before.type === 'star' || before.type === 'globstar'); + + if (opts.bash === true && (!isStart || rest[0] && rest[0] !== '/')) { + push({ + type: 'star', + value, + output: '' + }); + continue; + } + + const isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace'); + const isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren'); + + if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) { + push({ + type: 'star', + value, + output: '' + }); + continue; + } // strip consecutive `/**/` + + + while (rest.slice(0, 3) === '/**') { + const after = input[state.index + 4]; + + if (after && after !== '/') { + break; + } + + rest = rest.slice(3); + consume('/**', 3); + } + + if (prior.type === 'bos' && eos()) { + prev.type = 'globstar'; + prev.value += value; + prev.output = globstar(opts); + state.output = prev.output; + state.globstar = true; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) { + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = 'globstar'; + prev.output = globstar(opts) + (opts.strictSlashes ? ')' : '|$)'); + prev.value += value; + state.globstar = true; + state.output += prior.output + prev.output; + consume(value); + continue; + } + + if (prior.type === 'slash' && prior.prev.type !== 'bos' && rest[0] === '/') { + const end = rest[1] !== void 0 ? '|$' : ''; + state.output = state.output.slice(0, -(prior.output + prev.output).length); + prior.output = `(?:${prior.output}`; + prev.type = 'globstar'; + prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`; + prev.value += value; + state.output += prior.output + prev.output; + state.globstar = true; + consume(value + advance()); + push({ + type: 'slash', + value: '/', + output: '' + }); + continue; + } + + if (prior.type === 'bos' && rest[0] === '/') { + prev.type = 'globstar'; + prev.value += value; + prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`; + state.output = prev.output; + state.globstar = true; + consume(value + advance()); + push({ + type: 'slash', + value: '/', + output: '' + }); + continue; + } // remove single star from output + + + state.output = state.output.slice(0, -prev.output.length); // reset previous token to globstar + + prev.type = 'globstar'; + prev.output = globstar(opts); + prev.value += value; // reset output with globstar + + state.output += prev.output; + state.globstar = true; + consume(value); + continue; + } + + const token = { + type: 'star', + value, + output: star + }; + + if (opts.bash === true) { + token.output = '.*?'; + + if (prev.type === 'bos' || prev.type === 'slash') { + token.output = nodot + token.output; + } + + push(token); + continue; + } + + if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) { + token.output = value; + push(token); + continue; + } + + if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') { + if (prev.type === 'dot') { + state.output += NO_DOT_SLASH; + prev.output += NO_DOT_SLASH; + } else if (opts.dot === true) { + state.output += NO_DOTS_SLASH; + prev.output += NO_DOTS_SLASH; + } else { + state.output += nodot; + prev.output += nodot; + } + + if (peek() !== '*') { + state.output += ONE_CHAR; + prev.output += ONE_CHAR; + } + } + + push(token); + } + + while (state.brackets > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ']')); + state.output = utils$2.escapeLast(state.output, '['); + decrement('brackets'); + } + + while (state.parens > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', ')')); + state.output = utils$2.escapeLast(state.output, '('); + decrement('parens'); + } + + while (state.braces > 0) { + if (opts.strictBrackets === true) throw new SyntaxError(syntaxError$1('closing', '}')); + state.output = utils$2.escapeLast(state.output, '{'); + decrement('braces'); + } + + if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) { + push({ + type: 'maybe_slash', + value: '', + output: `${SLASH_LITERAL}?` + }); + } // rebuild the output if we had to backtrack at any point + + + if (state.backtrack === true) { + state.output = ''; + + for (const token of state.tokens) { + state.output += token.output != null ? token.output : token.value; + + if (token.suffix) { + state.output += token.suffix; + } + } + } + + return state; +}; +/** + * Fast paths for creating regular expressions for common glob patterns. + * This can significantly speed up processing and has very little downside + * impact when none of the fast paths match. + */ + + +parse$6.fastpaths = (input, options) => { + const opts = Object.assign({}, options); + const max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$3, opts.maxLength) : MAX_LENGTH$3; + const len = input.length; + + if (len > max) { + throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`); + } + + input = REPLACEMENTS[input] || input; + const win32 = utils$2.isWindows(options); // create constants based on platform, for windows or posix + + const { + DOT_LITERAL, + SLASH_LITERAL, + ONE_CHAR, + DOTS_SLASH, + NO_DOT, + NO_DOTS, + NO_DOTS_SLASH, + STAR, + START_ANCHOR + } = constants$3.globChars(win32); + const nodot = opts.dot ? NO_DOTS : NO_DOT; + const slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT; + const capture = opts.capture ? '' : '?:'; + const state = { + negated: false, + prefix: '' + }; + let star = opts.bash === true ? '.*?' : STAR; + + if (opts.capture) { + star = `(${star})`; + } + + const globstar = opts => { + if (opts.noglobstar === true) return star; + return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`; + }; + + const create = str => { + switch (str) { + case '*': + return `${nodot}${ONE_CHAR}${star}`; + + case '.*': + return `${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*.*': + return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '*/*': + return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`; + + case '**': + return nodot + globstar(opts); + + case '**/*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`; + + case '**/*.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`; + + case '**/.*': + return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`; + + default: + { + const match = /^(.*?)\.(\w+)$/.exec(str); + if (!match) return; + const source = create(match[1]); + if (!source) return; + return source + DOT_LITERAL + match[2]; + } + } + }; + + const output = utils$2.removePrefix(input, state); + let source = create(output); + + if (source && opts.strictSlashes !== true) { + source += `${SLASH_LITERAL}?`; + } + + return source; +}; + +var parse_1$1 = parse$6; + +const isObject$2 = val => val && typeof val === 'object' && !Array.isArray(val); +/** + * Creates a matcher function from one or more glob patterns. The + * returned function takes a string to match as its first argument, + * and returns true if the string is a match. The returned matcher + * function also takes a boolean as the second argument that, when true, + * returns an object with additional information. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch(glob[, options]); + * + * const isMatch = picomatch('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @name picomatch + * @param {String|Array} `globs` One or more glob patterns. + * @param {Object=} `options` + * @return {Function=} Returns a matcher function. + * @api public + */ + + +const picomatch = (glob, options, returnState = false) => { + if (Array.isArray(glob)) { + const fns = glob.map(input => picomatch(input, options, returnState)); + + const arrayMatcher = str => { + for (const isMatch of fns) { + const state = isMatch(str); + if (state) return state; + } + + return false; + }; + + return arrayMatcher; + } + + const isState = isObject$2(glob) && glob.tokens && glob.input; + + if (glob === '' || typeof glob !== 'string' && !isState) { + throw new TypeError('Expected pattern to be a non-empty string'); + } + + const opts = options || {}; + const posix = utils$2.isWindows(options); + const regex = isState ? picomatch.compileRe(glob, options) : picomatch.makeRe(glob, options, false, true); + const state = regex.state; + delete regex.state; + + let isIgnored = () => false; + + if (opts.ignore) { + const ignoreOpts = Object.assign({}, options, { + ignore: null, + onMatch: null, + onResult: null + }); + isIgnored = picomatch(opts.ignore, ignoreOpts, returnState); + } + + const matcher = (input, returnObject = false) => { + const { + isMatch, + match, + output + } = picomatch.test(input, regex, options, { + glob, + posix + }); + const result = { + glob, + state, + regex, + posix, + input, + output, + match, + isMatch + }; + + if (typeof opts.onResult === 'function') { + opts.onResult(result); + } + + if (isMatch === false) { + result.isMatch = false; + return returnObject ? result : false; + } + + if (isIgnored(input)) { + if (typeof opts.onIgnore === 'function') { + opts.onIgnore(result); + } + + result.isMatch = false; + return returnObject ? result : false; + } + + if (typeof opts.onMatch === 'function') { + opts.onMatch(result); + } + + return returnObject ? result : true; + }; + + if (returnState) { + matcher.state = state; + } + + return matcher; +}; +/** + * Test `input` with the given `regex`. This is used by the main + * `picomatch()` function to test the input string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.test(input, regex[, options]); + * + * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/)); + * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' } + * ``` + * @param {String} `input` String to test. + * @param {RegExp} `regex` + * @return {Object} Returns an object with matching info. + * @api public + */ + + +picomatch.test = (input, regex, options, { + glob, + posix +} = {}) => { + if (typeof input !== 'string') { + throw new TypeError('Expected input to be a string'); + } + + if (input === '') { + return { + isMatch: false, + output: '' + }; + } + + const opts = options || {}; + const format = opts.format || (posix ? utils$2.toPosixSlashes : null); + let match = input === glob; + let output = match && format ? format(input) : input; + + if (match === false) { + output = format ? format(input) : input; + match = output === glob; + } + + if (match === false || opts.capture === true) { + if (opts.matchBase === true || opts.basename === true) { + match = picomatch.matchBase(input, regex, options, posix); + } else { + match = regex.exec(output); + } + } + + return { + isMatch: Boolean(match), + match, + output + }; +}; +/** + * Match the basename of a filepath. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.matchBase(input, glob[, options]); + * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true + * ``` + * @param {String} `input` String to test. + * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe). + * @return {Boolean} + * @api public + */ + + +picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => { + const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options); + return regex.test(path__default['default'].basename(input)); +}; +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.isMatch(string, patterns[, options]); + * + * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String|Array} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str); +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const picomatch = require('picomatch'); + * const result = picomatch.parse(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as a regex source string. + * @api public + */ + + +picomatch.parse = (pattern, options) => { + if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options)); + return parse_1$1(pattern, Object.assign({}, options, { + fastpaths: false + })); +}; +/** + * Scan a glob pattern to separate the pattern into segments. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.scan(input[, options]); + * + * const result = picomatch.scan('!./foo/*.js'); + * console.log(result); + * { prefix: '!./', + * input: '!./foo/*.js', + * start: 3, + * base: 'foo', + * glob: '*.js', + * isBrace: false, + * isBracket: false, + * isGlob: true, + * isExtglob: false, + * isGlobstar: false, + * negated: true } + * ``` + * @param {String} `input` Glob pattern to scan. + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + + +picomatch.scan = (input, options) => scan_1(input, options); +/** + * Create a regular expression from a parsed glob pattern. + * + * ```js + * const picomatch = require('picomatch'); + * const state = picomatch.parse('*.js'); + * // picomatch.compileRe(state[, options]); + * + * console.log(picomatch.compileRe(state)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `state` The object returned from the `.parse` method. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + + +picomatch.compileRe = (parsed, options, returnOutput = false, returnState = false) => { + if (returnOutput === true) { + return parsed.output; + } + + const opts = options || {}; + const prepend = opts.contains ? '' : '^'; + const append = opts.contains ? '' : '$'; + let source = `${prepend}(?:${parsed.output})${append}`; + + if (parsed && parsed.negated === true) { + source = `^(?!${source}).*$`; + } + + const regex = picomatch.toRegex(source, options); + + if (returnState === true) { + regex.state = parsed; + } + + return regex; +}; + +picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => { + if (!input || typeof input !== 'string') { + throw new TypeError('Expected a non-empty string'); + } + + const opts = options || {}; + let parsed = { + negated: false, + fastpaths: true + }; + let prefix = ''; + let output; + + if (input.startsWith('./')) { + input = input.slice(2); + prefix = parsed.prefix = './'; + } + + if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) { + output = parse_1$1.fastpaths(input, options); + } + + if (output === undefined) { + parsed = parse_1$1(input, options); + parsed.prefix = prefix + (parsed.prefix || ''); + } else { + parsed.output = output; + } + + return picomatch.compileRe(parsed, options, returnOutput, returnState); +}; +/** + * Create a regular expression from the given regex source string. + * + * ```js + * const picomatch = require('picomatch'); + * // picomatch.toRegex(source[, options]); + * + * const { output } = picomatch.parse('*.js'); + * console.log(picomatch.toRegex(output)); + * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/ + * ``` + * @param {String} `source` Regular expression source string. + * @param {Object} `options` + * @return {RegExp} + * @api public + */ + + +picomatch.toRegex = (source, options) => { + try { + const opts = options || {}; + return new RegExp(source, opts.flags || (opts.nocase ? 'i' : '')); + } catch (err) { + if (options && options.debug === true) throw err; + return /$^/; + } +}; +/** + * Picomatch constants. + * @return {Object} + */ + + +picomatch.constants = constants$3; +/** + * Expose "picomatch" + */ + +var picomatch_1 = picomatch; + +var picomatch$1 = picomatch_1; + +const isEmptyString = val => typeof val === 'string' && (val === '' || val === './'); +/** + * Returns an array of strings that match one or more glob patterns. + * + * ```js + * const mm = require('micromatch'); + * // mm(list, patterns[, options]); + * + * console.log(mm(['a.js', 'a.txt'], ['*.js'])); + * //=> [ 'a.js' ] + * ``` + * @param {String|Array} list List of strings to match. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} options See available [options](#options) + * @return {Array} Returns an array of matches + * @summary false + * @api public + */ + + +const micromatch = (list, patterns, options) => { + patterns = [].concat(patterns); + list = [].concat(list); + let omit = new Set(); + let keep = new Set(); + let items = new Set(); + let negatives = 0; + + let onResult = state => { + items.add(state.output); + + if (options && options.onResult) { + options.onResult(state); + } + }; + + for (let i = 0; i < patterns.length; i++) { + let isMatch = picomatch$1(String(patterns[i]), Object.assign({}, options, { + onResult + }), true); + let negated = isMatch.state.negated || isMatch.state.negatedExtglob; + if (negated) negatives++; + + for (let item of list) { + let matched = isMatch(item, true); + let match = negated ? !matched.isMatch : matched.isMatch; + if (!match) continue; + + if (negated) { + omit.add(matched.output); + } else { + omit.delete(matched.output); + keep.add(matched.output); + } + } + } + + let result = negatives === patterns.length ? [...items] : [...keep]; + let matches = result.filter(item => !omit.has(item)); + + if (options && matches.length === 0) { + if (options.failglob === true) { + throw new Error(`No matches found for "${patterns.join(', ')}"`); + } + + if (options.nonull === true || options.nullglob === true) { + return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns; + } + } + + return matches; +}; +/** + * Backwards compatibility + */ + + +micromatch.match = micromatch; +/** + * Returns a matcher function from the given glob `pattern` and `options`. + * The returned function takes a string to match as its only argument and returns + * true if the string is a match. + * + * ```js + * const mm = require('micromatch'); + * // mm.matcher(pattern[, options]); + * + * const isMatch = mm.matcher('*.!(*a)'); + * console.log(isMatch('a.a')); //=> false + * console.log(isMatch('a.b')); //=> true + * ``` + * @param {String} `pattern` Glob pattern + * @param {Object} `options` + * @return {Function} Returns a matcher function. + * @api public + */ + +micromatch.matcher = (pattern, options) => picomatch$1(pattern, options); +/** + * Returns true if **any** of the given glob `patterns` match the specified `string`. + * + * ```js + * const mm = require('micromatch'); + * // mm.isMatch(string, patterns[, options]); + * + * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true + * console.log(mm.isMatch('a.a', 'b.*')); //=> false + * ``` + * @param {String} str The string to test. + * @param {String|Array} patterns One or more glob patterns to use for matching. + * @param {Object} [options] See available [options](#options). + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str); +/** + * Backwards compatibility + */ + + +micromatch.any = micromatch.isMatch; +/** + * Returns a list of strings that _**do not match any**_ of the given `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.not(list, patterns[, options]); + * + * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a')); + * //=> ['b.b', 'c.c'] + * ``` + * @param {Array} `list` Array of strings to match. + * @param {String|Array} `patterns` One or more glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Array} Returns an array of strings that **do not match** the given patterns. + * @api public + */ + +micromatch.not = (list, patterns, options = {}) => { + patterns = [].concat(patterns).map(String); + let result = new Set(); + let items = []; + + let onResult = state => { + if (options.onResult) options.onResult(state); + items.push(state.output); + }; + + let matches = micromatch(list, patterns, Object.assign({}, options, { + onResult + })); + + for (let item of items) { + if (!matches.includes(item)) { + result.add(item); + } + } + + return [...result]; +}; +/** + * Returns true if the given `string` contains the given pattern. Similar + * to [.isMatch](#isMatch) but the pattern can match any part of the string. + * + * ```js + * var mm = require('micromatch'); + * // mm.contains(string, pattern[, options]); + * + * console.log(mm.contains('aa/bb/cc', '*b')); + * //=> true + * console.log(mm.contains('aa/bb/cc', '*d')); + * //=> false + * ``` + * @param {String} `str` The string to match. + * @param {String|Array} `patterns` Glob pattern to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if the patter matches any part of `str`. + * @api public + */ + + +micromatch.contains = (str, pattern, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`); + } + + if (Array.isArray(pattern)) { + return pattern.some(p => micromatch.contains(str, p, options)); + } + + if (typeof pattern === 'string') { + if (isEmptyString(str) || isEmptyString(pattern)) { + return false; + } + + if (str.includes(pattern) || str.startsWith('./') && str.slice(2).includes(pattern)) { + return true; + } + } + + return micromatch.isMatch(str, pattern, Object.assign({}, options, { + contains: true + })); +}; +/** + * Filter the keys of the given object with the given `glob` pattern + * and `options`. Does not attempt to match nested keys. If you need this feature, + * use [glob-object][] instead. + * + * ```js + * const mm = require('micromatch'); + * // mm.matchKeys(object, patterns[, options]); + * + * const obj = { aa: 'a', ab: 'b', ac: 'c' }; + * console.log(mm.matchKeys(obj, '*b')); + * //=> { ab: 'b' } + * ``` + * @param {Object} `object` The object with keys to filter. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Object} Returns an object with only keys that match the given patterns. + * @api public + */ + + +micromatch.matchKeys = (obj, patterns, options) => { + if (!utils$2.isObject(obj)) { + throw new TypeError('Expected the first argument to be an object'); + } + + let keys = micromatch(Object.keys(obj), patterns, options); + let res = {}; + + for (let key of keys) res[key] = obj[key]; + + return res; +}; +/** + * Returns true if some of the strings in the given `list` match any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.some(list, patterns[, options]); + * + * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // true + * console.log(mm.some(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +micromatch.some = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$1(String(pattern), options); + + if (items.some(item => isMatch(item))) { + return true; + } + } + + return false; +}; +/** + * Returns true if every string in the given `list` matches + * any of the given glob `patterns`. + * + * ```js + * const mm = require('micromatch'); + * // mm.every(list, patterns[, options]); + * + * console.log(mm.every('foo.js', ['foo.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js'])); + * // true + * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js'])); + * // false + * console.log(mm.every(['foo.js'], ['*.js', '!foo.js'])); + * // false + * ``` + * @param {String|Array} `list` The string or array of strings to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +micromatch.every = (list, patterns, options) => { + let items = [].concat(list); + + for (let pattern of [].concat(patterns)) { + let isMatch = picomatch$1(String(pattern), options); + + if (!items.every(item => isMatch(item))) { + return false; + } + } + + return true; +}; +/** + * Returns true if **all** of the given `patterns` match + * the specified string. + * + * ```js + * const mm = require('micromatch'); + * // mm.all(string, patterns[, options]); + * + * console.log(mm.all('foo.js', ['foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', '!foo.js'])); + * // false + * + * console.log(mm.all('foo.js', ['*.js', 'foo.js'])); + * // true + * + * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js'])); + * // true + * ``` + * @param {String|Array} `str` The string to test. + * @param {String|Array} `patterns` One or more glob patterns to use for matching. + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns true if any patterns match `str` + * @api public + */ + + +micromatch.all = (str, patterns, options) => { + if (typeof str !== 'string') { + throw new TypeError(`Expected a string: "${util__default['default'].inspect(str)}"`); + } + + return [].concat(patterns).every(p => picomatch$1(p, options)(str)); +}; +/** + * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match. + * + * ```js + * const mm = require('micromatch'); + * // mm.capture(pattern, string[, options]); + * + * console.log(mm.capture('test/*.js', 'test/foo.js')); + * //=> ['foo'] + * console.log(mm.capture('test/*.js', 'foo/bar.css')); + * //=> null + * ``` + * @param {String} `glob` Glob pattern to use for matching. + * @param {String} `input` String to match + * @param {Object} `options` See available [options](#options) for changing how matches are performed + * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`. + * @api public + */ + + +micromatch.capture = (glob, input, options) => { + let posix = utils$2.isWindows(options); + let regex = picomatch$1.makeRe(String(glob), Object.assign({}, options, { + capture: true + })); + let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input); + + if (match) { + return match.slice(1).map(v => v === void 0 ? '' : v); + } +}; +/** + * Create a regular expression from the given glob `pattern`. + * + * ```js + * const mm = require('micromatch'); + * // mm.makeRe(pattern[, options]); + * + * console.log(mm.makeRe('*.js')); + * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/ + * ``` + * @param {String} `pattern` A glob pattern to convert to regex. + * @param {Object} `options` + * @return {RegExp} Returns a regex created from the given pattern. + * @api public + */ + + +micromatch.makeRe = (...args) => picomatch$1.makeRe(...args); +/** + * Scan a glob pattern to separate the pattern into segments. Used + * by the [split](#split) method. + * + * ```js + * const mm = require('micromatch'); + * const state = mm.scan(pattern[, options]); + * ``` + * @param {String} `pattern` + * @param {Object} `options` + * @return {Object} Returns an object with + * @api public + */ + + +micromatch.scan = (...args) => picomatch$1.scan(...args); +/** + * Parse a glob pattern to create the source string for a regular + * expression. + * + * ```js + * const mm = require('micromatch'); + * const state = mm(pattern[, options]); + * ``` + * @param {String} `glob` + * @param {Object} `options` + * @return {Object} Returns an object with useful properties and output to be used as regex source string. + * @api public + */ + + +micromatch.parse = (patterns, options) => { + let res = []; + + for (let pattern of [].concat(patterns || [])) { + for (let str of braces_1(String(pattern), options)) { + res.push(picomatch$1.parse(str, options)); + } + } + + return res; +}; +/** + * Process the given brace `pattern`. + * + * ```js + * const { braces } = require('micromatch'); + * console.log(braces('foo/{a,b,c}/bar')); + * //=> [ 'foo/(a|b|c)/bar' ] + * + * console.log(braces('foo/{a,b,c}/bar', { expand: true })); + * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ] + * ``` + * @param {String} `pattern` String with brace pattern to process. + * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options. + * @return {Array} + * @api public + */ + + +micromatch.braces = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + + if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) { + return [pattern]; + } + + return braces_1(pattern, options); +}; +/** + * Expand braces + */ + + +micromatch.braceExpand = (pattern, options) => { + if (typeof pattern !== 'string') throw new TypeError('Expected a string'); + return micromatch.braces(pattern, Object.assign({}, options, { + expand: true + })); +}; +/** + * Expose micromatch + */ + + +var micromatch_1 = micromatch; + +var pattern = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.matchAny = exports.convertPatternsToRe = exports.makeRe = exports.getPatternParts = exports.expandBraceExpansion = exports.expandPatternsWithBraceExpansion = exports.isAffectDepthOfReadingPattern = exports.endsWithSlashGlobStar = exports.hasGlobStar = exports.getBaseDirectory = exports.getPositivePatterns = exports.getNegativePatterns = exports.isPositivePattern = exports.isNegativePattern = exports.convertToNegativePattern = exports.convertToPositivePattern = exports.isDynamicPattern = exports.isStaticPattern = void 0; + const GLOBSTAR = '**'; + const ESCAPE_SYMBOL = '\\'; + const COMMON_GLOB_SYMBOLS_RE = /[*?]|^!/; + const REGEX_CHARACTER_CLASS_SYMBOLS_RE = /\[.*]/; + const REGEX_GROUP_SYMBOLS_RE = /(?:^|[^!*+?@])\(.*\|.*\)/; + const GLOB_EXTENSION_SYMBOLS_RE = /[!*+?@]\(.*\)/; + const BRACE_EXPANSIONS_SYMBOLS_RE = /{.*(?:,|\.\.).*}/; + + function isStaticPattern(pattern, options = {}) { + return !isDynamicPattern(pattern, options); + } + + exports.isStaticPattern = isStaticPattern; + + function isDynamicPattern(pattern, options = {}) { + /** + * A special case with an empty string is necessary for matching patterns that start with a forward slash. + * An empty string cannot be a dynamic pattern. + * For example, the pattern `/lib/*` will be spread into parts: '', 'lib', '*'. + */ + if (pattern === '') { + return false; + } + /** + * When the `caseSensitiveMatch` option is disabled, all patterns must be marked as dynamic, because we cannot check + * filepath directly (without read directory). + */ + + + if (options.caseSensitiveMatch === false || pattern.includes(ESCAPE_SYMBOL)) { + return true; + } + + if (COMMON_GLOB_SYMBOLS_RE.test(pattern) || REGEX_CHARACTER_CLASS_SYMBOLS_RE.test(pattern) || REGEX_GROUP_SYMBOLS_RE.test(pattern)) { + return true; + } + + if (options.extglob !== false && GLOB_EXTENSION_SYMBOLS_RE.test(pattern)) { + return true; + } + + if (options.braceExpansion !== false && BRACE_EXPANSIONS_SYMBOLS_RE.test(pattern)) { + return true; + } + + return false; + } + + exports.isDynamicPattern = isDynamicPattern; + + function convertToPositivePattern(pattern) { + return isNegativePattern(pattern) ? pattern.slice(1) : pattern; + } + + exports.convertToPositivePattern = convertToPositivePattern; + + function convertToNegativePattern(pattern) { + return '!' + pattern; + } + + exports.convertToNegativePattern = convertToNegativePattern; + + function isNegativePattern(pattern) { + return pattern.startsWith('!') && pattern[1] !== '('; + } + + exports.isNegativePattern = isNegativePattern; + + function isPositivePattern(pattern) { + return !isNegativePattern(pattern); + } + + exports.isPositivePattern = isPositivePattern; + + function getNegativePatterns(patterns) { + return patterns.filter(isNegativePattern); + } + + exports.getNegativePatterns = getNegativePatterns; + + function getPositivePatterns(patterns) { + return patterns.filter(isPositivePattern); + } + + exports.getPositivePatterns = getPositivePatterns; + + function getBaseDirectory(pattern) { + return globParent(pattern, { + flipBackslashes: false + }); + } + + exports.getBaseDirectory = getBaseDirectory; + + function hasGlobStar(pattern) { + return pattern.includes(GLOBSTAR); + } + + exports.hasGlobStar = hasGlobStar; + + function endsWithSlashGlobStar(pattern) { + return pattern.endsWith('/' + GLOBSTAR); + } + + exports.endsWithSlashGlobStar = endsWithSlashGlobStar; + + function isAffectDepthOfReadingPattern(pattern) { + const basename = path__default['default'].basename(pattern); + return endsWithSlashGlobStar(pattern) || isStaticPattern(basename); + } + + exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern; + + function expandPatternsWithBraceExpansion(patterns) { + return patterns.reduce((collection, pattern) => { + return collection.concat(expandBraceExpansion(pattern)); + }, []); + } + + exports.expandPatternsWithBraceExpansion = expandPatternsWithBraceExpansion; + + function expandBraceExpansion(pattern) { + return micromatch_1.braces(pattern, { + expand: true, + nodupes: true + }); + } + + exports.expandBraceExpansion = expandBraceExpansion; + + function getPatternParts(pattern, options) { + let { + parts + } = picomatch$1.scan(pattern, Object.assign(Object.assign({}, options), { + parts: true + })); + /** + * The scan method returns an empty array in some cases. + * See micromatch/picomatch#58 for more details. + */ + + if (parts.length === 0) { + parts = [pattern]; + } + /** + * The scan method does not return an empty part for the pattern with a forward slash. + * This is another part of micromatch/picomatch#58. + */ + + + if (parts[0].startsWith('/')) { + parts[0] = parts[0].slice(1); + parts.unshift(''); + } + + return parts; + } + + exports.getPatternParts = getPatternParts; + + function makeRe(pattern, options) { + return micromatch_1.makeRe(pattern, options); + } + + exports.makeRe = makeRe; + + function convertPatternsToRe(patterns, options) { + return patterns.map(pattern => makeRe(pattern, options)); + } + + exports.convertPatternsToRe = convertPatternsToRe; + + function matchAny(entry, patternsRe) { + return patternsRe.some(patternRe => patternRe.test(entry)); + } + + exports.matchAny = matchAny; +}); + +var stream$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.merge = void 0; + + function merge(streams) { + const mergedStream = merge2_1(streams); + streams.forEach(stream => { + stream.once('error', error => mergedStream.emit('error', error)); + }); + mergedStream.once('close', () => propagateCloseEventToSources(streams)); + mergedStream.once('end', () => propagateCloseEventToSources(streams)); + return mergedStream; + } + + exports.merge = merge; + + function propagateCloseEventToSources(streams) { + streams.forEach(stream => stream.emit('close')); + } +}); + +var string$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.isEmpty = exports.isString = void 0; + + function isString(input) { + return typeof input === 'string'; + } + + exports.isString = isString; + + function isEmpty(input) { + return input === ''; + } + + exports.isEmpty = isEmpty; +}); + +var utils$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.string = exports.stream = exports.pattern = exports.path = exports.fs = exports.errno = exports.array = void 0; + exports.array = array$2; + exports.errno = errno; + exports.fs = fs$1; + exports.path = path_1; + exports.pattern = pattern; + exports.stream = stream$1; + exports.string = string$1; +}); + +var tasks = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.convertPatternGroupToTask = exports.convertPatternGroupsToTasks = exports.groupPatternsByBaseDirectory = exports.getNegativePatternsAsPositive = exports.getPositivePatterns = exports.convertPatternsToTasks = exports.generate = void 0; + + function generate(patterns, settings) { + const positivePatterns = getPositivePatterns(patterns); + const negativePatterns = getNegativePatternsAsPositive(patterns, settings.ignore); + const staticPatterns = positivePatterns.filter(pattern => utils$3.pattern.isStaticPattern(pattern, settings)); + const dynamicPatterns = positivePatterns.filter(pattern => utils$3.pattern.isDynamicPattern(pattern, settings)); + const staticTasks = convertPatternsToTasks(staticPatterns, negativePatterns, + /* dynamic */ + false); + const dynamicTasks = convertPatternsToTasks(dynamicPatterns, negativePatterns, + /* dynamic */ + true); + return staticTasks.concat(dynamicTasks); + } + + exports.generate = generate; + + function convertPatternsToTasks(positive, negative, dynamic) { + const positivePatternsGroup = groupPatternsByBaseDirectory(positive); // When we have a global group – there is no reason to divide the patterns into independent tasks. + // In this case, the global task covers the rest. + + if ('.' in positivePatternsGroup) { + const task = convertPatternGroupToTask('.', positive, negative, dynamic); + return [task]; + } + + return convertPatternGroupsToTasks(positivePatternsGroup, negative, dynamic); + } + + exports.convertPatternsToTasks = convertPatternsToTasks; + + function getPositivePatterns(patterns) { + return utils$3.pattern.getPositivePatterns(patterns); + } + + exports.getPositivePatterns = getPositivePatterns; + + function getNegativePatternsAsPositive(patterns, ignore) { + const negative = utils$3.pattern.getNegativePatterns(patterns).concat(ignore); + const positive = negative.map(utils$3.pattern.convertToPositivePattern); + return positive; + } + + exports.getNegativePatternsAsPositive = getNegativePatternsAsPositive; + + function groupPatternsByBaseDirectory(patterns) { + const group = {}; + return patterns.reduce((collection, pattern) => { + const base = utils$3.pattern.getBaseDirectory(pattern); + + if (base in collection) { + collection[base].push(pattern); + } else { + collection[base] = [pattern]; + } + + return collection; + }, group); + } + + exports.groupPatternsByBaseDirectory = groupPatternsByBaseDirectory; + + function convertPatternGroupsToTasks(positive, negative, dynamic) { + return Object.keys(positive).map(base => { + return convertPatternGroupToTask(base, positive[base], negative, dynamic); + }); + } + + exports.convertPatternGroupsToTasks = convertPatternGroupsToTasks; + + function convertPatternGroupToTask(base, positive, negative, dynamic) { + return { + dynamic, + positive, + negative, + base, + patterns: [].concat(positive, negative.map(utils$3.pattern.convertToNegativePattern)) + }; + } + + exports.convertPatternGroupToTask = convertPatternGroupToTask; +}); + +var async$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function read(path, settings, callback) { + settings.fs.lstat(path, (lstatError, lstat) => { + if (lstatError !== null) { + return callFailureCallback(callback, lstatError); + } + + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return callSuccessCallback(callback, lstat); + } + + settings.fs.stat(path, (statError, stat) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + return callFailureCallback(callback, statError); + } + + return callSuccessCallback(callback, lstat); + } + + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + + callSuccessCallback(callback, stat); + }); + }); + } + + exports.read = read; + + function callFailureCallback(callback, error) { + callback(error); + } + + function callSuccessCallback(callback, result) { + callback(null, result); + } +}); + +var sync$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function read(path, settings) { + const lstat = settings.fs.lstatSync(path); + + if (!lstat.isSymbolicLink() || !settings.followSymbolicLink) { + return lstat; + } + + try { + const stat = settings.fs.statSync(path); + + if (settings.markSymbolicLink) { + stat.isSymbolicLink = () => true; + } + + return stat; + } catch (error) { + if (!settings.throwErrorOnBrokenSymbolicLink) { + return lstat; + } + + throw error; + } + } + + exports.read = read; +}); + +var fs_1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + stat: fs__default['default'].stat, + lstatSync: fs__default['default'].lstatSync, + statSync: fs__default['default'].statSync + }; + + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + + exports.createFileSystemAdapter = createFileSystemAdapter; +}); + +var settings = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLink = this._getValue(this._options.followSymbolicLink, true); + this.fs = fs_1.createFileSystemAdapter(this._options.fs); + this.markSymbolicLink = this._getValue(this._options.markSymbolicLink, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + } + + _getValue(option, value) { + return option === undefined ? value : option; + } + + } + + exports.default = Settings; +}); + +var out = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Settings = settings.default; + + function stat(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return async$1.read(path, getSettings(), optionsOrSettingsOrCallback); + } + + async$1.read(path, getSettings(optionsOrSettingsOrCallback), callback); + } + + exports.stat = stat; + + function statSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync$1.read(path, settings); + } + + exports.statSync = statSync; + + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings.default) { + return settingsOrOptions; + } + + return new settings.default(settingsOrOptions); + } +}); + +var runParallel_1 = runParallel; + +function runParallel(tasks, cb) { + var results, pending, keys; + var isSync = true; + + if (Array.isArray(tasks)) { + results = []; + pending = tasks.length; + } else { + keys = Object.keys(tasks); + results = {}; + pending = keys.length; + } + + function done(err) { + function end() { + if (cb) cb(err, results); + cb = null; + } + + if (isSync) process.nextTick(end);else end(); + } + + function each(i, err, result) { + results[i] = result; + + if (--pending === 0 || err) { + done(err); + } + } + + if (!pending) { + // empty + done(null); + } else if (keys) { + // object + keys.forEach(function (key) { + tasks[key](function (err, result) { + each(key, err, result); + }); + }); + } else { + // array + tasks.forEach(function (task, i) { + task(function (err, result) { + each(i, err, result); + }); + }); + } + + isSync = false; +} + +var constants$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + const NODE_PROCESS_VERSION_PARTS = process.versions.node.split('.'); + const MAJOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[0], 10); + const MINOR_VERSION = parseInt(NODE_PROCESS_VERSION_PARTS[1], 10); + const SUPPORTED_MAJOR_VERSION = 10; + const SUPPORTED_MINOR_VERSION = 10; + const IS_MATCHED_BY_MAJOR = MAJOR_VERSION > SUPPORTED_MAJOR_VERSION; + const IS_MATCHED_BY_MAJOR_AND_MINOR = MAJOR_VERSION === SUPPORTED_MAJOR_VERSION && MINOR_VERSION >= SUPPORTED_MINOR_VERSION; + /** + * IS `true` for Node.js 10.10 and greater. + */ + + exports.IS_SUPPORT_READDIR_WITH_FILE_TYPES = IS_MATCHED_BY_MAJOR || IS_MATCHED_BY_MAJOR_AND_MINOR; +}); + +var fs$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class DirentFromStats { + constructor(name, stats) { + this.name = name; + this.isBlockDevice = stats.isBlockDevice.bind(stats); + this.isCharacterDevice = stats.isCharacterDevice.bind(stats); + this.isDirectory = stats.isDirectory.bind(stats); + this.isFIFO = stats.isFIFO.bind(stats); + this.isFile = stats.isFile.bind(stats); + this.isSocket = stats.isSocket.bind(stats); + this.isSymbolicLink = stats.isSymbolicLink.bind(stats); + } + + } + + function createDirentFromStats(name, stats) { + return new DirentFromStats(name, stats); + } + + exports.createDirentFromStats = createDirentFromStats; +}); + +var utils$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.fs = fs$2; +}); + +var async$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function read(directory, settings, callback) { + if (!settings.stats && constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings, callback); + } + + return readdir(directory, settings, callback); + } + + exports.read = read; + + function readdirWithFileTypes(directory, settings, callback) { + settings.fs.readdir(directory, { + withFileTypes: true + }, (readdirError, dirents) => { + if (readdirError !== null) { + return callFailureCallback(callback, readdirError); + } + + const entries = dirents.map(dirent => ({ + dirent, + name: dirent.name, + path: `${directory}${settings.pathSegmentSeparator}${dirent.name}` + })); + + if (!settings.followSymbolicLinks) { + return callSuccessCallback(callback, entries); + } + + const tasks = entries.map(entry => makeRplTaskEntry(entry, settings)); + runParallel_1(tasks, (rplError, rplEntries) => { + if (rplError !== null) { + return callFailureCallback(callback, rplError); + } + + callSuccessCallback(callback, rplEntries); + }); + }); + } + + exports.readdirWithFileTypes = readdirWithFileTypes; + + function makeRplTaskEntry(entry, settings) { + return done => { + if (!entry.dirent.isSymbolicLink()) { + return done(null, entry); + } + + settings.fs.stat(entry.path, (statError, stats) => { + if (statError !== null) { + if (settings.throwErrorOnBrokenSymbolicLink) { + return done(statError); + } + + return done(null, entry); + } + + entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats); + return done(null, entry); + }); + }; + } + + function readdir(directory, settings, callback) { + settings.fs.readdir(directory, (readdirError, names) => { + if (readdirError !== null) { + return callFailureCallback(callback, readdirError); + } + + const filepaths = names.map(name => `${directory}${settings.pathSegmentSeparator}${name}`); + const tasks = filepaths.map(filepath => { + return done => out.stat(filepath, settings.fsStatSettings, done); + }); + runParallel_1(tasks, (rplError, results) => { + if (rplError !== null) { + return callFailureCallback(callback, rplError); + } + + const entries = []; + names.forEach((name, index) => { + const stats = results[index]; + const entry = { + name, + path: filepaths[index], + dirent: utils$4.fs.createDirentFromStats(name, stats) + }; + + if (settings.stats) { + entry.stats = stats; + } + + entries.push(entry); + }); + callSuccessCallback(callback, entries); + }); + }); + } + + exports.readdir = readdir; + + function callFailureCallback(callback, error) { + callback(error); + } + + function callSuccessCallback(callback, result) { + callback(null, result); + } +}); + +var sync$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function read(directory, settings) { + if (!settings.stats && constants$4.IS_SUPPORT_READDIR_WITH_FILE_TYPES) { + return readdirWithFileTypes(directory, settings); + } + + return readdir(directory, settings); + } + + exports.read = read; + + function readdirWithFileTypes(directory, settings) { + const dirents = settings.fs.readdirSync(directory, { + withFileTypes: true + }); + return dirents.map(dirent => { + const entry = { + dirent, + name: dirent.name, + path: `${directory}${settings.pathSegmentSeparator}${dirent.name}` + }; + + if (entry.dirent.isSymbolicLink() && settings.followSymbolicLinks) { + try { + const stats = settings.fs.statSync(entry.path); + entry.dirent = utils$4.fs.createDirentFromStats(entry.name, stats); + } catch (error) { + if (settings.throwErrorOnBrokenSymbolicLink) { + throw error; + } + } + } + + return entry; + }); + } + + exports.readdirWithFileTypes = readdirWithFileTypes; + + function readdir(directory, settings) { + const names = settings.fs.readdirSync(directory); + return names.map(name => { + const entryPath = `${directory}${settings.pathSegmentSeparator}${name}`; + const stats = out.statSync(entryPath, settings.fsStatSettings); + const entry = { + name, + path: entryPath, + dirent: utils$4.fs.createDirentFromStats(name, stats) + }; + + if (settings.stats) { + entry.stats = stats; + } + + return entry; + }); + } + + exports.readdir = readdir; +}); + +var fs_1$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + stat: fs__default['default'].stat, + lstatSync: fs__default['default'].lstatSync, + statSync: fs__default['default'].statSync, + readdir: fs__default['default'].readdir, + readdirSync: fs__default['default'].readdirSync + }; + + function createFileSystemAdapter(fsMethods) { + if (fsMethods === undefined) { + return exports.FILE_SYSTEM_ADAPTER; + } + + return Object.assign(Object.assign({}, exports.FILE_SYSTEM_ADAPTER), fsMethods); + } + + exports.createFileSystemAdapter = createFileSystemAdapter; +}); + +var settings$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, false); + this.fs = fs_1$1.createFileSystemAdapter(this._options.fs); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep); + this.stats = this._getValue(this._options.stats, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, true); + this.fsStatSettings = new out.Settings({ + followSymbolicLink: this.followSymbolicLinks, + fs: this.fs, + throwErrorOnBrokenSymbolicLink: this.throwErrorOnBrokenSymbolicLink + }); + } + + _getValue(option, value) { + return option === undefined ? value : option; + } + + } + + exports.default = Settings; +}); + +var out$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Settings = settings$1.default; + + function scandir(path, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return async$2.read(path, getSettings(), optionsOrSettingsOrCallback); + } + + async$2.read(path, getSettings(optionsOrSettingsOrCallback), callback); + } + + exports.scandir = scandir; + + function scandirSync(path, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + return sync$2.read(path, settings); + } + + exports.scandirSync = scandirSync; + + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings$1.default) { + return settingsOrOptions; + } + + return new settings$1.default(settingsOrOptions); + } +}); + +function reusify(Constructor) { + var head = new Constructor(); + var tail = head; + + function get() { + var current = head; + + if (current.next) { + head = current.next; + } else { + head = new Constructor(); + tail = head; + } + + current.next = null; + return current; + } + + function release(obj) { + tail.next = obj; + tail = obj; + } + + return { + get: get, + release: release + }; +} + +var reusify_1 = reusify; + +function fastqueue(context, worker, concurrency) { + if (typeof context === 'function') { + concurrency = worker; + worker = context; + context = null; + } + + var cache = reusify_1(Task); + var queueHead = null; + var queueTail = null; + var _running = 0; + var self = { + push: push, + drain: noop$1, + saturated: noop$1, + pause: pause, + paused: false, + concurrency: concurrency, + running: running, + resume: resume, + idle: idle, + length: length, + getQueue: getQueue, + unshift: unshift, + empty: noop$1, + kill: kill, + killAndDrain: killAndDrain + }; + return self; + + function running() { + return _running; + } + + function pause() { + self.paused = true; + } + + function length() { + var current = queueHead; + var counter = 0; + + while (current) { + current = current.next; + counter++; + } + + return counter; + } + + function getQueue() { + var current = queueHead; + var tasks = []; + + while (current) { + tasks.push(current.value); + current = current.next; + } + + return tasks; + } + + function resume() { + if (!self.paused) return; + self.paused = false; + + for (var i = 0; i < self.concurrency; i++) { + _running++; + release(); + } + } + + function idle() { + return _running === 0 && self.length() === 0; + } + + function push(value, done) { + var current = cache.get(); + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop$1; + + if (_running === self.concurrency || self.paused) { + if (queueTail) { + queueTail.next = current; + queueTail = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function unshift(value, done) { + var current = cache.get(); + current.context = context; + current.release = release; + current.value = value; + current.callback = done || noop$1; + + if (_running === self.concurrency || self.paused) { + if (queueHead) { + current.next = queueHead; + queueHead = current; + } else { + queueHead = current; + queueTail = current; + self.saturated(); + } + } else { + _running++; + worker.call(context, current.value, current.worked); + } + } + + function release(holder) { + if (holder) { + cache.release(holder); + } + + var next = queueHead; + + if (next) { + if (!self.paused) { + if (queueTail === queueHead) { + queueTail = null; + } + + queueHead = next.next; + next.next = null; + worker.call(context, next.value, next.worked); + + if (queueTail === null) { + self.empty(); + } + } else { + _running--; + } + } else if (--_running === 0) { + self.drain(); + } + } + + function kill() { + queueHead = null; + queueTail = null; + self.drain = noop$1; + } + + function killAndDrain() { + queueHead = null; + queueTail = null; + self.drain(); + self.drain = noop$1; + } +} + +function noop$1() {} + +function Task() { + this.value = null; + this.callback = noop$1; + this.next = null; + this.release = noop$1; + this.context = null; + var self = this; + + this.worked = function worked(err, result) { + var callback = self.callback; + self.value = null; + self.callback = noop$1; + callback.call(self.context, err, result); + self.release(self); + }; +} + +var queue = fastqueue; + +var common$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + function isFatalError(settings, error) { + if (settings.errorFilter === null) { + return true; + } + + return !settings.errorFilter(error); + } + + exports.isFatalError = isFatalError; + + function isAppliedFilter(filter, value) { + return filter === null || filter(value); + } + + exports.isAppliedFilter = isAppliedFilter; + + function replacePathSegmentSeparator(filepath, separator) { + return filepath.split(/[\\/]/).join(separator); + } + + exports.replacePathSegmentSeparator = replacePathSegmentSeparator; + + function joinPathSegments(a, b, separator) { + if (a === '') { + return b; + } + + return a + separator + b; + } + + exports.joinPathSegments = joinPathSegments; +}); + +var reader = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Reader { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._root = common$2.replacePathSegmentSeparator(_root, _settings.pathSegmentSeparator); + } + + } + + exports.default = Reader; +}); + +var async$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class AsyncReader extends reader.default { + constructor(_root, _settings) { + super(_root, _settings); + this._settings = _settings; + this._scandir = out$1.scandir; + this._emitter = new events__default['default'].EventEmitter(); + this._queue = queue(this._worker.bind(this), this._settings.concurrency); + this._isFatalError = false; + this._isDestroyed = false; + + this._queue.drain = () => { + if (!this._isFatalError) { + this._emitter.emit('end'); + } + }; + } + + read() { + this._isFatalError = false; + this._isDestroyed = false; + setImmediate(() => { + this._pushToQueue(this._root, this._settings.basePath); + }); + return this._emitter; + } + + destroy() { + if (this._isDestroyed) { + throw new Error('The reader is already destroyed'); + } + + this._isDestroyed = true; + + this._queue.killAndDrain(); + } + + onEntry(callback) { + this._emitter.on('entry', callback); + } + + onError(callback) { + this._emitter.once('error', callback); + } + + onEnd(callback) { + this._emitter.once('end', callback); + } + + _pushToQueue(directory, base) { + const queueItem = { + directory, + base + }; + + this._queue.push(queueItem, error => { + if (error !== null) { + this._handleError(error); + } + }); + } + + _worker(item, done) { + this._scandir(item.directory, this._settings.fsScandirSettings, (error, entries) => { + if (error !== null) { + return done(error, undefined); + } + + for (const entry of entries) { + this._handleEntry(entry, item.base); + } + + done(null, undefined); + }); + } + + _handleError(error) { + if (!common$2.isFatalError(this._settings, error)) { + return; + } + + this._isFatalError = true; + this._isDestroyed = true; + + this._emitter.emit('error', error); + } + + _handleEntry(entry, base) { + if (this._isDestroyed || this._isFatalError) { + return; + } + + const fullpath = entry.path; + + if (base !== undefined) { + entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + + if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) { + this._emitEntry(entry); + } + + if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, entry.path); + } + } + + _emitEntry(entry) { + this._emitter.emit('entry', entry); + } + + } + + exports.default = AsyncReader; +}); + +var async$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class AsyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async$3.default(this._root, this._settings); + this._storage = new Set(); + } + + read(callback) { + this._reader.onError(error => { + callFailureCallback(callback, error); + }); + + this._reader.onEntry(entry => { + this._storage.add(entry); + }); + + this._reader.onEnd(() => { + callSuccessCallback(callback, [...this._storage]); + }); + + this._reader.read(); + } + + } + + exports.default = AsyncProvider; + + function callFailureCallback(callback, error) { + callback(error); + } + + function callSuccessCallback(callback, entries) { + callback(null, entries); + } +}); + +var stream$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class StreamProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new async$3.default(this._root, this._settings); + this._stream = new stream__default['default'].Readable({ + objectMode: true, + read: () => {}, + destroy: this._reader.destroy.bind(this._reader) + }); + } + + read() { + this._reader.onError(error => { + this._stream.emit('error', error); + }); + + this._reader.onEntry(entry => { + this._stream.push(entry); + }); + + this._reader.onEnd(() => { + this._stream.push(null); + }); + + this._reader.read(); + + return this._stream; + } + + } + + exports.default = StreamProvider; +}); + +var sync$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class SyncReader extends reader.default { + constructor() { + super(...arguments); + this._scandir = out$1.scandirSync; + this._storage = new Set(); + this._queue = new Set(); + } + + read() { + this._pushToQueue(this._root, this._settings.basePath); + + this._handleQueue(); + + return [...this._storage]; + } + + _pushToQueue(directory, base) { + this._queue.add({ + directory, + base + }); + } + + _handleQueue() { + for (const item of this._queue.values()) { + this._handleDirectory(item.directory, item.base); + } + } + + _handleDirectory(directory, base) { + try { + const entries = this._scandir(directory, this._settings.fsScandirSettings); + + for (const entry of entries) { + this._handleEntry(entry, base); + } + } catch (error) { + this._handleError(error); + } + } + + _handleError(error) { + if (!common$2.isFatalError(this._settings, error)) { + return; + } + + throw error; + } + + _handleEntry(entry, base) { + const fullpath = entry.path; + + if (base !== undefined) { + entry.path = common$2.joinPathSegments(base, entry.name, this._settings.pathSegmentSeparator); + } + + if (common$2.isAppliedFilter(this._settings.entryFilter, entry)) { + this._pushToStorage(entry); + } + + if (entry.dirent.isDirectory() && common$2.isAppliedFilter(this._settings.deepFilter, entry)) { + this._pushToQueue(fullpath, entry.path); + } + } + + _pushToStorage(entry) { + this._storage.add(entry); + } + + } + + exports.default = SyncReader; +}); + +var sync$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class SyncProvider { + constructor(_root, _settings) { + this._root = _root; + this._settings = _settings; + this._reader = new sync$3.default(this._root, this._settings); + } + + read() { + return this._reader.read(); + } + + } + + exports.default = SyncProvider; +}); + +var settings$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.basePath = this._getValue(this._options.basePath, undefined); + this.concurrency = this._getValue(this._options.concurrency, Infinity); + this.deepFilter = this._getValue(this._options.deepFilter, null); + this.entryFilter = this._getValue(this._options.entryFilter, null); + this.errorFilter = this._getValue(this._options.errorFilter, null); + this.pathSegmentSeparator = this._getValue(this._options.pathSegmentSeparator, path__default['default'].sep); + this.fsScandirSettings = new out$1.Settings({ + followSymbolicLinks: this._options.followSymbolicLinks, + fs: this._options.fs, + pathSegmentSeparator: this._options.pathSegmentSeparator, + stats: this._options.stats, + throwErrorOnBrokenSymbolicLink: this._options.throwErrorOnBrokenSymbolicLink + }); + } + + _getValue(option, value) { + return option === undefined ? value : option; + } + + } + + exports.default = Settings; +}); + +var out$2 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.Settings = settings$2.default; + + function walk(directory, optionsOrSettingsOrCallback, callback) { + if (typeof optionsOrSettingsOrCallback === 'function') { + return new async$4.default(directory, getSettings()).read(optionsOrSettingsOrCallback); + } + + new async$4.default(directory, getSettings(optionsOrSettingsOrCallback)).read(callback); + } + + exports.walk = walk; + + function walkSync(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new sync$4.default(directory, settings); + return provider.read(); + } + + exports.walkSync = walkSync; + + function walkStream(directory, optionsOrSettings) { + const settings = getSettings(optionsOrSettings); + const provider = new stream$2.default(directory, settings); + return provider.read(); + } + + exports.walkStream = walkStream; + + function getSettings(settingsOrOptions = {}) { + if (settingsOrOptions instanceof settings$2.default) { + return settingsOrOptions; + } + + return new settings$2.default(settingsOrOptions); + } +}); + +var reader$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Reader { + constructor(_settings) { + this._settings = _settings; + this._fsStatSettings = new out.Settings({ + followSymbolicLink: this._settings.followSymbolicLinks, + fs: this._settings.fs, + throwErrorOnBrokenSymbolicLink: this._settings.followSymbolicLinks + }); + } + + _getFullEntryPath(filepath) { + return path__default['default'].resolve(this._settings.cwd, filepath); + } + + _makeEntry(stats, pattern) { + const entry = { + name: pattern, + path: pattern, + dirent: utils$3.fs.createDirentFromStats(pattern, stats) + }; + + if (this._settings.stats) { + entry.stats = stats; + } + + return entry; + } + + _isFatalError(error) { + return !utils$3.errno.isEnoentCodeError(error) && !this._settings.suppressErrors; + } + + } + + exports.default = Reader; +}); + +var stream$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ReaderStream extends reader$1.default { + constructor() { + super(...arguments); + this._walkStream = out$2.walkStream; + this._stat = out.stat; + } + + dynamic(root, options) { + return this._walkStream(root, options); + } + + static(patterns, options) { + const filepaths = patterns.map(this._getFullEntryPath, this); + const stream = new stream__default['default'].PassThrough({ + objectMode: true + }); + + stream._write = (index, _enc, done) => { + return this._getEntry(filepaths[index], patterns[index], options).then(entry => { + if (entry !== null && options.entryFilter(entry)) { + stream.push(entry); + } + + if (index === filepaths.length - 1) { + stream.end(); + } + + done(); + }).catch(done); + }; + + for (let i = 0; i < filepaths.length; i++) { + stream.write(i); + } + + return stream; + } + + _getEntry(filepath, pattern, options) { + return this._getStat(filepath).then(stats => this._makeEntry(stats, pattern)).catch(error => { + if (options.errorFilter(error)) { + return null; + } + + throw error; + }); + } + + _getStat(filepath) { + return new Promise((resolve, reject) => { + this._stat(filepath, this._fsStatSettings, (error, stats) => { + return error === null ? resolve(stats) : reject(error); + }); + }); + } + + } + + exports.default = ReaderStream; +}); + +var matcher = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Matcher { + constructor(_patterns, _settings, _micromatchOptions) { + this._patterns = _patterns; + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this._storage = []; + + this._fillStorage(); + } + + _fillStorage() { + /** + * The original pattern may include `{,*,**,a/*}`, which will lead to problems with matching (unresolved level). + * So, before expand patterns with brace expansion into separated patterns. + */ + const patterns = utils$3.pattern.expandPatternsWithBraceExpansion(this._patterns); + + for (const pattern of patterns) { + const segments = this._getPatternSegments(pattern); + + const sections = this._splitSegmentsIntoSections(segments); + + this._storage.push({ + complete: sections.length <= 1, + pattern, + segments, + sections + }); + } + } + + _getPatternSegments(pattern) { + const parts = utils$3.pattern.getPatternParts(pattern, this._micromatchOptions); + return parts.map(part => { + const dynamic = utils$3.pattern.isDynamicPattern(part, this._settings); + + if (!dynamic) { + return { + dynamic: false, + pattern: part + }; + } + + return { + dynamic: true, + pattern: part, + patternRe: utils$3.pattern.makeRe(part, this._micromatchOptions) + }; + }); + } + + _splitSegmentsIntoSections(segments) { + return utils$3.array.splitWhen(segments, segment => segment.dynamic && utils$3.pattern.hasGlobStar(segment.pattern)); + } + + } + + exports.default = Matcher; +}); + +var partial = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class PartialMatcher extends matcher.default { + match(filepath) { + const parts = filepath.split('/'); + const levels = parts.length; + + const patterns = this._storage.filter(info => !info.complete || info.segments.length > levels); + + for (const pattern of patterns) { + const section = pattern.sections[0]; + /** + * In this case, the pattern has a globstar and we must read all directories unconditionally, + * but only if the level has reached the end of the first group. + * + * fixtures/{a,b}/** + * ^ true/false ^ always true + */ + + if (!pattern.complete && levels > section.length) { + return true; + } + + const match = parts.every((part, index) => { + const segment = pattern.segments[index]; + + if (segment.dynamic && segment.patternRe.test(part)) { + return true; + } + + if (!segment.dynamic && segment.pattern === part) { + return true; + } + + return false; + }); + + if (match) { + return true; + } + } + + return false; + } + + } + + exports.default = PartialMatcher; +}); + +var deep = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class DeepFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + } + + getFilter(basePath, positive, negative) { + const matcher = this._getMatcher(positive); + + const negativeRe = this._getNegativePatternsRe(negative); + + return entry => this._filter(basePath, entry, matcher, negativeRe); + } + + _getMatcher(patterns) { + return new partial.default(patterns, this._settings, this._micromatchOptions); + } + + _getNegativePatternsRe(patterns) { + const affectDepthOfReadingPatterns = patterns.filter(utils$3.pattern.isAffectDepthOfReadingPattern); + return utils$3.pattern.convertPatternsToRe(affectDepthOfReadingPatterns, this._micromatchOptions); + } + + _filter(basePath, entry, matcher, negativeRe) { + if (this._isSkippedByDeep(basePath, entry.path)) { + return false; + } + + if (this._isSkippedSymbolicLink(entry)) { + return false; + } + + const filepath = utils$3.path.removeLeadingDotSegment(entry.path); + + if (this._isSkippedByPositivePatterns(filepath, matcher)) { + return false; + } + + return this._isSkippedByNegativePatterns(filepath, negativeRe); + } + + _isSkippedByDeep(basePath, entryPath) { + /** + * Avoid unnecessary depth calculations when it doesn't matter. + */ + if (this._settings.deep === Infinity) { + return false; + } + + return this._getEntryLevel(basePath, entryPath) >= this._settings.deep; + } + + _getEntryLevel(basePath, entryPath) { + const entryPathDepth = entryPath.split('/').length; + + if (basePath === '') { + return entryPathDepth; + } + + const basePathDepth = basePath.split('/').length; + return entryPathDepth - basePathDepth; + } + + _isSkippedSymbolicLink(entry) { + return !this._settings.followSymbolicLinks && entry.dirent.isSymbolicLink(); + } + + _isSkippedByPositivePatterns(entryPath, matcher) { + return !this._settings.baseNameMatch && !matcher.match(entryPath); + } + + _isSkippedByNegativePatterns(entryPath, patternsRe) { + return !utils$3.pattern.matchAny(entryPath, patternsRe); + } + + } + + exports.default = DeepFilter; +}); + +var entry = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class EntryFilter { + constructor(_settings, _micromatchOptions) { + this._settings = _settings; + this._micromatchOptions = _micromatchOptions; + this.index = new Map(); + } + + getFilter(positive, negative) { + const positiveRe = utils$3.pattern.convertPatternsToRe(positive, this._micromatchOptions); + const negativeRe = utils$3.pattern.convertPatternsToRe(negative, this._micromatchOptions); + return entry => this._filter(entry, positiveRe, negativeRe); + } + + _filter(entry, positiveRe, negativeRe) { + if (this._settings.unique && this._isDuplicateEntry(entry)) { + return false; + } + + if (this._onlyFileFilter(entry) || this._onlyDirectoryFilter(entry)) { + return false; + } + + if (this._isSkippedByAbsoluteNegativePatterns(entry.path, negativeRe)) { + return false; + } + + const filepath = this._settings.baseNameMatch ? entry.name : entry.path; + const isMatched = this._isMatchToPatterns(filepath, positiveRe) && !this._isMatchToPatterns(entry.path, negativeRe); + + if (this._settings.unique && isMatched) { + this._createIndexRecord(entry); + } + + return isMatched; + } + + _isDuplicateEntry(entry) { + return this.index.has(entry.path); + } + + _createIndexRecord(entry) { + this.index.set(entry.path, undefined); + } + + _onlyFileFilter(entry) { + return this._settings.onlyFiles && !entry.dirent.isFile(); + } + + _onlyDirectoryFilter(entry) { + return this._settings.onlyDirectories && !entry.dirent.isDirectory(); + } + + _isSkippedByAbsoluteNegativePatterns(entryPath, patternsRe) { + if (!this._settings.absolute) { + return false; + } + + const fullpath = utils$3.path.makeAbsolute(this._settings.cwd, entryPath); + return utils$3.pattern.matchAny(fullpath, patternsRe); + } + + _isMatchToPatterns(entryPath, patternsRe) { + const filepath = utils$3.path.removeLeadingDotSegment(entryPath); + return utils$3.pattern.matchAny(filepath, patternsRe); + } + + } + + exports.default = EntryFilter; +}); + +var error = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ErrorFilter { + constructor(_settings) { + this._settings = _settings; + } + + getFilter() { + return error => this._isNonFatalError(error); + } + + _isNonFatalError(error) { + return utils$3.errno.isEnoentCodeError(error) || this._settings.suppressErrors; + } + + } + + exports.default = ErrorFilter; +}); + +var entry$1 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class EntryTransformer { + constructor(_settings) { + this._settings = _settings; + } + + getTransformer() { + return entry => this._transform(entry); + } + + _transform(entry) { + let filepath = entry.path; + + if (this._settings.absolute) { + filepath = utils$3.path.makeAbsolute(this._settings.cwd, filepath); + filepath = utils$3.path.unixify(filepath); + } + + if (this._settings.markDirectories && entry.dirent.isDirectory()) { + filepath += '/'; + } + + if (!this._settings.objectMode) { + return filepath; + } + + return Object.assign(Object.assign({}, entry), { + path: filepath + }); + } + + } + + exports.default = EntryTransformer; +}); + +var provider = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class Provider { + constructor(_settings) { + this._settings = _settings; + this.errorFilter = new error.default(this._settings); + this.entryFilter = new entry.default(this._settings, this._getMicromatchOptions()); + this.deepFilter = new deep.default(this._settings, this._getMicromatchOptions()); + this.entryTransformer = new entry$1.default(this._settings); + } + + _getRootDirectory(task) { + return path__default['default'].resolve(this._settings.cwd, task.base); + } + + _getReaderOptions(task) { + const basePath = task.base === '.' ? '' : task.base; + return { + basePath, + pathSegmentSeparator: '/', + concurrency: this._settings.concurrency, + deepFilter: this.deepFilter.getFilter(basePath, task.positive, task.negative), + entryFilter: this.entryFilter.getFilter(task.positive, task.negative), + errorFilter: this.errorFilter.getFilter(), + followSymbolicLinks: this._settings.followSymbolicLinks, + fs: this._settings.fs, + stats: this._settings.stats, + throwErrorOnBrokenSymbolicLink: this._settings.throwErrorOnBrokenSymbolicLink, + transform: this.entryTransformer.getTransformer() + }; + } + + _getMicromatchOptions() { + return { + dot: this._settings.dot, + matchBase: this._settings.baseNameMatch, + nobrace: !this._settings.braceExpansion, + nocase: !this._settings.caseSensitiveMatch, + noext: !this._settings.extglob, + noglobstar: !this._settings.globstar, + posix: true, + strictSlashes: false + }; + } + + } + + exports.default = Provider; +}); + +var async$5 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ProviderAsync extends provider.default { + constructor() { + super(...arguments); + this._reader = new stream$3.default(this._settings); + } + + read(task) { + const root = this._getRootDirectory(task); + + const options = this._getReaderOptions(task); + + const entries = []; + return new Promise((resolve, reject) => { + const stream = this.api(root, task, options); + stream.once('error', reject); + stream.on('data', entry => entries.push(options.transform(entry))); + stream.once('end', () => resolve(entries)); + }); + } + + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + + return this._reader.static(task.patterns, options); + } + + } + + exports.default = ProviderAsync; +}); + +var stream$4 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ProviderStream extends provider.default { + constructor() { + super(...arguments); + this._reader = new stream$3.default(this._settings); + } + + read(task) { + const root = this._getRootDirectory(task); + + const options = this._getReaderOptions(task); + + const source = this.api(root, task, options); + const destination = new stream__default['default'].Readable({ + objectMode: true, + read: () => {} + }); + source.once('error', error => destination.emit('error', error)).on('data', entry => destination.emit('data', options.transform(entry))).once('end', () => destination.emit('end')); + destination.once('close', () => source.destroy()); + return destination; + } + + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + + return this._reader.static(task.patterns, options); + } + + } + + exports.default = ProviderStream; +}); + +var sync$5 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ReaderSync extends reader$1.default { + constructor() { + super(...arguments); + this._walkSync = out$2.walkSync; + this._statSync = out.statSync; + } + + dynamic(root, options) { + return this._walkSync(root, options); + } + + static(patterns, options) { + const entries = []; + + for (const pattern of patterns) { + const filepath = this._getFullEntryPath(pattern); + + const entry = this._getEntry(filepath, pattern, options); + + if (entry === null || !options.entryFilter(entry)) { + continue; + } + + entries.push(entry); + } + + return entries; + } + + _getEntry(filepath, pattern, options) { + try { + const stats = this._getStat(filepath); + + return this._makeEntry(stats, pattern); + } catch (error) { + if (options.errorFilter(error)) { + return null; + } + + throw error; + } + } + + _getStat(filepath) { + return this._statSync(filepath, this._fsStatSettings); + } + + } + + exports.default = ReaderSync; +}); + +var sync$6 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + + class ProviderSync extends provider.default { + constructor() { + super(...arguments); + this._reader = new sync$5.default(this._settings); + } + + read(task) { + const root = this._getRootDirectory(task); + + const options = this._getReaderOptions(task); + + const entries = this.api(root, task, options); + return entries.map(options.transform); + } + + api(root, task, options) { + if (task.dynamic) { + return this._reader.dynamic(root, options); + } + + return this._reader.static(task.patterns, options); + } + + } + + exports.default = ProviderSync; +}); + +var settings$3 = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports.DEFAULT_FILE_SYSTEM_ADAPTER = void 0; + const CPU_COUNT = os__default['default'].cpus().length; + exports.DEFAULT_FILE_SYSTEM_ADAPTER = { + lstat: fs__default['default'].lstat, + lstatSync: fs__default['default'].lstatSync, + stat: fs__default['default'].stat, + statSync: fs__default['default'].statSync, + readdir: fs__default['default'].readdir, + readdirSync: fs__default['default'].readdirSync + }; + + class Settings { + constructor(_options = {}) { + this._options = _options; + this.absolute = this._getValue(this._options.absolute, false); + this.baseNameMatch = this._getValue(this._options.baseNameMatch, false); + this.braceExpansion = this._getValue(this._options.braceExpansion, true); + this.caseSensitiveMatch = this._getValue(this._options.caseSensitiveMatch, true); + this.concurrency = this._getValue(this._options.concurrency, CPU_COUNT); + this.cwd = this._getValue(this._options.cwd, process.cwd()); + this.deep = this._getValue(this._options.deep, Infinity); + this.dot = this._getValue(this._options.dot, false); + this.extglob = this._getValue(this._options.extglob, true); + this.followSymbolicLinks = this._getValue(this._options.followSymbolicLinks, true); + this.fs = this._getFileSystemMethods(this._options.fs); + this.globstar = this._getValue(this._options.globstar, true); + this.ignore = this._getValue(this._options.ignore, []); + this.markDirectories = this._getValue(this._options.markDirectories, false); + this.objectMode = this._getValue(this._options.objectMode, false); + this.onlyDirectories = this._getValue(this._options.onlyDirectories, false); + this.onlyFiles = this._getValue(this._options.onlyFiles, true); + this.stats = this._getValue(this._options.stats, false); + this.suppressErrors = this._getValue(this._options.suppressErrors, false); + this.throwErrorOnBrokenSymbolicLink = this._getValue(this._options.throwErrorOnBrokenSymbolicLink, false); + this.unique = this._getValue(this._options.unique, true); + + if (this.onlyDirectories) { + this.onlyFiles = false; + } + + if (this.stats) { + this.objectMode = true; + } + } + + _getValue(option, value) { + return option === undefined ? value : option; + } + + _getFileSystemMethods(methods = {}) { + return Object.assign(Object.assign({}, exports.DEFAULT_FILE_SYSTEM_ADAPTER), methods); + } + + } + + exports.default = Settings; +}); + +async function FastGlob(source, options) { + assertPatternsInput(source); + const works = getWorks(source, async$5.default, options); + const result = await Promise.all(works); + return utils$3.array.flatten(result); +} // https://github.com/typescript-eslint/typescript-eslint/issues/60 +// eslint-disable-next-line no-redeclare + + +(function (FastGlob) { + function sync(source, options) { + assertPatternsInput(source); + const works = getWorks(source, sync$6.default, options); + return utils$3.array.flatten(works); + } + + FastGlob.sync = sync; + + function stream(source, options) { + assertPatternsInput(source); + const works = getWorks(source, stream$4.default, options); + /** + * The stream returned by the provider cannot work with an asynchronous iterator. + * To support asynchronous iterators, regardless of the number of tasks, we always multiplex streams. + * This affects performance (+25%). I don't see best solution right now. + */ + + return utils$3.stream.merge(works); + } + + FastGlob.stream = stream; + + function generateTasks(source, options) { + assertPatternsInput(source); + const patterns = [].concat(source); + const settings = new settings$3.default(options); + return tasks.generate(patterns, settings); + } + + FastGlob.generateTasks = generateTasks; + + function isDynamicPattern(source, options) { + assertPatternsInput(source); + const settings = new settings$3.default(options); + return utils$3.pattern.isDynamicPattern(source, settings); + } + + FastGlob.isDynamicPattern = isDynamicPattern; + + function escapePath(source) { + assertPatternsInput(source); + return utils$3.path.escape(source); + } + + FastGlob.escapePath = escapePath; +})(FastGlob || (FastGlob = {})); + +function getWorks(source, _Provider, options) { + const patterns = [].concat(source); + const settings = new settings$3.default(options); + const tasks$1 = tasks.generate(patterns, settings); + const provider = new _Provider(settings); + return tasks$1.map(provider.read, provider); +} + +function assertPatternsInput(input) { + const source = [].concat(input); + const isValidSource = source.every(item => utils$3.string.isString(item) && !utils$3.string.isEmpty(item)); + + if (!isValidSource) { + throw new TypeError('Patterns must be a string (non empty) or an array of strings'); + } +} + +var out$3 = FastGlob; + +const { + promisify +} = util__default['default']; + +async function isType(fsStatType, statsMethodName, filePath) { + if (typeof filePath !== 'string') { + throw new TypeError(`Expected a string, got ${typeof filePath}`); + } + + try { + const stats = await promisify(fs__default['default'][fsStatType])(filePath); + return stats[statsMethodName](); + } catch (error) { + if (error.code === 'ENOENT') { + return false; + } + + throw error; + } +} + +function isTypeSync(fsStatType, statsMethodName, filePath) { + if (typeof filePath !== 'string') { + throw new TypeError(`Expected a string, got ${typeof filePath}`); + } + + try { + return fs__default['default'][fsStatType](filePath)[statsMethodName](); + } catch (error) { + if (error.code === 'ENOENT') { + return false; + } + + throw error; + } +} + +var isFile = isType.bind(null, 'stat', 'isFile'); +var isDirectory = isType.bind(null, 'stat', 'isDirectory'); +var isSymlink = isType.bind(null, 'lstat', 'isSymbolicLink'); +var isFileSync = isTypeSync.bind(null, 'statSync', 'isFile'); +var isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory'); +var isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink'); +var pathType = { + isFile: isFile, + isDirectory: isDirectory, + isSymlink: isSymlink, + isFileSync: isFileSync, + isDirectorySync: isDirectorySync, + isSymlinkSync: isSymlinkSync +}; + +const getExtensions = extensions => extensions.length > 1 ? `{${extensions.join(',')}}` : extensions[0]; + +const getPath = (filepath, cwd) => { + const pth = filepath[0] === '!' ? filepath.slice(1) : filepath; + return path__default['default'].isAbsolute(pth) ? pth : path__default['default'].join(cwd, pth); +}; + +const addExtensions = (file, extensions) => { + if (path__default['default'].extname(file)) { + return `**/${file}`; + } + + return `**/${file}.${getExtensions(extensions)}`; +}; + +const getGlob = (directory, options) => { + if (options.files && !Array.isArray(options.files)) { + throw new TypeError(`Expected \`files\` to be of type \`Array\` but received type \`${typeof options.files}\``); + } + + if (options.extensions && !Array.isArray(options.extensions)) { + throw new TypeError(`Expected \`extensions\` to be of type \`Array\` but received type \`${typeof options.extensions}\``); + } + + if (options.files && options.extensions) { + return options.files.map(x => path__default['default'].posix.join(directory, addExtensions(x, options.extensions))); + } + + if (options.files) { + return options.files.map(x => path__default['default'].posix.join(directory, `**/${x}`)); + } + + if (options.extensions) { + return [path__default['default'].posix.join(directory, `**/*.${getExtensions(options.extensions)}`)]; + } + + return [path__default['default'].posix.join(directory, '**')]; +}; + +var dirGlob = async (input, options) => { + options = Object.assign({ + cwd: process.cwd() + }, options); + + if (typeof options.cwd !== 'string') { + throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); + } + + const globs = await Promise.all([].concat(input).map(async x => { + const isDirectory = await pathType.isDirectory(getPath(x, options.cwd)); + return isDirectory ? getGlob(x, options) : x; + })); + return [].concat.apply([], globs); // eslint-disable-line prefer-spread +}; + +var sync$7 = (input, options) => { + options = Object.assign({ + cwd: process.cwd() + }, options); + + if (typeof options.cwd !== 'string') { + throw new TypeError(`Expected \`cwd\` to be of type \`string\` but received type \`${typeof options.cwd}\``); + } + + const globs = [].concat(input).map(x => pathType.isDirectorySync(getPath(x, options.cwd)) ? getGlob(x, options) : x); + return [].concat.apply([], globs); // eslint-disable-line prefer-spread +}; +dirGlob.sync = sync$7; + +// A simple implementation of make-array +function makeArray(subject) { + return Array.isArray(subject) ? subject : [subject]; +} + +const EMPTY = ''; +const SPACE = ' '; +const ESCAPE = '\\'; +const REGEX_TEST_BLANK_LINE = /^\s+$/; +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/; +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/; +const REGEX_SPLITALL_CRLF = /\r?\n/g; // /foo, +// ./foo, +// ../foo, +// . +// .. + +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/; +const SLASH$1 = '/'; +const KEY_IGNORE$1 = typeof Symbol !== 'undefined' ? Symbol.for('node-ignore') +/* istanbul ignore next */ +: 'node-ignore'; + +const define$1 = (object, key, value) => Object.defineProperty(object, key, { + value +}); + +const REGEX_REGEXP_RANGE$1 = /([0-z])-([0-z])/g; // Sanitize the range of a regular expression +// The cases are complicated, see test cases for details + +const sanitizeRange$1 = range => range.replace(REGEX_REGEXP_RANGE$1, (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match // Invalid range (out of order) which is ok for gitignore rules but +// fatal for JavaScript regular expression, so eliminate it. +: EMPTY); // See fixtures #59 + + +const cleanRangeBackSlash = slashes => { + const { + length + } = slashes; + return slashes.slice(0, length - length % 2); +}; // > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` +// '`foo/`' should not continue with the '`..`' + + +const REPLACERS = [// > Trailing spaces are ignored unless they are quoted with backslash ("\") +[// (a\ ) -> (a ) +// (a ) -> (a) +// (a \ ) -> (a ) +/\\?\s+$/, match => match.indexOf('\\') === 0 ? SPACE : EMPTY], // replace (\ ) with ' ' +[/\\\s/g, () => SPACE], // Escape metacharacters +// which is written down by users but means special for regular expressions. +// > There are 12 characters with special meanings: +// > - the backslash \, +// > - the caret ^, +// > - the dollar sign $, +// > - the period or dot ., +// > - the vertical bar or pipe symbol |, +// > - the question mark ?, +// > - the asterisk or star *, +// > - the plus sign +, +// > - the opening parenthesis (, +// > - the closing parenthesis ), +// > - and the opening square bracket [, +// > - the opening curly brace {, +// > These special characters are often called "metacharacters". +[/[\\$.|*+(){^]/g, match => `\\${match}`], [// > a question mark (?) matches a single character +/(?!\\)\?/g, () => '[^/]'], // leading slash +[// > A leading slash matches the beginning of the pathname. +// > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". +// A leading slash matches the beginning of the pathname +/^\//, () => '^'], // replace special metacharacter slash after the leading slash +[/\//g, () => '\\/'], [// > A leading "**" followed by a slash means match in all directories. +// > For example, "**/foo" matches file or directory "foo" anywhere, +// > the same as pattern "foo". +// > "**/foo/bar" matches file or directory "bar" anywhere that is directly +// > under directory "foo". +// Notice that the '*'s have been replaced as '\\*' +/^\^*\\\*\\\*\\\//, // '**/foo' <-> 'foo' +() => '^(?:.*\\/)?'], // starting +[// there will be no leading '/' +// (which has been replaced by section "leading slash") +// If starts with '**', adding a '^' to the regular expression also works +/^(?=[^^])/, function startingReplacer() { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^'; +}], // two globstars +[// Use lookahead assertions so that we could match more than one `'/**'` +/\\\/\\\*\\\*(?=\\\/|$)/g, // Zero, one or several directories +// should not use '*', or it will be replaced by the next replacer +// Check if it is not the last `'/**'` +(_, index, str) => index + 6 < str.length // case: /**/ +// > A slash followed by two consecutive asterisks then a slash matches +// > zero or more directories. +// > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. +// '/**/' +? '(?:\\/[^\\/]+)*' // case: /** +// > A trailing `"/**"` matches everything inside. +// #21: everything inside but it should not include the current folder +: '\\/.+'], // intermediate wildcards +[// Never replace escaped '*' +// ignore rule '\*' will match the path '*' +// 'abc.*/' -> go +// 'abc.*' -> skip this rule +/(^|[^\\]+)\\\*(?=.+)/g, // '*.js' matches '.js' +// '*.js' doesn't match 'abc' +(_, p1) => `${p1}[^\\/]*`], [// unescape, revert step 3 except for back slash +// For example, if a user escape a '\\*', +// after step 3, the result will be '\\\\\\*' +/\\\\\\(?=[$.|*+(){^])/g, () => ESCAPE], [// '\\\\' -> '\\' +/\\\\/g, () => ESCAPE], [// > The range notation, e.g. [a-zA-Z], +// > can be used to match one of the characters in a range. +// `\` is escaped by step 3 +/(\\)?\[([^\]/]*?)(\\*)($|\])/g, (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE // '\\[bar]' -> '\\\\[bar\\]' +? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === ']' ? endEscape.length % 2 === 0 // A normal case, and it is a range notation +// '[bar]' +// '[bar\\\\]' +? `[${sanitizeRange$1(range)}${endEscape}]` // Invalid range notaton +// '[bar\\]' -> '[bar\\\\]' +: '[]' : '[]'], // ending +[// 'js' will not match 'js.' +// 'ab' will not match 'abc' +/(?:[^*])$/, // WTF! +// https://git-scm.com/docs/gitignore +// changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) +// which re-fixes #24, #38 +// > If there is a separator at the end of the pattern then the pattern +// > will only match directories, otherwise the pattern can match both +// > files and directories. +// 'js*' will not match 'a.js' +// 'js/' will not match 'a.js' +// 'js' will match 'a.js' and 'a.js/' +match => /\/$/.test(match) // foo/ will not match 'foo' +? `${match}$` // foo matches 'foo' and 'foo/' +: `${match}(?=$|\\/$)`], // trailing wildcard +[/(\^|\\\/)?\\\*$/, (_, p1) => { + const prefix = p1 // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*'; + return `${prefix}(?=$|\\/$)`; +}]]; // A simple cache, because an ignore rule only has only one certain meaning + +const regexCache = Object.create(null); // @param {pattern} + +const makeRegex = (pattern, negative, ignorecase) => { + const r = regexCache[pattern]; + + if (r) { + return r; + } // const replacers = negative + // ? NEGATIVE_REPLACERS + // : POSITIVE_REPLACERS + + + const source = REPLACERS.reduce((prev, current) => prev.replace(current[0], current[1].bind(pattern)), pattern); + return regexCache[pattern] = ignorecase ? new RegExp(source, 'i') : new RegExp(source); +}; + +const isString = subject => typeof subject === 'string'; // > A blank line matches no files, so it can serve as a separator for readability. + + +const checkPattern$1 = pattern => pattern && isString(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) // > A line starting with # serves as a comment. +&& pattern.indexOf('#') !== 0; + +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF); + +class IgnoreRule { + constructor(origin, pattern, negative, regex) { + this.origin = origin; + this.pattern = pattern; + this.negative = negative; + this.regex = regex; + } + +} + +const createRule$1 = (pattern, ignorecase) => { + const origin = pattern; + let negative = false; // > An optional prefix "!" which negates the pattern; + + if (pattern.indexOf('!') === 0) { + negative = true; + pattern = pattern.substr(1); + } + + pattern = pattern // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#'); + const regex = makeRegex(pattern, negative, ignorecase); + return new IgnoreRule(origin, pattern, negative, regex); +}; + +const throwError = (message, Ctor) => { + throw new Ctor(message); +}; + +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow(`path must be a string, but got \`${originalPath}\``, TypeError); + } // We don't know if we should ignore EMPTY, so throw + + + if (!path) { + return doThrow(`path must not be empty`, TypeError); + } // Check if it is a relative path + + + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d'; + return doThrow(`path should be a ${r} string, but got "${originalPath}"`, RangeError); + } + + return true; +}; + +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path); + +checkPath.isNotRelative = isNotRelative; + +checkPath.convert = p => p; + +class Ignore { + constructor({ + ignorecase = true + } = {}) { + this._rules = []; + this._ignorecase = ignorecase; + define$1(this, KEY_IGNORE$1, true); + + this._initCache(); + } + + _initCache() { + this._ignoreCache = Object.create(null); + this._testCache = Object.create(null); + } + + _addPattern(pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE$1]) { + this._rules = this._rules.concat(pattern._rules); + this._added = true; + return; + } + + if (checkPattern$1(pattern)) { + const rule = createRule$1(pattern, this._ignorecase); + this._added = true; + + this._rules.push(rule); + } + } // @param {Array | string | Ignore} pattern + + + add(pattern) { + this._added = false; + makeArray(isString(pattern) ? splitPattern(pattern) : pattern).forEach(this._addPattern, this); // Some rules have just added to the ignore, + // making the behavior changed. + + if (this._added) { + this._initCache(); + } + + return this; + } // legacy + + + addPattern(pattern) { + return this.add(pattern); + } // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. + // @returns {TestResult} true if a file is ignored + + + _testOne(path, checkUnignored) { + let ignored = false; + let unignored = false; + + this._rules.forEach(rule => { + const { + negative + } = rule; + + if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) { + return; + } + + const matched = rule.regex.test(path); + + if (matched) { + ignored = !negative; + unignored = negative; + } + }); + + return { + ignored, + unignored + }; + } // @returns {TestResult} + + + _test(originalPath, cache, checkUnignored, slices) { + const path = originalPath // Supports nullable path + && checkPath.convert(originalPath); + checkPath(path, originalPath, throwError); + return this._t(path, cache, checkUnignored, slices); + } + + _t(path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path]; + } + + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH$1); + } + + slices.pop(); // If the path has no parent directory, just test it + + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored); + } + + const parent = this._t(slices.join(SLASH$1) + SLASH$1, cache, checkUnignored, slices); // If the path contains a parent directory, check the parent first + + + return cache[path] = parent.ignored // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent : this._testOne(path, checkUnignored); + } + + ignores(path) { + return this._test(path, this._ignoreCache, false).ignored; + } + + createFilter() { + return path => !this.ignores(path); + } + + filter(paths) { + return makeArray(paths).filter(this.createFilter()); + } // @returns {TestResult} + + + test(path) { + return this._test(path, this._testCache, true); + } + +} + +const factory = options => new Ignore(options); + +const returnFalse = () => false; + +const isPathValid = path => checkPath(path && checkPath.convert(path), path, returnFalse); + +factory.isPathValid = isPathValid; // Fixes typescript + +factory.default = factory; +var ignore$1 = factory; // Windows +// -------------------------------------------------------------- + +/* istanbul ignore if */ + +if ( // Detect `process` so that it can run in browsers. +typeof process !== 'undefined' && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === 'win32')) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, '/'); + + checkPath.convert = makePosix; // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i; + + checkPath.isNotRelative = path => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) || isNotRelative(path); +} + +var slash$1 = path => { + const isExtendedLengthPath = /^\\\\\?\\/.test(path); + const hasNonAscii = /[^\u0000-\u0080]+/.test(path); // eslint-disable-line no-control-regex + + if (isExtendedLengthPath || hasNonAscii) { + return path; + } + + return path.replace(/\\/g, '/'); +}; + +const { + promisify: promisify$1 +} = util__default['default']; +const DEFAULT_IGNORE = ['**/node_modules/**', '**/flow-typed/**', '**/coverage/**', '**/.git']; +const readFileP = promisify$1(fs__default['default'].readFile); + +const mapGitIgnorePatternTo = base => ignore => { + if (ignore.startsWith('!')) { + return '!' + path__default['default'].posix.join(base, ignore.slice(1)); + } + + return path__default['default'].posix.join(base, ignore); +}; + +const parseGitIgnore = (content, options) => { + const base = slash$1(path__default['default'].relative(options.cwd, path__default['default'].dirname(options.fileName))); + return content.split(/\r?\n/).filter(Boolean).filter(line => !line.startsWith('#')).map(mapGitIgnorePatternTo(base)); +}; + +const reduceIgnore = files => { + return files.reduce((ignores, file) => { + ignores.add(parseGitIgnore(file.content, { + cwd: file.cwd, + fileName: file.filePath + })); + return ignores; + }, ignore$1()); +}; + +const ensureAbsolutePathForCwd = (cwd, p) => { + cwd = slash$1(cwd); + + if (path__default['default'].isAbsolute(p)) { + if (p.startsWith(cwd)) { + return p; + } + + throw new Error(`Path ${p} is not in cwd ${cwd}`); + } + + return path__default['default'].join(cwd, p); +}; + +const getIsIgnoredPredecate = (ignores, cwd) => { + return p => ignores.ignores(slash$1(path__default['default'].relative(cwd, ensureAbsolutePathForCwd(cwd, p)))); +}; + +const getFile = async (file, cwd) => { + const filePath = path__default['default'].join(cwd, file); + const content = await readFileP(filePath, 'utf8'); + return { + cwd, + filePath, + content + }; +}; + +const getFileSync = (file, cwd) => { + const filePath = path__default['default'].join(cwd, file); + const content = fs__default['default'].readFileSync(filePath, 'utf8'); + return { + cwd, + filePath, + content + }; +}; + +const normalizeOptions$3 = ({ + ignore = [], + cwd = slash$1(process.cwd()) +} = {}) => { + return { + ignore, + cwd + }; +}; + +var gitignore = async options => { + options = normalizeOptions$3(options); + const paths = await out$3('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }); + const files = await Promise.all(paths.map(file => getFile(file, options.cwd))); + const ignores = reduceIgnore(files); + return getIsIgnoredPredecate(ignores, options.cwd); +}; + +var sync$8 = options => { + options = normalizeOptions$3(options); + const paths = out$3.sync('**/.gitignore', { + ignore: DEFAULT_IGNORE.concat(options.ignore), + cwd: options.cwd + }); + const files = paths.map(file => getFileSync(file, options.cwd)); + const ignores = reduceIgnore(files); + return getIsIgnoredPredecate(ignores, options.cwd); +}; +gitignore.sync = sync$8; + +const { + Transform +} = stream__default['default']; + +class ObjectTransform extends Transform { + constructor() { + super({ + objectMode: true + }); + } + +} + +class FilterStream extends ObjectTransform { + constructor(filter) { + super(); + this._filter = filter; + } + + _transform(data, encoding, callback) { + if (this._filter(data)) { + this.push(data); + } + + callback(); + } + +} + +class UniqueStream extends ObjectTransform { + constructor() { + super(); + this._pushed = new Set(); + } + + _transform(data, encoding, callback) { + if (!this._pushed.has(data)) { + this.push(data); + + this._pushed.add(data); + } + + callback(); + } + +} + +var streamUtils = { + FilterStream, + UniqueStream +}; + +const { + FilterStream: FilterStream$1, + UniqueStream: UniqueStream$1 +} = streamUtils; + +const DEFAULT_FILTER = () => false; + +const isNegative = pattern => pattern[0] === '!'; + +const assertPatternsInput$1 = patterns => { + if (!patterns.every(pattern => typeof pattern === 'string')) { + throw new TypeError('Patterns must be a string or an array of strings'); + } +}; + +const checkCwdOption = (options = {}) => { + if (!options.cwd) { + return; + } + + let stat; + + try { + stat = fs__default['default'].statSync(options.cwd); + } catch (_) { + return; + } + + if (!stat.isDirectory()) { + throw new Error('The `cwd` option must be a path to a directory'); + } +}; + +const getPathString = p => p.stats instanceof fs__default['default'].Stats ? p.path : p; + +const generateGlobTasks = (patterns, taskOptions) => { + patterns = arrayUnion([].concat(patterns)); + assertPatternsInput$1(patterns); + checkCwdOption(taskOptions); + const globTasks = []; + taskOptions = Object.assign({ + ignore: [], + expandDirectories: true + }, taskOptions); + + for (const [index, pattern] of patterns.entries()) { + if (isNegative(pattern)) { + continue; + } + + const ignore = patterns.slice(index).filter(isNegative).map(pattern => pattern.slice(1)); + const options = Object.assign({}, taskOptions, { + ignore: taskOptions.ignore.concat(ignore) + }); + globTasks.push({ + pattern, + options + }); + } + + return globTasks; +}; + +const globDirs = (task, fn) => { + let options = {}; + + if (task.options.cwd) { + options.cwd = task.options.cwd; + } + + if (Array.isArray(task.options.expandDirectories)) { + options = Object.assign({}, options, { + files: task.options.expandDirectories + }); + } else if (typeof task.options.expandDirectories === 'object') { + options = Object.assign({}, options, task.options.expandDirectories); + } + + return fn(task.pattern, options); +}; + +const getPattern = (task, fn) => task.options.expandDirectories ? globDirs(task, fn) : [task.pattern]; + +const getFilterSync = options => { + return options && options.gitignore ? gitignore.sync({ + cwd: options.cwd, + ignore: options.ignore + }) : DEFAULT_FILTER; +}; + +const globToTask = task => glob => { + const { + options + } = task; + + if (options.ignore && Array.isArray(options.ignore) && options.expandDirectories) { + options.ignore = dirGlob.sync(options.ignore); + } + + return { + pattern: glob, + options + }; +}; + +var globby$1 = async (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); + + const getFilter = async () => { + return options && options.gitignore ? gitignore({ + cwd: options.cwd, + ignore: options.ignore + }) : DEFAULT_FILTER; + }; + + const getTasks = async () => { + const tasks = await Promise.all(globTasks.map(async task => { + const globs = await getPattern(task, dirGlob); + return Promise.all(globs.map(globToTask(task))); + })); + return arrayUnion(...tasks); + }; + + const [filter, tasks] = await Promise.all([getFilter(), getTasks()]); + const paths = await Promise.all(tasks.map(task => out$3(task.pattern, task.options))); + return arrayUnion(...paths).filter(path_ => !filter(getPathString(path_))); +}; + +var sync$9 = (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); + const tasks = globTasks.reduce((tasks, task) => { + const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); + return tasks.concat(newTask); + }, []); + const filter = getFilterSync(options); + return tasks.reduce((matches, task) => arrayUnion(matches, out$3.sync(task.pattern, task.options)), []).filter(path_ => !filter(path_)); +}; + +var stream$5 = (patterns, options) => { + const globTasks = generateGlobTasks(patterns, options); + const tasks = globTasks.reduce((tasks, task) => { + const newTask = getPattern(task, dirGlob.sync).map(globToTask(task)); + return tasks.concat(newTask); + }, []); + const filter = getFilterSync(options); + const filterStream = new FilterStream$1(p => !filter(p)); + const uniqueStream = new UniqueStream$1(); + return merge2_1(tasks.map(task => out$3.stream(task.pattern, task.options))).pipe(filterStream).pipe(uniqueStream); +}; + +var generateGlobTasks_1 = generateGlobTasks; + +var hasMagic = (patterns, options) => [].concat(patterns).some(pattern => out$3.isDynamicPattern(pattern, options)); + +var gitignore_1 = gitignore; +globby$1.sync = sync$9; +globby$1.stream = stream$5; +globby$1.generateGlobTasks = generateGlobTasks_1; +globby$1.hasMagic = hasMagic; +globby$1.gitignore = gitignore_1; + +var createLanguage = function (linguistData, override) { + const { + languageId + } = linguistData, + rest = _objectWithoutPropertiesLoose(linguistData, ["languageId"]); + + return Object.assign({ + linguistLanguageId: languageId + }, rest, override(linguistData)); +}; + +const { + getLast: getLast$1, + hasNewline: hasNewline$3, + getNextNonSpaceNonCommentCharacterIndexWithStartIndex: getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1, + getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$1, + hasNewlineInRange: hasNewlineInRange$2, + isNodeIgnoreComment: isNodeIgnoreComment$1, + addLeadingComment: addLeadingComment$3, + addTrailingComment: addTrailingComment$3, + addDanglingComment: addDanglingComment$3, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$2 +} = util; + +function handleOwnLineComment(comment, text, options, ast, isLastComment) { + const { + precedingNode, + enclosingNode, + followingNode + } = comment; + return handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleMemberExpressionComments(enclosingNode, followingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleImportSpecifierComments(enclosingNode, comment) || handleForComments(enclosingNode, precedingNode, comment) || handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) || handleAssignmentPatternComments(enclosingNode, comment) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleLabeledStatementComments(enclosingNode, comment); +} + +function handleEndOfLineComment(comment, text, options, ast, isLastComment) { + const { + precedingNode, + enclosingNode, + followingNode + } = comment; + return handleClosureTypeCastComments(followingNode, comment) || handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) || handleImportSpecifierComments(enclosingNode, comment) || handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) || handleClassComments(enclosingNode, precedingNode, followingNode, comment) || handleLabeledStatementComments(enclosingNode, comment) || handleCallExpressionComments(precedingNode, enclosingNode, comment) || handlePropertyComments(enclosingNode, comment) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleTypeAliasComments(enclosingNode, followingNode, comment) || handleVariableDeclaratorComments(enclosingNode, followingNode, comment); +} + +function handleRemainingComment(comment, text, options, ast, isLastComment) { + const { + precedingNode, + enclosingNode, + followingNode + } = comment; + + if (handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) || handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) || handleCommentInEmptyParens(text, enclosingNode, comment, options) || handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) || handleOnlyComments(enclosingNode, ast, comment, isLastComment) || handleCommentAfterArrowParams(text, enclosingNode, comment, options) || handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) || handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) || handleBreakAndContinueStatementComments(enclosingNode, comment) || handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options)) { + return true; + } + + return false; +} + +function addBlockStatementFirstComment(node, comment) { + const body = (node.body || node.properties).filter(n => n.type !== "EmptyStatement"); + + if (body.length === 0) { + addDanglingComment$3(node, comment); + } else { + addLeadingComment$3(body[0], comment); + } +} + +function addBlockOrNotComment(node, comment) { + if (node.type === "BlockStatement") { + addBlockStatementFirstComment(node, comment); + } else { + addLeadingComment$3(node, comment); + } +} + +function handleClosureTypeCastComments(followingNode, comment) { + if (followingNode && isTypeCastComment(comment)) { + addLeadingComment$3(followingNode, comment); + return true; + } + + return false; +} // There are often comments before the else clause of if statements like +// +// if (1) { ... } +// // comment +// else { ... } +// +// They are being attached as leading comments of the BlockExpression which +// is not well printed. What we want is to instead move the comment inside +// of the block and make it leadingComment of the first element of the block +// or dangling comment of the block if there is nothing inside +// +// if (1) { ... } +// else { +// // comment +// ... +// } + + +function handleIfStatementComments(text, precedingNode, enclosingNode, followingNode, comment, options) { + if (!enclosingNode || enclosingNode.type !== "IfStatement" || !followingNode) { + return false; + } // We unfortunately have no way using the AST or location of nodes to know + // if the comment is positioned before the condition parenthesis: + // if (a /* comment */) {} + // The only workaround I found is to look at the next character to see if + // it is a ). + + + const nextCharacter = getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd); + + if (nextCharacter === ")") { + addTrailingComment$3(precedingNode, comment); + return true; + } // Comments before `else`: + // - treat as trailing comments of the consequent, if it's a BlockStatement + // - treat as a dangling comment otherwise + + + if (precedingNode === enclosingNode.consequent && followingNode === enclosingNode.alternate) { + if (precedingNode.type === "BlockStatement") { + addTrailingComment$3(precedingNode, comment); + } else { + addDanglingComment$3(enclosingNode, comment); + } + + return true; + } + + if (followingNode.type === "BlockStatement") { + addBlockStatementFirstComment(followingNode, comment); + return true; + } + + if (followingNode.type === "IfStatement") { + addBlockOrNotComment(followingNode.consequent, comment); + return true; + } // For comments positioned after the condition parenthesis in an if statement + // before the consequent without brackets on, such as + // if (a) /* comment */ true, + // we look at the next character to see if the following node + // is the consequent for the if statement + + + if (enclosingNode.consequent === followingNode) { + addLeadingComment$3(followingNode, comment); + return true; + } + + return false; +} + +function handleWhileComments(text, precedingNode, enclosingNode, followingNode, comment, options) { + if (!enclosingNode || enclosingNode.type !== "WhileStatement" || !followingNode) { + return false; + } // We unfortunately have no way using the AST or location of nodes to know + // if the comment is positioned before the condition parenthesis: + // while (a /* comment */) {} + // The only workaround I found is to look at the next character to see if + // it is a ). + + + const nextCharacter = getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd); + + if (nextCharacter === ")") { + addTrailingComment$3(precedingNode, comment); + return true; + } + + if (followingNode.type === "BlockStatement") { + addBlockStatementFirstComment(followingNode, comment); + return true; + } + + return false; +} // Same as IfStatement but for TryStatement + + +function handleTryStatementComments(enclosingNode, precedingNode, followingNode, comment) { + if (!enclosingNode || enclosingNode.type !== "TryStatement" && enclosingNode.type !== "CatchClause" || !followingNode) { + return false; + } + + if (enclosingNode.type === "CatchClause" && precedingNode) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + if (followingNode.type === "BlockStatement") { + addBlockStatementFirstComment(followingNode, comment); + return true; + } + + if (followingNode.type === "TryStatement") { + addBlockOrNotComment(followingNode.finalizer, comment); + return true; + } + + if (followingNode.type === "CatchClause") { + addBlockOrNotComment(followingNode.body, comment); + return true; + } + + return false; +} + +function handleMemberExpressionComments(enclosingNode, followingNode, comment) { + if (enclosingNode && (enclosingNode.type === "MemberExpression" || enclosingNode.type === "OptionalMemberExpression") && followingNode && followingNode.type === "Identifier") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleConditionalExpressionComments(enclosingNode, precedingNode, followingNode, comment, text, options) { + const isSameLineAsPrecedingNode = precedingNode && !hasNewlineInRange$2(text, options.locEnd(precedingNode), options.locStart(comment)); + + if ((!precedingNode || !isSameLineAsPrecedingNode) && enclosingNode && (enclosingNode.type === "ConditionalExpression" || enclosingNode.type === "TSConditionalType") && followingNode) { + addLeadingComment$3(followingNode, comment); + return true; + } + + return false; +} + +function handleObjectPropertyAssignment(enclosingNode, precedingNode, comment) { + if (enclosingNode && (enclosingNode.type === "ObjectProperty" || enclosingNode.type === "Property") && enclosingNode.shorthand && enclosingNode.key === precedingNode && enclosingNode.value.type === "AssignmentPattern") { + addTrailingComment$3(enclosingNode.value.left, comment); + return true; + } + + return false; +} + +function handleClassComments(enclosingNode, precedingNode, followingNode, comment) { + if (enclosingNode && (enclosingNode.type === "ClassDeclaration" || enclosingNode.type === "ClassExpression" || enclosingNode.type === "DeclareClass" || enclosingNode.type === "DeclareInterface" || enclosingNode.type === "InterfaceDeclaration" || enclosingNode.type === "TSInterfaceDeclaration")) { + if (enclosingNode.decorators && enclosingNode.decorators.length > 0 && !(followingNode && followingNode.type === "Decorator")) { + addTrailingComment$3(enclosingNode.decorators[enclosingNode.decorators.length - 1], comment); + return true; + } + + if (enclosingNode.body && followingNode === enclosingNode.body) { + addBlockStatementFirstComment(enclosingNode.body, comment); + return true; + } // Don't add leading comments to `implements`, `extends`, `mixins` to + // avoid printing the comment after the keyword. + + + if (followingNode) { + for (const prop of ["implements", "extends", "mixins"]) { + if (enclosingNode[prop] && followingNode === enclosingNode[prop][0]) { + if (precedingNode && (precedingNode === enclosingNode.id || precedingNode === enclosingNode.typeParameters || precedingNode === enclosingNode.superClass)) { + addTrailingComment$3(precedingNode, comment); + } else { + addDanglingComment$3(enclosingNode, comment, prop); + } + + return true; + } + } + } + } + + return false; +} + +function handleMethodNameComments(text, enclosingNode, precedingNode, comment, options) { + // This is only needed for estree parsers (flow, typescript) to attach + // after a method name: + // obj = { fn /*comment*/() {} }; + if (enclosingNode && precedingNode && ( // "MethodDefinition" is handled in getCommentChildNodes + enclosingNode.type === "Property" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "TSAbstractMethodDefinition") && precedingNode.type === "Identifier" && enclosingNode.key === precedingNode && // special Property case: { key: /*comment*/(value) }; + // comment should be attached to value instead of key + getNextNonSpaceNonCommentCharacter$1(text, precedingNode, options.locEnd) !== ":") { + addTrailingComment$3(precedingNode, comment); + return true; + } // Print comments between decorators and class methods as a trailing comment + // on the decorator node instead of the method node + + + if (precedingNode && enclosingNode && precedingNode.type === "Decorator" && (enclosingNode.type === "ClassMethod" || enclosingNode.type === "ClassProperty" || enclosingNode.type === "TSAbstractClassProperty" || enclosingNode.type === "TSAbstractMethodDefinition" || enclosingNode.type === "TSDeclareMethod" || enclosingNode.type === "MethodDefinition")) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + return false; +} + +function handleFunctionNameComments(text, enclosingNode, precedingNode, comment, options) { + if (getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd) !== "(") { + return false; + } + + if (precedingNode && enclosingNode && (enclosingNode.type === "FunctionDeclaration" || enclosingNode.type === "FunctionExpression" || enclosingNode.type === "ClassMethod" || enclosingNode.type === "MethodDefinition" || enclosingNode.type === "ObjectMethod")) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + return false; +} + +function handleCommentAfterArrowParams(text, enclosingNode, comment, options) { + if (!(enclosingNode && enclosingNode.type === "ArrowFunctionExpression")) { + return false; + } + + const index = getNextNonSpaceNonCommentCharacterIndex$2(text, comment, options.locEnd); + + if (index !== false && text.slice(index, index + 2) === "=>") { + addDanglingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleCommentInEmptyParens(text, enclosingNode, comment, options) { + if (getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd) !== ")") { + return false; + } // Only add dangling comments to fix the case when no params are present, + // i.e. a function without any argument. + + + if (enclosingNode && (isRealFunctionLikeNode(enclosingNode) && // `params` vs `parameters` - see https://github.com/babel/babel/issues/9231 + (enclosingNode.params || enclosingNode.parameters).length === 0 || (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression" || enclosingNode.type === "NewExpression") && enclosingNode.arguments.length === 0)) { + addDanglingComment$3(enclosingNode, comment); + return true; + } + + if (enclosingNode && enclosingNode.type === "MethodDefinition" && enclosingNode.value.params.length === 0) { + addDanglingComment$3(enclosingNode.value, comment); + return true; + } + + return false; +} + +function handleLastFunctionArgComments(text, precedingNode, enclosingNode, followingNode, comment, options) { + // Flow function type definitions + if (precedingNode && precedingNode.type === "FunctionTypeParam" && enclosingNode && enclosingNode.type === "FunctionTypeAnnotation" && followingNode && followingNode.type !== "FunctionTypeParam") { + addTrailingComment$3(precedingNode, comment); + return true; + } // Real functions and TypeScript function type definitions + + + if (precedingNode && (precedingNode.type === "Identifier" || precedingNode.type === "AssignmentPattern") && enclosingNode && isRealFunctionLikeNode(enclosingNode) && getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd) === ")") { + addTrailingComment$3(precedingNode, comment); + return true; + } + + if (enclosingNode && enclosingNode.type === "FunctionDeclaration" && followingNode && followingNode.type === "BlockStatement") { + const functionParamRightParenIndex = (() => { + if ((enclosingNode.params || enclosingNode.parameters).length !== 0) { + return getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, options.locEnd(getLast$1(enclosingNode.params || enclosingNode.parameters))); + } + + const functionParamLeftParenIndex = getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, options.locEnd(enclosingNode.id)); + return functionParamLeftParenIndex !== false && getNextNonSpaceNonCommentCharacterIndexWithStartIndex$1(text, functionParamLeftParenIndex + 1); + })(); + + if (options.locStart(comment) > functionParamRightParenIndex) { + addBlockStatementFirstComment(followingNode, comment); + return true; + } + } + + return false; +} + +function handleImportSpecifierComments(enclosingNode, comment) { + if (enclosingNode && enclosingNode.type === "ImportSpecifier") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleLabeledStatementComments(enclosingNode, comment) { + if (enclosingNode && enclosingNode.type === "LabeledStatement") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleBreakAndContinueStatementComments(enclosingNode, comment) { + if (enclosingNode && (enclosingNode.type === "ContinueStatement" || enclosingNode.type === "BreakStatement") && !enclosingNode.label) { + addTrailingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleCallExpressionComments(precedingNode, enclosingNode, comment) { + if (enclosingNode && (enclosingNode.type === "CallExpression" || enclosingNode.type === "OptionalCallExpression") && precedingNode && enclosingNode.callee === precedingNode && enclosingNode.arguments.length > 0) { + addLeadingComment$3(enclosingNode.arguments[0], comment); + return true; + } + + return false; +} + +function handleUnionTypeComments(precedingNode, enclosingNode, followingNode, comment) { + if (enclosingNode && (enclosingNode.type === "UnionTypeAnnotation" || enclosingNode.type === "TSUnionType")) { + if (isNodeIgnoreComment$1(comment)) { + followingNode.prettierIgnore = true; + comment.unignore = true; + } + + if (precedingNode) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + return false; + } + + if (followingNode && (followingNode.type === "UnionTypeAnnotation" || followingNode.type === "TSUnionType") && isNodeIgnoreComment$1(comment)) { + followingNode.types[0].prettierIgnore = true; + comment.unignore = true; + } + + return false; +} + +function handlePropertyComments(enclosingNode, comment) { + if (enclosingNode && (enclosingNode.type === "Property" || enclosingNode.type === "ObjectProperty")) { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleOnlyComments(enclosingNode, ast, comment, isLastComment) { + // With Flow the enclosingNode is undefined so use the AST instead. + if (ast && ast.body && ast.body.length === 0) { + if (isLastComment) { + addDanglingComment$3(ast, comment); + } else { + addLeadingComment$3(ast, comment); + } + + return true; + } else if (enclosingNode && enclosingNode.type === "Program" && enclosingNode.body.length === 0 && enclosingNode.directives && enclosingNode.directives.length === 0) { + if (isLastComment) { + addDanglingComment$3(enclosingNode, comment); + } else { + addLeadingComment$3(enclosingNode, comment); + } + + return true; + } + + return false; +} + +function handleForComments(enclosingNode, precedingNode, comment) { + if (enclosingNode && (enclosingNode.type === "ForInStatement" || enclosingNode.type === "ForOfStatement")) { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleImportDeclarationComments(text, enclosingNode, precedingNode, comment, options) { + if (precedingNode && precedingNode.type === "ImportSpecifier" && enclosingNode && enclosingNode.type === "ImportDeclaration" && hasNewline$3(text, options.locEnd(comment))) { + addTrailingComment$3(precedingNode, comment); + return true; + } + + return false; +} + +function handleAssignmentPatternComments(enclosingNode, comment) { + if (enclosingNode && enclosingNode.type === "AssignmentPattern") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleTypeAliasComments(enclosingNode, followingNode, comment) { + if (enclosingNode && enclosingNode.type === "TypeAlias") { + addLeadingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleVariableDeclaratorComments(enclosingNode, followingNode, comment) { + if (enclosingNode && (enclosingNode.type === "VariableDeclarator" || enclosingNode.type === "AssignmentExpression") && followingNode && (followingNode.type === "ObjectExpression" || followingNode.type === "ArrayExpression" || followingNode.type === "TemplateLiteral" || followingNode.type === "TaggedTemplateExpression" || isBlockComment(comment))) { + addLeadingComment$3(followingNode, comment); + return true; + } + + return false; +} + +function handleTSFunctionTrailingComments(text, enclosingNode, followingNode, comment, options) { + if (!followingNode && enclosingNode && (enclosingNode.type === "TSMethodSignature" || enclosingNode.type === "TSDeclareFunction" || enclosingNode.type === "TSAbstractMethodDefinition") && getNextNonSpaceNonCommentCharacter$1(text, comment, options.locEnd) === ";") { + addTrailingComment$3(enclosingNode, comment); + return true; + } + + return false; +} + +function handleTSMappedTypeComments(text, enclosingNode, precedingNode, followingNode, comment) { + if (!enclosingNode || enclosingNode.type !== "TSMappedType") { + return false; + } + + if (followingNode && followingNode.type === "TSTypeParameter" && followingNode.name) { + addLeadingComment$3(followingNode.name, comment); + return true; + } + + if (precedingNode && precedingNode.type === "TSTypeParameter" && precedingNode.constraint) { + addTrailingComment$3(precedingNode.constraint, comment); + return true; + } + + return false; +} + +function isBlockComment(comment) { + return comment.type === "Block" || comment.type === "CommentBlock"; +} +/** + * @param {any} node + * @param {(comment: any) => boolean} fn + * @returns boolean + */ + + +function hasLeadingComment(node, fn = () => true) { + if (node.leadingComments) { + return node.leadingComments.some(fn); + } + + if (node.comments) { + return node.comments.some(comment => comment.leading && fn(comment)); + } + + return false; +} + +function isRealFunctionLikeNode(node) { + return node.type === "ArrowFunctionExpression" || node.type === "FunctionExpression" || node.type === "FunctionDeclaration" || node.type === "ObjectMethod" || node.type === "ClassMethod" || node.type === "TSDeclareFunction" || node.type === "TSCallSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSConstructSignatureDeclaration" || node.type === "TSMethodSignature" || node.type === "TSConstructorType" || node.type === "TSFunctionType" || node.type === "TSDeclareMethod"; +} + +function getGapRegex(enclosingNode) { + if (enclosingNode && enclosingNode.type !== "BinaryExpression" && enclosingNode.type !== "LogicalExpression") { + // Support degenerate single-element unions and intersections. + // E.g.: `type A = /* 1 */ & B` + return /^[\s&(|]*$/; + } +} + +function getCommentChildNodes(node, options) { + // Prevent attaching comments to FunctionExpression in this case: + // class Foo { + // bar() // comment + // { + // baz(); + // } + // } + if ((options.parser === "typescript" || options.parser === "flow") && node.type === "MethodDefinition" && node.value && node.value.type === "FunctionExpression" && node.value.params.length === 0 && !node.value.returnType && (!node.value.typeParameters || node.value.typeParameters.length === 0) && node.value.body) { + return [...(node.decorators || []), node.key, node.value.body]; + } +} + +function isTypeCastComment(comment) { + return isBlockComment(comment) && comment.value[0] === "*" && // TypeScript expects the type to be enclosed in curly brackets, however + // Closure Compiler accepts types in parens and even without any delimiters at all. + // That's why we just search for "@type". + /@type\b/.test(comment.value); +} + +var comments$1 = { + handleOwnLineComment, + handleEndOfLineComment, + handleRemainingComment, + hasLeadingComment, + isBlockComment, + isTypeCastComment, + getGapRegex, + getCommentChildNodes +}; + +const { + builders: { + indent: indent$2, + join: join$2, + line: line$3, + hardline: hardline$3, + softline: softline$1, + literalline: literalline$2, + concat: concat$5, + group: group$1, + dedentToRoot: dedentToRoot$1 + }, + utils: { + mapDoc: mapDoc$1, + replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$1 + } +} = document; +const { + isBlockComment: isBlockComment$1, + hasLeadingComment: hasLeadingComment$1 +} = comments$1; + +function embed(path, print, textToDoc, options) { + const node = path.getValue(); + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + + switch (node.type) { + case "TemplateLiteral": + { + const isCss = [isStyledJsx, isStyledComponents, isCssProp, isAngularComponentStyles].some(isIt => isIt(path)); + + if (isCss) { + // Get full template literal with expressions replaced by placeholders + const rawQuasis = node.quasis.map(q => q.value.raw); + let placeholderID = 0; + const text = rawQuasis.reduce((prevVal, currVal, idx) => { + return idx === 0 ? currVal : prevVal + "@prettier-placeholder-" + placeholderID++ + "-id" + currVal; + }, ""); + const doc = textToDoc(text, { + parser: "scss" + }, { + stripTrailingHardline: true + }); + return transformCssDoc(doc, path, print); + } + /* + * react-relay and graphql-tag + * graphql`...` + * graphql.experimental`...` + * gql`...` + * + * This intentionally excludes Relay Classic tags, as Prettier does not + * support Relay Classic formatting. + */ + + + if (isGraphQL(path)) { + const expressionDocs = node.expressions ? path.map(print, "expressions") : []; + const numQuasis = node.quasis.length; + + if (numQuasis === 1 && node.quasis[0].value.raw.trim() === "") { + return "``"; + } + + const parts = []; + + for (let i = 0; i < numQuasis; i++) { + const templateElement = node.quasis[i]; + const isFirst = i === 0; + const isLast = i === numQuasis - 1; + const text = templateElement.value.cooked; // Bail out if any of the quasis have an invalid escape sequence + // (which would make the `cooked` value be `null` or `undefined`) + + if (typeof text !== "string") { + return null; + } + + const lines = text.split("\n"); + const numLines = lines.length; + const expressionDoc = expressionDocs[i]; + const startsWithBlankLine = numLines > 2 && lines[0].trim() === "" && lines[1].trim() === ""; + const endsWithBlankLine = numLines > 2 && lines[numLines - 1].trim() === "" && lines[numLines - 2].trim() === ""; + const commentsAndWhitespaceOnly = lines.every(line => /^\s*(?:#[^\n\r]*)?$/.test(line)); // Bail out if an interpolation occurs within a comment. + + if (!isLast && /#[^\n\r]*$/.test(lines[numLines - 1])) { + return null; + } + + let doc = null; + + if (commentsAndWhitespaceOnly) { + doc = printGraphqlComments(lines); + } else { + doc = textToDoc(text, { + parser: "graphql" + }, { + stripTrailingHardline: true + }); + } + + if (doc) { + doc = escapeTemplateCharacters(doc, false); + + if (!isFirst && startsWithBlankLine) { + parts.push(""); + } + + parts.push(doc); + + if (!isLast && endsWithBlankLine) { + parts.push(""); + } + } else if (!isFirst && !isLast && startsWithBlankLine) { + parts.push(""); + } + + if (expressionDoc) { + parts.push(concat$5(["${", expressionDoc, "}"])); + } + } + + return concat$5(["`", indent$2(concat$5([hardline$3, join$2(hardline$3, parts)])), hardline$3, "`"]); + } + + const htmlParser = isHtml(path) ? "html" : isAngularComponentTemplate(path) ? "angular" : undefined; + + if (htmlParser) { + return printHtmlTemplateLiteral(path, print, textToDoc, htmlParser, options); + } + + break; + } + + case "TemplateElement": + { + /** + * md`...` + * markdown`...` + */ + if (parentParent && parentParent.type === "TaggedTemplateExpression" && parent.quasis.length === 1 && parentParent.tag.type === "Identifier" && (parentParent.tag.name === "md" || parentParent.tag.name === "markdown")) { + const text = parent.quasis[0].value.raw.replace(/((?:\\\\)*)\\`/g, (_, backslashes) => "\\".repeat(backslashes.length / 2) + "`"); + const indentation = getIndentation(text); + const hasIndent = indentation !== ""; + return concat$5([hasIndent ? indent$2(concat$5([softline$1, printMarkdown(text.replace(new RegExp(`^${indentation}`, "gm"), ""))])) : concat$5([literalline$2, dedentToRoot$1(printMarkdown(text))]), softline$1]); + } + + break; + } + } + + function printMarkdown(text) { + const doc = textToDoc(text, { + parser: "markdown", + __inJsTemplate: true + }, { + stripTrailingHardline: true + }); + return escapeTemplateCharacters(doc, true); + } +} + +function getIndentation(str) { + const firstMatchedIndent = str.match(/^([^\S\n]*)\S/m); + return firstMatchedIndent === null ? "" : firstMatchedIndent[1]; +} + +function uncook(cookedValue) { + return cookedValue.replace(/([\\`]|\${)/g, "\\$1"); +} + +function escapeTemplateCharacters(doc, raw) { + return mapDoc$1(doc, currentDoc => { + if (!currentDoc.parts) { + return currentDoc; + } + + const parts = currentDoc.parts.map(part => { + if (typeof part === "string") { + return raw ? part.replace(/(\\*)`/g, "$1$1\\`") : uncook(part); + } + + return part; + }); + return Object.assign({}, currentDoc, { + parts + }); + }); +} + +function transformCssDoc(quasisDoc, path, print) { + const parentNode = path.getValue(); + const isEmpty = parentNode.quasis.length === 1 && !parentNode.quasis[0].value.raw.trim(); + + if (isEmpty) { + return "``"; + } + + const expressionDocs = parentNode.expressions ? path.map(print, "expressions") : []; + const newDoc = replacePlaceholders(quasisDoc, expressionDocs); + /* istanbul ignore if */ + + if (!newDoc) { + throw new Error("Couldn't insert all the expressions"); + } + + return concat$5(["`", indent$2(concat$5([hardline$3, newDoc])), softline$1, "`"]); +} // Search all the placeholders in the quasisDoc tree +// and replace them with the expression docs one by one +// returns a new doc with all the placeholders replaced, +// or null if it couldn't replace any expression + + +function replacePlaceholders(quasisDoc, expressionDocs) { + if (!expressionDocs || !expressionDocs.length) { + return quasisDoc; + } + + let replaceCounter = 0; + const newDoc = mapDoc$1(quasisDoc, doc => { + if (!doc || !doc.parts || !doc.parts.length) { + return doc; + } + + let { + parts + } = doc; + const atIndex = parts.indexOf("@"); + const placeholderIndex = atIndex + 1; + + if (atIndex > -1 && typeof parts[placeholderIndex] === "string" && parts[placeholderIndex].startsWith("prettier-placeholder")) { + // If placeholder is split, join it + const at = parts[atIndex]; + const placeholder = parts[placeholderIndex]; + const rest = parts.slice(placeholderIndex + 1); + parts = parts.slice(0, atIndex).concat([at + placeholder]).concat(rest); + } + + const replacedParts = []; + parts.forEach(part => { + if (typeof part !== "string" || !part.includes("@prettier-placeholder")) { + replacedParts.push(part); + return; + } // When we have multiple placeholders in one line, like: + // ${Child}${Child2}:not(:first-child) + + + part.split(/@prettier-placeholder-(\d+)-id/).forEach((component, idx) => { + // The placeholder is always at odd indices + if (idx % 2 === 0) { + replacedParts.push(replaceNewlinesWithLiterallines$1(component)); + return; + } // The component will always be a number at odd index + + + replacedParts.push("${", expressionDocs[component], "}"); + replaceCounter++; + }); + }); + return Object.assign({}, doc, { + parts: replacedParts + }); + }); + return expressionDocs.length === replaceCounter ? newDoc : null; +} + +function printGraphqlComments(lines) { + const parts = []; + let seenComment = false; + lines.map(textLine => textLine.trim()).forEach((textLine, i, array) => { + // Lines are either whitespace only, or a comment (with potential whitespace + // around it). Drop whitespace-only lines. + if (textLine === "") { + return; + } + + if (array[i - 1] === "" && seenComment) { + // If a non-first comment is preceded by a blank (whitespace only) line, + // add in a blank line. + parts.push(concat$5([hardline$3, textLine])); + } else { + parts.push(textLine); + } + + seenComment = true; + }); // If `lines` was whitespace only, return `null`. + + return parts.length === 0 ? null : join$2(hardline$3, parts); +} +/** + * Template literal in these contexts: + * + * css`` + * css.global`` + * css.resolve`` + */ + + +function isStyledJsx(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + return parentParent && node.quasis && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXElement" && parentParent.openingElement.name.name === "style" && parentParent.openingElement.attributes.some(attribute => attribute.name.name === "jsx") || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "Identifier" && parent.tag.name === "css" || parent && parent.type === "TaggedTemplateExpression" && parent.tag.type === "MemberExpression" && parent.tag.object.name === "css" && (parent.tag.property.name === "global" || parent.tag.property.name === "resolve"); +} +/** + * Angular Components can have: + * - Inline HTML template + * - Inline CSS styles + * + * ...which are both within template literals somewhere + * inside of the Component decorator factory. + * + * E.g. + * @Component({ + * template: `
...
`, + * styles: [`h1 { color: blue; }`] + * }) + */ + + +function isAngularComponentStyles(path) { + return path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "ArrayExpression" && name === "elements", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "styles" && name === "value", ...angularComponentObjectExpressionPredicates); +} + +function isAngularComponentTemplate(path) { + return path.match(node => node.type === "TemplateLiteral", (node, name) => (node.type === "Property" || node.type === "ObjectProperty") && node.key.type === "Identifier" && node.key.name === "template" && name === "value", ...angularComponentObjectExpressionPredicates); +} + +const angularComponentObjectExpressionPredicates = [(node, name) => node.type === "ObjectExpression" && name === "properties", (node, name) => node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "Component" && name === "arguments", (node, name) => node.type === "Decorator" && name === "expression"]; +/** + * styled-components template literals + */ + +function isStyledComponents(path) { + const parent = path.getParentNode(); + + if (!parent || parent.type !== "TaggedTemplateExpression") { + return false; + } + + const { + tag + } = parent; + + switch (tag.type) { + case "MemberExpression": + return (// styled.foo`` + isStyledIdentifier(tag.object) || // Component.extend`` + isStyledExtend(tag) + ); + + case "CallExpression": + return (// styled(Component)`` + isStyledIdentifier(tag.callee) || tag.callee.type === "MemberExpression" && (tag.callee.object.type === "MemberExpression" && ( // styled.foo.attrs({})`` + isStyledIdentifier(tag.callee.object.object) || // Component.extend.attrs({})`` + isStyledExtend(tag.callee.object)) || // styled(Component).attrs({})`` + tag.callee.object.type === "CallExpression" && isStyledIdentifier(tag.callee.object.callee)) + ); + + case "Identifier": + // css`` + return tag.name === "css"; + + default: + return false; + } +} +/** + * JSX element with CSS prop + */ + + +function isCssProp(path) { + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + return parentParent && parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" && parentParent.name.type === "JSXIdentifier" && parentParent.name.name === "css"; +} + +function isStyledIdentifier(node) { + return node.type === "Identifier" && node.name === "styled"; +} + +function isStyledExtend(node) { + return /^[A-Z]/.test(node.object.name) && node.property.name === "extend"; +} +/* + * react-relay and graphql-tag + * graphql`...` + * graphql.experimental`...` + * gql`...` + * GraphQL comment block + * + * This intentionally excludes Relay Classic tags, as Prettier does not + * support Relay Classic formatting. + */ + + +function isGraphQL(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + return hasLanguageComment(node, "GraphQL") || parent && (parent.type === "TaggedTemplateExpression" && (parent.tag.type === "MemberExpression" && parent.tag.object.name === "graphql" && parent.tag.property.name === "experimental" || parent.tag.type === "Identifier" && (parent.tag.name === "gql" || parent.tag.name === "graphql")) || parent.type === "CallExpression" && parent.callee.type === "Identifier" && parent.callee.name === "graphql"); +} + +function hasLanguageComment(node, languageName) { + // This checks for a leading comment that is exactly `/* GraphQL */` + // In order to be in line with other implementations of this comment tag + // we will not trim the comment value and we will expect exactly one space on + // either side of the GraphQL string + // Also see ./clean.js + return hasLeadingComment$1(node, comment => isBlockComment$1(comment) && comment.value === ` ${languageName} `); +} +/** + * - html`...` + * - HTML comment block + */ + + +function isHtml(path) { + return hasLanguageComment(path.getValue(), "HTML") || path.match(node => node.type === "TemplateLiteral", (node, name) => node.type === "TaggedTemplateExpression" && node.tag.type === "Identifier" && node.tag.name === "html" && name === "quasi"); +} // The counter is needed to distinguish nested embeds. + + +let htmlTemplateLiteralCounter = 0; + +function printHtmlTemplateLiteral(path, print, textToDoc, parser, options) { + const node = path.getValue(); + const counter = htmlTemplateLiteralCounter; + htmlTemplateLiteralCounter = htmlTemplateLiteralCounter + 1 >>> 0; + + const composePlaceholder = index => `PRETTIER_HTML_PLACEHOLDER_${index}_${counter}_IN_JS`; + + const text = node.quasis.map((quasi, index, quasis) => index === quasis.length - 1 ? quasi.value.cooked : quasi.value.cooked + composePlaceholder(index)).join(""); + const expressionDocs = path.map(print, "expressions"); + + if (expressionDocs.length === 0 && text.trim().length === 0) { + return "``"; + } + + const placeholderRegex = new RegExp(composePlaceholder("(\\d+)"), "g"); + let topLevelCount = 0; + const contentDoc = mapDoc$1(textToDoc(text, { + parser, + + __onHtmlRoot(root) { + topLevelCount = root.children.length; + } + + }, { + stripTrailingHardline: true + }), doc => { + if (typeof doc !== "string") { + return doc; + } + + const parts = []; + const components = doc.split(placeholderRegex); + + for (let i = 0; i < components.length; i++) { + let component = components[i]; + + if (i % 2 === 0) { + if (component) { + component = uncook(component); + + if (options.embeddedInHtml) { + component = component.replace(/<\/(script)\b/gi, "<\\/$1"); + } + + parts.push(component); + } + + continue; + } + + const placeholderIndex = +component; + parts.push(concat$5(["${", group$1(expressionDocs[placeholderIndex]), "}"])); + } + + return concat$5(parts); + }); + const leadingWhitespace = /^\s/.test(text) ? " " : ""; + const trailingWhitespace = /\s$/.test(text) ? " " : ""; + const linebreak = options.htmlWhitespaceSensitivity === "ignore" ? hardline$3 : leadingWhitespace && trailingWhitespace ? line$3 : null; + + if (linebreak) { + return group$1(concat$5(["`", indent$2(concat$5([linebreak, group$1(contentDoc)])), linebreak, "`"])); + } + + return group$1(concat$5(["`", leadingWhitespace, topLevelCount > 1 ? indent$2(group$1(contentDoc)) : group$1(contentDoc), trailingWhitespace, "`"])); +} + +var embed_1 = embed; + +function clean(ast, newObj, parent) { + ["range", "raw", "comments", "leadingComments", "trailingComments", "innerComments", "extra", "start", "end", "loc", "flags", "errors", "tokens"].forEach(name => { + delete newObj[name]; + }); + + if (ast.type === "Program") { + delete newObj.sourceType; + } + + if (ast.type === "BigIntLiteral") { + if (newObj.value) { + newObj.value = newObj.value.toLowerCase(); + } + + if (newObj.bigint) { + newObj.bigint = newObj.bigint.toLowerCase(); + } + } + + if (ast.type === "DecimalLiteral") { + newObj.value = Number(newObj.value); + } // We remove extra `;` and add them when needed + + + if (ast.type === "EmptyStatement") { + return null; + } // We move text around, including whitespaces and add {" "} + + + if (ast.type === "JSXText") { + return null; + } + + if (ast.type === "JSXExpressionContainer" && (ast.expression.type === "Literal" || ast.expression.type === "StringLiteral") && ast.expression.value === " ") { + return null; + } // We change {'key': value} into {key: value}. + // And {key: value} into {'key': value}. + // Also for (some) number keys. + + + if ((ast.type === "Property" || ast.type === "ObjectProperty" || ast.type === "MethodDefinition" || ast.type === "ClassProperty" || ast.type === "ClassMethod" || ast.type === "TSDeclareMethod" || ast.type === "TSPropertySignature" || ast.type === "ObjectTypeProperty") && typeof ast.key === "object" && ast.key && (ast.key.type === "Literal" || ast.key.type === "NumericLiteral" || ast.key.type === "StringLiteral" || ast.key.type === "Identifier")) { + delete newObj.key; + } + + if (ast.type === "OptionalMemberExpression" && ast.optional === false) { + newObj.type = "MemberExpression"; + delete newObj.optional; + } // Remove raw and cooked values from TemplateElement when it's CSS + // styled-jsx + + + if (ast.type === "JSXElement" && ast.openingElement.name.name === "style" && ast.openingElement.attributes.some(attr => attr.name.name === "jsx")) { + const templateLiterals = newObj.children.filter(child => child.type === "JSXExpressionContainer" && child.expression.type === "TemplateLiteral").map(container => container.expression); + const quasis = templateLiterals.reduce((quasis, templateLiteral) => quasis.concat(templateLiteral.quasis), []); + quasis.forEach(q => delete q.value); + } // CSS template literals in css prop + + + if (ast.type === "JSXAttribute" && ast.name.name === "css" && ast.value.type === "JSXExpressionContainer" && ast.value.expression.type === "TemplateLiteral") { + newObj.value.expression.quasis.forEach(q => delete q.value); + } // We change quotes + + + if (ast.type === "JSXAttribute" && ast.value && ast.value.type === "Literal" && /["']|"|'/.test(ast.value.value)) { + newObj.value.value = newObj.value.value.replace(/["']|"|'/g, '"'); + } // Angular Components: Inline HTML template and Inline CSS styles + + + const expression = ast.expression || ast.callee; + + if (ast.type === "Decorator" && expression.type === "CallExpression" && expression.callee.name === "Component" && expression.arguments.length === 1) { + const astProps = ast.expression.arguments[0].properties; + newObj.expression.arguments[0].properties.forEach((prop, index) => { + let templateLiteral = null; + + switch (astProps[index].key.name) { + case "styles": + if (prop.value.type === "ArrayExpression") { + templateLiteral = prop.value.elements[0]; + } + + break; + + case "template": + if (prop.value.type === "TemplateLiteral") { + templateLiteral = prop.value; + } + + break; + } + + if (templateLiteral) { + templateLiteral.quasis.forEach(q => delete q.value); + } + }); + } // styled-components, graphql, markdown + + + if (ast.type === "TaggedTemplateExpression" && (ast.tag.type === "MemberExpression" || ast.tag.type === "Identifier" && (ast.tag.name === "gql" || ast.tag.name === "graphql" || ast.tag.name === "css" || ast.tag.name === "md" || ast.tag.name === "markdown" || ast.tag.name === "html") || ast.tag.type === "CallExpression")) { + newObj.quasi.quasis.forEach(quasi => delete quasi.value); + } + + if (ast.type === "TemplateLiteral") { + // This checks for a leading comment that is exactly `/* GraphQL */` + // In order to be in line with other implementations of this comment tag + // we will not trim the comment value and we will expect exactly one space on + // either side of the GraphQL string + // Also see ./embed.js + const hasLanguageComment = ast.leadingComments && ast.leadingComments.some(comment => comment.type === "CommentBlock" && ["GraphQL", "HTML"].some(languageName => comment.value === ` ${languageName} `)); + + if (hasLanguageComment || parent.type === "CallExpression" && parent.callee.name === "graphql") { + newObj.quasis.forEach(quasi => delete quasi.value); + } // TODO: check parser + // `flow` and `typescript` don't have `leadingComments` + + + if (!ast.leadingComments) { + newObj.quasis.forEach(quasi => { + if (quasi.value) { + delete quasi.value.cooked; + } + }); + } + } + + if (ast.type === "InterpreterDirective") { + newObj.value = newObj.value.trimEnd(); + } +} + +var clean_1 = clean; + +const detectNewline = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + + const newlines = string.match(/(?:\r?\n)/g) || []; + + if (newlines.length === 0) { + return; + } + + const crlf = newlines.filter(newline => newline === '\r\n').length; + const lf = newlines.length - crlf; + return crlf > lf ? '\r\n' : '\n'; +}; + +var detectNewline_1 = detectNewline; + +var graceful = string => typeof string === 'string' && detectNewline(string) || '\n'; +detectNewline_1.graceful = graceful; + +var build = createCommonjsModule(function (module, exports) { + + Object.defineProperty(exports, '__esModule', { + value: true + }); + exports.extract = extract; + exports.strip = strip; + exports.parse = parse; + exports.parseWithComments = parseWithComments; + exports.print = print; + + function _os() { + const data = os__default['default']; + + _os = function () { + return data; + }; + + return data; + } + + function _detectNewline() { + const data = _interopRequireDefault(detectNewline_1); + + _detectNewline = function () { + return data; + }; + + return data; + } + + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + default: obj + }; + } + /** + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + + const commentEndRe = /\*\/$/; + const commentStartRe = /^\/\*\*/; + const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/; + const lineCommentRe = /(^|\s+)\/\/([^\r\n]*)/g; + const ltrimNewlineRe = /^(\r?\n)+/; + const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g; + const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g; + const stringStartRe = /(\r?\n|^) *\* ?/g; + const STRING_ARRAY = []; + + function extract(contents) { + const match = contents.match(docblockRe); + return match ? match[0].trimLeft() : ''; + } + + function strip(contents) { + const match = contents.match(docblockRe); + return match && match[0] ? contents.substring(match[0].length) : contents; + } + + function parse(docblock) { + return parseWithComments(docblock).pragmas; + } + + function parseWithComments(docblock) { + const line = (0, _detectNewline().default)(docblock) || _os().EOL; + + docblock = docblock.replace(commentStartRe, '').replace(commentEndRe, '').replace(stringStartRe, '$1'); // Normalize multi-line directives + + let prev = ''; + + while (prev !== docblock) { + prev = docblock; + docblock = docblock.replace(multilineRe, `${line}$1 $2${line}`); + } + + docblock = docblock.replace(ltrimNewlineRe, '').trimRight(); + const result = Object.create(null); + const comments = docblock.replace(propertyRe, '').replace(ltrimNewlineRe, '').trimRight(); + let match; + + while (match = propertyRe.exec(docblock)) { + // strip linecomments from pragmas + const nextPragma = match[2].replace(lineCommentRe, ''); + + if (typeof result[match[1]] === 'string' || Array.isArray(result[match[1]])) { + result[match[1]] = STRING_ARRAY.concat(result[match[1]], nextPragma); + } else { + result[match[1]] = nextPragma; + } + } + + return { + comments, + pragmas: result + }; + } + + function print({ + comments = '', + pragmas = {} + }) { + const line = (0, _detectNewline().default)(comments) || _os().EOL; + + const head = '/**'; + const start = ' *'; + const tail = ' */'; + const keys = Object.keys(pragmas); + const printedObject = keys.map(key => printKeyValues(key, pragmas[key])).reduce((arr, next) => arr.concat(next), []).map(keyValue => start + ' ' + keyValue + line).join(''); + + if (!comments) { + if (keys.length === 0) { + return ''; + } + + if (keys.length === 1 && !Array.isArray(pragmas[keys[0]])) { + const value = pragmas[keys[0]]; + return `${head} ${printKeyValues(keys[0], value)[0]}${tail}`; + } + } + + const printedComments = comments.split(line).map(textLine => `${start} ${textLine}`).join(line) + line; + return head + line + (comments ? printedComments : '') + (comments && keys.length ? start + line : '') + printedObject + tail; + } + + function printKeyValues(key, valueOrArray) { + return STRING_ARRAY.concat(valueOrArray).map(value => `@${key} ${value}`.trim()); + } +}); + +const { + parseWithComments, + strip, + extract, + print +} = build; +const { + getShebang: getShebang$1 +} = util; +const { + normalizeEndOfLine: normalizeEndOfLine$2 +} = endOfLine; + +function parseDocBlock(text) { + const shebang = getShebang$1(text); + + if (shebang) { + text = text.slice(shebang.length + 1); + } + + const docBlock = extract(text); + const { + pragmas, + comments + } = parseWithComments(docBlock); + return { + shebang, + text, + pragmas, + comments + }; +} + +function hasPragma(text) { + const pragmas = Object.keys(parseDocBlock(text).pragmas); + return pragmas.includes("prettier") || pragmas.includes("format"); +} + +function insertPragma(originalText) { + const { + shebang, + text, + pragmas, + comments + } = parseDocBlock(originalText); + const strippedText = strip(text); + const docBlock = print({ + pragmas: Object.assign({ + format: "" + }, pragmas), + comments: comments.trimStart() + }); + return (shebang ? `${shebang}\n` : "") + // normalise newlines (mitigate use of os.EOL by jest-docblock) + normalizeEndOfLine$2(docBlock) + (strippedText.startsWith("\n") ? "\n" : "\n\n") + strippedText; +} + +var pragma = { + hasPragma, + insertPragma +}; + +var ast = createCommonjsModule(function (module) { + /* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + + function isExpression(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'ArrayExpression': + case 'AssignmentExpression': + case 'BinaryExpression': + case 'CallExpression': + case 'ConditionalExpression': + case 'FunctionExpression': + case 'Identifier': + case 'Literal': + case 'LogicalExpression': + case 'MemberExpression': + case 'NewExpression': + case 'ObjectExpression': + case 'SequenceExpression': + case 'ThisExpression': + case 'UnaryExpression': + case 'UpdateExpression': + return true; + } + + return false; + } + + function isIterationStatement(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'DoWhileStatement': + case 'ForInStatement': + case 'ForStatement': + case 'WhileStatement': + return true; + } + + return false; + } + + function isStatement(node) { + if (node == null) { + return false; + } + + switch (node.type) { + case 'BlockStatement': + case 'BreakStatement': + case 'ContinueStatement': + case 'DebuggerStatement': + case 'DoWhileStatement': + case 'EmptyStatement': + case 'ExpressionStatement': + case 'ForInStatement': + case 'ForStatement': + case 'IfStatement': + case 'LabeledStatement': + case 'ReturnStatement': + case 'SwitchStatement': + case 'ThrowStatement': + case 'TryStatement': + case 'VariableDeclaration': + case 'WhileStatement': + case 'WithStatement': + return true; + } + + return false; + } + + function isSourceElement(node) { + return isStatement(node) || node != null && node.type === 'FunctionDeclaration'; + } + + function trailingStatement(node) { + switch (node.type) { + case 'IfStatement': + if (node.alternate != null) { + return node.alternate; + } + + return node.consequent; + + case 'LabeledStatement': + case 'ForStatement': + case 'ForInStatement': + case 'WhileStatement': + case 'WithStatement': + return node.body; + } + + return null; + } + + function isProblematicIfStatement(node) { + var current; + + if (node.type !== 'IfStatement') { + return false; + } + + if (node.alternate == null) { + return false; + } + + current = node.consequent; + + do { + if (current.type === 'IfStatement') { + if (current.alternate == null) { + return true; + } + } + + current = trailingStatement(current); + } while (current); + + return false; + } + + module.exports = { + isExpression: isExpression, + isStatement: isStatement, + isIterationStatement: isIterationStatement, + isSourceElement: isSourceElement, + isProblematicIfStatement: isProblematicIfStatement, + trailingStatement: trailingStatement + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + +}); + +var code = createCommonjsModule(function (module) { + /* + Copyright (C) 2013-2014 Yusuke Suzuki + Copyright (C) 2014 Ivan Nikulin + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + + var ES6Regex, ES5Regex, NON_ASCII_WHITESPACES, IDENTIFIER_START, IDENTIFIER_PART, ch; // See `tools/generate-identifier-regex.js`. + + ES5Regex = { + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/, + // ECMAScript 5.1/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/ + }; + ES6Regex = { + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // ECMAScript 6/Unicode v9.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08B6-\u08BD\u08D4-\u08E1\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C80-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D54-\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1C80-\u1C88\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C5\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE3E\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC00-\uDC4A\uDC50-\uDC59\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC36\uDC38-\uDC40\uDC50-\uDC59\uDC72-\uDC8F\uDC92-\uDCA7\uDCA9-\uDCB6]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F\uDFE0]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD838[\uDC00-\uDC06\uDC08-\uDC18\uDC1B-\uDC21\uDC23\uDC24\uDC26-\uDC2A]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6\uDD00-\uDD4A\uDD50-\uDD59]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + + function isDecimalDigit(ch) { + return 0x30 <= ch && ch <= 0x39; // 0..9 + } + + function isHexDigit(ch) { + return 0x30 <= ch && ch <= 0x39 || // 0..9 + 0x61 <= ch && ch <= 0x66 || // a..f + 0x41 <= ch && ch <= 0x46; // A..F + } + + function isOctalDigit(ch) { + return ch >= 0x30 && ch <= 0x37; // 0..7 + } // 7.2 White Space + + + NON_ASCII_WHITESPACES = [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF]; + + function isWhiteSpace(ch) { + return ch === 0x20 || ch === 0x09 || ch === 0x0B || ch === 0x0C || ch === 0xA0 || ch >= 0x1680 && NON_ASCII_WHITESPACES.indexOf(ch) >= 0; + } // 7.3 Line Terminators + + + function isLineTerminator(ch) { + return ch === 0x0A || ch === 0x0D || ch === 0x2028 || ch === 0x2029; + } // 7.6 Identifier Names and Identifiers + + + function fromCodePoint(cp) { + if (cp <= 0xFFFF) { + return String.fromCharCode(cp); + } + + var cu1 = String.fromCharCode(Math.floor((cp - 0x10000) / 0x400) + 0xD800); + var cu2 = String.fromCharCode((cp - 0x10000) % 0x400 + 0xDC00); + return cu1 + cu2; + } + + IDENTIFIER_START = new Array(0x80); + + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_START[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + IDENTIFIER_PART = new Array(0x80); + + for (ch = 0; ch < 0x80; ++ch) { + IDENTIFIER_PART[ch] = ch >= 0x61 && ch <= 0x7A || // a..z + ch >= 0x41 && ch <= 0x5A || // A..Z + ch >= 0x30 && ch <= 0x39 || // 0..9 + ch === 0x24 || ch === 0x5F; // $ (dollar) and _ (underscore) + } + + function isIdentifierStartES5(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES5Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES5(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES5Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + function isIdentifierStartES6(ch) { + return ch < 0x80 ? IDENTIFIER_START[ch] : ES6Regex.NonAsciiIdentifierStart.test(fromCodePoint(ch)); + } + + function isIdentifierPartES6(ch) { + return ch < 0x80 ? IDENTIFIER_PART[ch] : ES6Regex.NonAsciiIdentifierPart.test(fromCodePoint(ch)); + } + + module.exports = { + isDecimalDigit: isDecimalDigit, + isHexDigit: isHexDigit, + isOctalDigit: isOctalDigit, + isWhiteSpace: isWhiteSpace, + isLineTerminator: isLineTerminator, + isIdentifierStartES5: isIdentifierStartES5, + isIdentifierPartES5: isIdentifierPartES5, + isIdentifierStartES6: isIdentifierStartES6, + isIdentifierPartES6: isIdentifierPartES6 + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + +}); + +var keyword$1 = createCommonjsModule(function (module) { + /* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + + var code$1 = code; + + function isStrictModeReservedWordES6(id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'let': + return true; + + default: + return false; + } + } + + function isKeywordES5(id, strict) { + // yield should not be treated as keyword under non-strict mode. + if (!strict && id === 'yield') { + return false; + } + + return isKeywordES6(id, strict); + } + + function isKeywordES6(id, strict) { + if (strict && isStrictModeReservedWordES6(id)) { + return true; + } + + switch (id.length) { + case 2: + return id === 'if' || id === 'in' || id === 'do'; + + case 3: + return id === 'var' || id === 'for' || id === 'new' || id === 'try'; + + case 4: + return id === 'this' || id === 'else' || id === 'case' || id === 'void' || id === 'with' || id === 'enum'; + + case 5: + return id === 'while' || id === 'break' || id === 'catch' || id === 'throw' || id === 'const' || id === 'yield' || id === 'class' || id === 'super'; + + case 6: + return id === 'return' || id === 'typeof' || id === 'delete' || id === 'switch' || id === 'export' || id === 'import'; + + case 7: + return id === 'default' || id === 'finally' || id === 'extends'; + + case 8: + return id === 'function' || id === 'continue' || id === 'debugger'; + + case 10: + return id === 'instanceof'; + + default: + return false; + } + } + + function isReservedWordES5(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES5(id, strict); + } + + function isReservedWordES6(id, strict) { + return id === 'null' || id === 'true' || id === 'false' || isKeywordES6(id, strict); + } + + function isRestrictedWord(id) { + return id === 'eval' || id === 'arguments'; + } + + function isIdentifierNameES5(id) { + var i, iz, ch; + + if (id.length === 0) { + return false; + } + + ch = id.charCodeAt(0); + + if (!code$1.isIdentifierStartES5(ch)) { + return false; + } + + for (i = 1, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + + if (!code$1.isIdentifierPartES5(ch)) { + return false; + } + } + + return true; + } + + function decodeUtf16(lead, trail) { + return (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000; + } + + function isIdentifierNameES6(id) { + var i, iz, ch, lowCh, check; + + if (id.length === 0) { + return false; + } + + check = code$1.isIdentifierStartES6; + + for (i = 0, iz = id.length; i < iz; ++i) { + ch = id.charCodeAt(i); + + if (0xD800 <= ch && ch <= 0xDBFF) { + ++i; + + if (i >= iz) { + return false; + } + + lowCh = id.charCodeAt(i); + + if (!(0xDC00 <= lowCh && lowCh <= 0xDFFF)) { + return false; + } + + ch = decodeUtf16(ch, lowCh); + } + + if (!check(ch)) { + return false; + } + + check = code$1.isIdentifierPartES6; + } + + return true; + } + + function isIdentifierES5(id, strict) { + return isIdentifierNameES5(id) && !isReservedWordES5(id, strict); + } + + function isIdentifierES6(id, strict) { + return isIdentifierNameES6(id) && !isReservedWordES6(id, strict); + } + + module.exports = { + isKeywordES5: isKeywordES5, + isKeywordES6: isKeywordES6, + isReservedWordES5: isReservedWordES5, + isReservedWordES6: isReservedWordES6, + isRestrictedWord: isRestrictedWord, + isIdentifierNameES5: isIdentifierNameES5, + isIdentifierNameES6: isIdentifierNameES6, + isIdentifierES5: isIdentifierES5, + isIdentifierES6: isIdentifierES6 + }; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + +}); + +var utils$5 = createCommonjsModule(function (module, exports) { + /* + Copyright (C) 2013 Yusuke Suzuki + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY + DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + (function () { + + exports.ast = ast; + exports.code = code; + exports.keyword = keyword$1; + })(); + /* vim: set sw=4 ts=4 et tw=80 : */ + +}); + +const isIdentifierName = utils$5.keyword.isIdentifierNameES5; +const { + getLast: getLast$2, + hasNewline: hasNewline$4, + hasNewlineInRange: hasNewlineInRange$3, + hasIgnoreComment: hasIgnoreComment$1, + hasNodeIgnoreComment: hasNodeIgnoreComment$1, + skipWhitespace: skipWhitespace$2 +} = util; +/** + * @typedef {import("./types/estree").Node} Node + * @typedef {import("./types/estree").TemplateLiteral} TemplateLiteral + * @typedef {import("./types/estree").Comment} Comment + * @typedef {import("./types/estree").MemberExpression} MemberExpression + * @typedef {import("./types/estree").OptionalMemberExpression} OptionalMemberExpression + * @typedef {import("./types/estree").CallExpression} CallExpression + * @typedef {import("./types/estree").OptionalCallExpression} OptionalCallExpression + * @typedef {import("./types/estree").Expression} Expression + * @typedef {import("./types/estree").Property} Property + * @typedef {import("./types/estree").ObjectTypeProperty} ObjectTypeProperty + * @typedef {import("./types/estree").JSXElement} JSXElement + * @typedef {import("./types/estree").TaggedTemplateExpression} TaggedTemplateExpression + * @typedef {import("./types/estree").Literal} Literal + * + * @typedef {import("../common/fast-path")} FastPath + */ +// We match any whitespace except line terminators because +// Flow annotation comments cannot be split across lines. For example: +// +// (this /* +// : any */).foo = 5; +// +// is not picked up by Flow (see https://github.com/facebook/flow/issues/7050), so +// removing the newline would create a type annotation that the user did not intend +// to create. + +const NON_LINE_TERMINATING_WHITE_SPACE = "(?:(?=.)\\s)"; +const FLOW_SHORTHAND_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*:`); +const FLOW_ANNOTATION = new RegExp(`^${NON_LINE_TERMINATING_WHITE_SPACE}*::`); +/** + * @param {Node} node + * @returns {boolean} + */ + +function hasFlowShorthandAnnotationComment(node) { + // https://flow.org/en/docs/types/comments/ + // Syntax example: const r = new (window.Request /*: Class */)(""); + return node.extra && node.extra.parenthesized && node.trailingComments && FLOW_SHORTHAND_ANNOTATION.test(node.trailingComments[0].value); +} +/** + * @param {Comment[]} comments + * @returns {boolean} + */ + + +function hasFlowAnnotationComment(comments) { + return comments && FLOW_ANNOTATION.test(comments[0].value); +} +/** + * @param {Node} node + * @param {(Node) => boolean} fn + * @returns {boolean} + */ + + +function hasNode(node, fn) { + if (!node || typeof node !== "object") { + return false; + } + + if (Array.isArray(node)) { + return node.some(value => hasNode(value, fn)); + } + + const result = fn(node); + return typeof result === "boolean" ? result : Object.keys(node).some(key => hasNode(node[key], fn)); +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function hasNakedLeftSide(node) { + return node.type === "AssignmentExpression" || node.type === "BinaryExpression" || node.type === "LogicalExpression" || node.type === "NGPipeExpression" || node.type === "ConditionalExpression" || node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "BindExpression" || node.type === "UpdateExpression" && !node.prefix || node.type === "TSAsExpression" || node.type === "TSNonNullExpression"; +} + +function getLeftSide(node) { + if (node.expressions) { + return node.expressions[0]; + } + + return node.left || node.test || node.callee || node.object || node.tag || node.argument || node.expression; +} + +function getLeftSidePathName(path, node) { + if (node.expressions) { + return ["expressions", 0]; + } + + if (node.left) { + return ["left"]; + } + + if (node.test) { + return ["test"]; + } + + if (node.object) { + return ["object"]; + } + + if (node.callee) { + return ["callee"]; + } + + if (node.tag) { + return ["tag"]; + } + + if (node.argument) { + return ["argument"]; + } + + if (node.expression) { + return ["expression"]; + } + + throw new Error("Unexpected node has no left side."); +} + +const exportDeclarationTypes = new Set(["ExportDefaultDeclaration", "ExportDefaultSpecifier", "DeclareExportDeclaration", "ExportNamedDeclaration", "ExportAllDeclaration"]); +/** + * @param {Node} node + * @returns {boolean} + */ + +function isExportDeclaration(node) { + return node && exportDeclarationTypes.has(node.type); +} +/** + * @param {FastPath} path + * @returns {Node | null} + */ + + +function getParentExportDeclaration(path) { + const parentNode = path.getParentNode(); + + if (path.getName() === "declaration" && isExportDeclaration(parentNode)) { + return parentNode; + } + + return null; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isLiteral(node) { + return node.type === "BooleanLiteral" || node.type === "DirectiveLiteral" || node.type === "Literal" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "BigIntLiteral" || node.type === "DecimalLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "TemplateLiteral" || node.type === "TSTypeLiteral" || node.type === "JSXText"; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isNumericLiteral(node) { + return node.type === "NumericLiteral" || node.type === "Literal" && typeof node.value === "number"; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isStringLiteral(node) { + return node.type === "StringLiteral" || node.type === "Literal" && typeof node.value === "string"; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isObjectType(node) { + return node.type === "ObjectTypeAnnotation" || node.type === "TSTypeLiteral"; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isFunctionOrArrowExpression(node) { + return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression"; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isFunctionOrArrowExpressionWithBody(node) { + return node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression" && node.body.type === "BlockStatement"; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isTemplateLiteral(node) { + return node.type === "TemplateLiteral"; +} +/** + * Note: `inject` is used in AngularJS 1.x, `async` in Angular 2+ + * example: https://docs.angularjs.org/guide/unit-testing#using-beforeall- + * + * @param {Node} node + * @returns {boolean} + */ + + +function isAngularTestWrapper(node) { + return (node.type === "CallExpression" || node.type === "OptionalCallExpression") && node.callee.type === "Identifier" && (node.callee.name === "async" || node.callee.name === "inject" || node.callee.name === "fakeAsync"); +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isJSXNode(node) { + return node.type === "JSXElement" || node.type === "JSXFragment"; +} + +function isTheOnlyJSXElementInMarkdown(options, path) { + if (options.parentParser !== "markdown" && options.parentParser !== "mdx") { + return false; + } + + const node = path.getNode(); + + if (!node.expression || !isJSXNode(node.expression)) { + return false; + } + + const parent = path.getParentNode(); + return parent.type === "Program" && parent.body.length === 1; +} // Detect an expression node representing `{" "}` + + +function isJSXWhitespaceExpression(node) { + return node.type === "JSXExpressionContainer" && isLiteral(node.expression) && node.expression.value === " " && !node.expression.comments; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isMemberExpressionChain(node) { + if (node.type !== "MemberExpression" && node.type !== "OptionalMemberExpression") { + return false; + } + + if (node.object.type === "Identifier") { + return true; + } + + return isMemberExpressionChain(node.object); +} + +function isGetterOrSetter(node) { + return node.kind === "get" || node.kind === "set"; +} +/** + * @param {Node} nodeA + * @param {Node} nodeB + * @returns {boolean} + */ + + +function sameLocStart(nodeA, nodeB, options) { + return options.locStart(nodeA) === options.locStart(nodeB); +} // TODO: This is a bad hack and we need a better way to distinguish between +// arrow functions and otherwise + + +function isFunctionNotation(node, options) { + return isGetterOrSetter(node) || sameLocStart(node, node.value, options); +} // Hack to differentiate between the following two which have the same ast +// type T = { method: () => void }; +// type T = { method(): void }; + +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isObjectTypePropertyAFunction(node, options) { + return (node.type === "ObjectTypeProperty" || node.type === "ObjectTypeInternalSlot") && node.value.type === "FunctionTypeAnnotation" && !node.static && !isFunctionNotation(node, options); +} // Hack to differentiate between the following two which have the same ast +// declare function f(a): void; +// var f: (a) => void; + + +function isTypeAnnotationAFunction(node, options) { + return (node.type === "TypeAnnotation" || node.type === "TSTypeAnnotation") && node.typeAnnotation.type === "FunctionTypeAnnotation" && !node.static && !sameLocStart(node, node.typeAnnotation, options); +} + +const binaryishNodeTypes = new Set(["BinaryExpression", "LogicalExpression", "NGPipeExpression"]); +/** + * @param {Node} node + * @returns {boolean} + */ + +function isBinaryish(node) { + return binaryishNodeTypes.has(node.type); +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isMemberish(node) { + return node.type === "MemberExpression" || node.type === "OptionalMemberExpression" || node.type === "BindExpression" && Boolean(node.object); +} + +const flowTypeAnnotations = new Set(["AnyTypeAnnotation", "NullLiteralTypeAnnotation", "GenericTypeAnnotation", "ThisTypeAnnotation", "NumberTypeAnnotation", "VoidTypeAnnotation", "EmptyTypeAnnotation", "MixedTypeAnnotation", "BooleanTypeAnnotation", "BooleanLiteralTypeAnnotation", "StringTypeAnnotation"]); +/** + * @param {Node} node + * @returns {boolean} + */ + +function isSimpleFlowType(node) { + return node && flowTypeAnnotations.has(node.type) && !(node.type === "GenericTypeAnnotation" && node.typeParameters); +} + +const unitTestRe = /^(skip|[fx]?(it|describe|test))$/; +/** + * @param {CallExpression} node + * @returns {boolean} + */ + +function isSkipOrOnlyBlock(node) { + return (node.callee.type === "MemberExpression" || node.callee.type === "OptionalMemberExpression") && node.callee.object.type === "Identifier" && node.callee.property.type === "Identifier" && unitTestRe.test(node.callee.object.name) && (node.callee.property.name === "only" || node.callee.property.name === "skip"); +} +/** + * @param {CallExpression} node + * @returns {boolean} + */ + + +function isUnitTestSetUp(node) { + const unitTestSetUpRe = /^(before|after)(Each|All)$/; + return node.callee.type === "Identifier" && unitTestSetUpRe.test(node.callee.name) && node.arguments.length === 1; +} // eg; `describe("some string", (done) => {})` + + +function isTestCall(n, parent) { + if (n.type !== "CallExpression") { + return false; + } + + if (n.arguments.length === 1) { + if (isAngularTestWrapper(n) && parent && isTestCall(parent)) { + return isFunctionOrArrowExpression(n.arguments[0]); + } + + if (isUnitTestSetUp(n)) { + return isAngularTestWrapper(n.arguments[0]); + } + } else if (n.arguments.length === 2 || n.arguments.length === 3) { + if ((n.callee.type === "Identifier" && unitTestRe.test(n.callee.name) || isSkipOrOnlyBlock(n)) && (isTemplateLiteral(n.arguments[0]) || isStringLiteral(n.arguments[0]))) { + // it("name", () => { ... }, 2500) + if (n.arguments[2] && !isNumericLiteral(n.arguments[2])) { + return false; + } + + return (n.arguments.length === 2 ? isFunctionOrArrowExpression(n.arguments[1]) : isFunctionOrArrowExpressionWithBody(n.arguments[1]) && n.arguments[1].params.length <= 1) || isAngularTestWrapper(n.arguments[1]); + } + } + + return false; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function hasLeadingComment$2(node) { + return node.comments && node.comments.some(comment => comment.leading); +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function hasTrailingComment(node) { + return node.comments && node.comments.some(comment => comment.trailing); +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function hasTrailingLineComment(node) { + return node.comments && node.comments.some(comment => comment.trailing && !comments$1.isBlockComment(comment)); +} +/** + * @param {CallExpression | OptionalCallExpression} node + * @returns {boolean} + */ + + +function isCallOrOptionalCallExpression(node) { + return node.type === "CallExpression" || node.type === "OptionalCallExpression"; +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function hasDanglingComments(node) { + return node.comments && node.comments.some(comment => !comment.leading && !comment.trailing); +} +/** identify if an angular expression seems to have side effects */ + +/** + * @param {FastPath} path + * @returns {boolean} + */ + + +function hasNgSideEffect(path) { + return hasNode(path.getValue(), node => { + switch (node.type) { + case undefined: + return false; + + case "CallExpression": + case "OptionalCallExpression": + case "AssignmentExpression": + return true; + } + }); +} + +function isNgForOf(node, index, parentNode) { + return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null; +} +/** + * + * @param {any} node + * @returns {boolean} + */ + + +function isSimpleTemplateLiteral(node) { + if (node.expressions.length === 0) { + return false; + } + + return node.expressions.every(expr => { + // Disallow comments since printDocToString can't print them here + if (expr.comments) { + return false; + } // Allow `x` and `this` + + + if (expr.type === "Identifier" || expr.type === "ThisExpression") { + return true; + } // Allow `a.b.c`, `a.b[c]`, and `this.x.y` + + + if (expr.type === "MemberExpression" || expr.type === "OptionalMemberExpression") { + let head = expr; + + while (head.type === "MemberExpression" || head.type === "OptionalMemberExpression") { + if (head.property.type !== "Identifier" && head.property.type !== "Literal" && head.property.type !== "StringLiteral" && head.property.type !== "NumericLiteral") { + return false; + } + + head = head.object; + + if (head.comments) { + return false; + } + } + + if (head.type === "Identifier" || head.type === "ThisExpression") { + return true; + } + + return false; + } + + return false; + }); +} +/** + * @param {ObjectTypeProperty} node + */ + + +function getFlowVariance(node) { + if (!node.variance) { + return null; + } // Babel 7.0 currently uses variance node type, and flow should + // follow suit soon: + // https://github.com/babel/babel/issues/4722 + + + const variance = node.variance.kind || node.variance; + + switch (variance) { + case "plus": + return "+"; + + case "minus": + return "-"; + + default: + /* istanbul ignore next */ + return variance; + } +} +/** + * @param {FastPath} path + * @returns {boolean} + */ + + +function classPropMayCauseASIProblems(path) { + const node = path.getNode(); + + if (node.type !== "ClassProperty") { + return false; + } + + const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today + // so isn't properly tested yet. + + if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) { + return true; + } +} + +function classChildNeedsASIProtection(node) { + if (!node) { + return; + } + + if (node.static || node.accessibility // TypeScript + ) { + return false; + } + + if (!node.computed) { + const name = node.key && node.key.name; + + if (name === "in" || name === "instanceof") { + return true; + } + } + + switch (node.type) { + case "ClassProperty": + case "TSAbstractClassProperty": + return node.computed; + + case "MethodDefinition": // Flow + + case "TSAbstractMethodDefinition": // TypeScript + + case "ClassMethod": + case "ClassPrivateMethod": + { + // Babel + const isAsync = node.value ? node.value.async : node.async; + const isGenerator = node.value ? node.value.generator : node.generator; + + if (isAsync || node.kind === "get" || node.kind === "set") { + return false; + } + + if (node.computed || isGenerator) { + return true; + } + + return false; + } + + case "TSIndexSignature": + return true; + + default: + /* istanbul ignore next */ + return false; + } +} +/** + * @param {string} tokenNode + * @param {string} keyword + * @returns {string} + */ + + +function getTypeScriptMappedTypeModifier(tokenNode, keyword) { + if (tokenNode === "+") { + return "+" + keyword; + } else if (tokenNode === "-") { + return "-" + keyword; + } + + return keyword; +} + +function hasNewlineBetweenOrAfterDecorators(node, options) { + return hasNewlineInRange$3(options.originalText, options.locStart(node.decorators[0]), options.locEnd(getLast$2(node.decorators))) || hasNewline$4(options.originalText, options.locEnd(getLast$2(node.decorators))); +} // Only space, newline, carriage return, and tab are treated as whitespace +// inside JSX. + + +const jsxWhitespaceChars = " \n\r\t"; +const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)"); +const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); // Meaningful if it contains non-whitespace characters, +// or it contains whitespace without a new line. + +/** + * @param {Node} node + * @returns {boolean} + */ + +function isMeaningfulJSXText(node) { + return isLiteral(node) && (containsNonJsxWhitespaceRegex.test(rawText(node)) || !/\n/.test(rawText(node))); +} +/** + * @param {FastPath} path + * @returns {boolean} + */ + + +function hasJsxIgnoreComment(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (!parent || !node || !isJSXNode(node) || !isJSXNode(parent)) { + return false; + } // Lookup the previous sibling, ignoring any empty JSXText elements + + + const index = parent.children.indexOf(node); + let prevSibling = null; + + for (let i = index; i > 0; i--) { + const candidate = parent.children[i - 1]; + + if (candidate.type === "JSXText" && !isMeaningfulJSXText(candidate)) { + continue; + } + + prevSibling = candidate; + break; + } + + return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && prevSibling.expression.comments && prevSibling.expression.comments.some(comment => comment.value.trim() === "prettier-ignore"); +} +/** + * @param {JSXElement} node + * @returns {boolean} + */ + + +function isEmptyJSXElement(node) { + if (node.children.length === 0) { + return true; + } + + if (node.children.length > 1) { + return false; + } // if there is one text child and does not contain any meaningful text + // we can treat the element as empty. + + + const child = node.children[0]; + return isLiteral(child) && !isMeaningfulJSXText(child); +} +/** + * @param {FastPath} path + * @returns {boolean} + */ + + +function hasPrettierIgnore(path) { + return hasIgnoreComment$1(path) || hasJsxIgnoreComment(path); +} +/** + * @param {FastPath} path + * @returns {boolean} + */ + + +function isLastStatement(path) { + const parent = path.getParentNode(); + + if (!parent) { + return true; + } + + const node = path.getValue(); + const body = (parent.body || parent.consequent).filter(stmt => stmt.type !== "EmptyStatement"); + return body[body.length - 1] === node; +} +/** + * @param {string} text + * @param {Node} typeAnnotation + * @returns {boolean} + */ + + +function isFlowAnnotationComment(text, typeAnnotation, options) { + const start = options.locStart(typeAnnotation); + const end = skipWhitespace$2(text, options.locEnd(typeAnnotation)); + return end !== false && text.slice(start, start + 2) === "/*" && text.slice(end, end + 2) === "*/"; +} +/** + * @param {string} text + * @param {Node} node + * @returns {boolean} + */ + + +function hasLeadingOwnLineComment(text, node, options) { + if (isJSXNode(node)) { + return hasNodeIgnoreComment$1(node); + } + + const res = node.comments && node.comments.some(comment => comment.leading && hasNewline$4(text, options.locEnd(comment))); + return res; +} // This recurses the return argument, looking for the first token +// (the leftmost leaf node) and, if it (or its parents) has any +// leadingComments, returns true (so it can be wrapped in parens). + + +function returnArgumentHasLeadingComment(options, argument) { + if (hasLeadingOwnLineComment(options.originalText, argument, options)) { + return true; + } + + if (hasNakedLeftSide(argument)) { + let leftMost = argument; + let newLeftMost; + + while (newLeftMost = getLeftSide(leftMost)) { + leftMost = newLeftMost; + + if (hasLeadingOwnLineComment(options.originalText, leftMost, options)) { + return true; + } + } + } + + return false; +} // Note: Quoting/unquoting numbers in TypeScript is not safe. +// +// let a = { 1: 1, 2: 2 } +// let b = { '1': 1, '2': 2 } +// +// declare let aa: keyof typeof a; +// declare let bb: keyof typeof b; +// +// aa = bb; +// ^^ +// Type '"1" | "2"' is not assignable to type '1 | 2'. +// Type '"1"' is not assignable to type '1 | 2'.(2322) +// +// And in Flow, you get: +// +// const x = { +// 0: 1 +// ^ Non-string literal property keys not supported. [unsupported-syntax] +// } +// +// Angular does not support unquoted numbers in expressions. +// +// So we play it safe and only unquote numbers for the "babel" parser. +// (Vue supports unquoted numbers in expressions, but let’s keep it simple.) +// +// Identifiers can be unquoted in more circumstances, though. + + +function isStringPropSafeToUnquote(node, options) { + return options.parser !== "json" && isStringLiteral(node.key) && rawText(node.key).slice(1, -1) === node.key.value && (isIdentifierName(node.key.value) && // With `--strictPropertyInitialization`, TS treats properties with quoted names differently than unquoted ones. + // See https://github.com/microsoft/TypeScript/pull/20075 + !((options.parser === "typescript" || options.parser === "babel-ts") && node.type === "ClassProperty") || isSimpleNumber(node.key.value) && String(Number(node.key.value)) === node.key.value && options.parser === "babel"); +} // Matches “simple” numbers like `123` and `2.5` but not `1_000`, `1e+100` or `0b10`. + + +function isSimpleNumber(numberString) { + return /^(\d+|\d+\.\d+)$/.test(numberString); +} +/** + * @param {Node} node + * @param {Node} parentNode + * @returns {boolean} + */ + + +function isJestEachTemplateLiteral(node, parentNode) { + /** + * describe.each`table`(name, fn) + * describe.only.each`table`(name, fn) + * describe.skip.each`table`(name, fn) + * test.each`table`(name, fn) + * test.only.each`table`(name, fn) + * test.skip.each`table`(name, fn) + * + * Ref: https://github.com/facebook/jest/pull/6102 + */ + const jestEachTriggerRegex = /^[fx]?(describe|it|test)$/; + return parentNode.type === "TaggedTemplateExpression" && parentNode.quasi === node && parentNode.tag.type === "MemberExpression" && parentNode.tag.property.type === "Identifier" && parentNode.tag.property.name === "each" && (parentNode.tag.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.name) || parentNode.tag.object.type === "MemberExpression" && parentNode.tag.object.property.type === "Identifier" && (parentNode.tag.object.property.name === "only" || parentNode.tag.object.property.name === "skip") && parentNode.tag.object.object.type === "Identifier" && jestEachTriggerRegex.test(parentNode.tag.object.object.name)); +} +/** + * @param {TemplateLiteral} template + * @returns {boolean} + */ + + +function templateLiteralHasNewLines(template) { + return template.quasis.some(quasi => quasi.value.raw.includes("\n")); +} +/** + * @param {TemplateLiteral | TaggedTemplateExpression} n + * @param {string} text + * @returns {boolean} + */ + + +function isTemplateOnItsOwnLine(n, text, options) { + return (n.type === "TemplateLiteral" && templateLiteralHasNewLines(n) || n.type === "TaggedTemplateExpression" && templateLiteralHasNewLines(n.quasi)) && !hasNewline$4(text, options.locStart(n), { + backwards: true + }); +} +/** + * @param {Node} node + * @returns {boolean} + */ + + +function needsHardlineAfterDanglingComment(node) { + if (!node.comments) { + return false; + } + + const lastDanglingComment = getLast$2(node.comments.filter(comment => !comment.leading && !comment.trailing)); + return lastDanglingComment && !comments$1.isBlockComment(lastDanglingComment); +} // Logic to check for args with multiple anonymous functions. For instance, +// the following call should be split on multiple lines for readability: +// source.pipe(map((x) => x + x), filter((x) => x % 2 === 0)) + + +function isFunctionCompositionArgs(args) { + if (args.length <= 1) { + return false; + } + + let count = 0; + + for (const arg of args) { + if (isFunctionOrArrowExpression(arg)) { + count += 1; + + if (count > 1) { + return true; + } + } else if (isCallOrOptionalCallExpression(arg)) { + for (const childArg of arg.arguments) { + if (isFunctionOrArrowExpression(childArg)) { + return true; + } + } + } + } + + return false; +} // Logic to determine if a call is a “long curried function call”. +// See https://github.com/prettier/prettier/issues/1420. +// +// `connect(a, b, c)(d)` +// In the above call expression, the second call is the parent node and the +// first call is the current node. + +/** + * @param {FastPath} path + * @returns {boolean} + */ + + +function isLongCurriedCallExpression(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + return isCallOrOptionalCallExpression(node) && isCallOrOptionalCallExpression(parent) && parent.callee === node && node.arguments.length > parent.arguments.length && parent.arguments.length > 0; +} +/** + * @param {any} node + * @param {number} depth + * @returns {boolean} + */ + + +function isSimpleCallArgument(node, depth) { + if (depth >= 2) { + return false; + } + + const isChildSimple = child => isSimpleCallArgument(child, depth + 1); + + const regexpPattern = node.type === "Literal" && "regex" in node && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern; + + if (regexpPattern && regexpPattern.length > 5) { + return false; + } + + if (node.type === "Literal" || node.type === "BigIntLiteral" || node.type === "DecimalLiteral" || node.type === "BooleanLiteral" || node.type === "NullLiteral" || node.type === "NumericLiteral" || node.type === "RegExpLiteral" || node.type === "StringLiteral" || node.type === "Identifier" || node.type === "ThisExpression" || node.type === "Super" || node.type === "PrivateName" || node.type === "ArgumentPlaceholder" || node.type === "Import") { + return true; + } + + if (node.type === "TemplateLiteral") { + return node.expressions.every(isChildSimple); + } + + if (node.type === "ObjectExpression") { + return node.properties.every(p => !p.computed && (p.shorthand || p.value && isChildSimple(p.value))); + } + + if (node.type === "ArrayExpression") { + return node.elements.every(x => x === null || isChildSimple(x)); + } + + if (node.type === "ImportExpression") { + return isChildSimple(node.source); + } + + if (node.type === "CallExpression" || node.type === "OptionalCallExpression" || node.type === "NewExpression") { + return isSimpleCallArgument(node.callee, depth) && node.arguments.every(isChildSimple); + } + + if (node.type === "MemberExpression" || node.type === "OptionalMemberExpression") { + return isSimpleCallArgument(node.object, depth) && isSimpleCallArgument(node.property, depth); + } + + if (node.type === "UnaryExpression" && (node.operator === "!" || node.operator === "-")) { + return isSimpleCallArgument(node.argument, depth); + } + + if (node.type === "TSNonNullExpression") { + return isSimpleCallArgument(node.expression, depth); + } + + return false; +} + +function rawText(node) { + return node.extra ? node.extra.raw : node.raw; +} + +function identity$1(x) { + return x; +} + +function isTSXFile(options) { + return options.filepath && /\.tsx$/i.test(options.filepath); +} +/** + * @param {any} options + * @param {("es5" | "all")} [level] + * @returns {boolean} + */ + + +function shouldPrintComma(options, level = "es5") { + return options.trailingComma === "es5" && level === "es5" || options.trailingComma === "all" && (level === "all" || level === "es5"); +} +/** + * Tests if an expression starts with `{`, or (if forbidFunctionClassAndDoExpr + * holds) `function`, `class`, or `do {}`. Will be overzealous if there's + * already necessary grouping parentheses. + * + * @param {Node} node + * @param {boolean} forbidFunctionClassAndDoExpr + * @returns {boolean} + */ + + +function startsWithNoLookaheadToken(node, forbidFunctionClassAndDoExpr) { + node = getLeftMost(node); + + switch (node.type) { + case "FunctionExpression": + case "ClassExpression": + case "DoExpression": + return forbidFunctionClassAndDoExpr; + + case "ObjectExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); + + case "TaggedTemplateExpression": + if (node.tag.type === "FunctionExpression") { + // IIFEs are always already parenthesized + return false; + } + + return startsWithNoLookaheadToken(node.tag, forbidFunctionClassAndDoExpr); + + case "CallExpression": + case "OptionalCallExpression": + if (node.callee.type === "FunctionExpression") { + // IIFEs are always already parenthesized + return false; + } + + return startsWithNoLookaheadToken(node.callee, forbidFunctionClassAndDoExpr); + + case "ConditionalExpression": + return startsWithNoLookaheadToken(node.test, forbidFunctionClassAndDoExpr); + + case "UpdateExpression": + return !node.prefix && startsWithNoLookaheadToken(node.argument, forbidFunctionClassAndDoExpr); + + case "BindExpression": + return node.object && startsWithNoLookaheadToken(node.object, forbidFunctionClassAndDoExpr); + + case "SequenceExpression": + return startsWithNoLookaheadToken(node.expressions[0], forbidFunctionClassAndDoExpr); + + case "TSAsExpression": + return startsWithNoLookaheadToken(node.expression, forbidFunctionClassAndDoExpr); + + default: + return false; + } +} + +const equalityOperators = { + "==": true, + "!=": true, + "===": true, + "!==": true +}; +const multiplicativeOperators = { + "*": true, + "/": true, + "%": true +}; +const bitshiftOperators = { + ">>": true, + ">>>": true, + "<<": true +}; + +function shouldFlatten(parentOp, nodeOp) { + if (getPrecedence(nodeOp) !== getPrecedence(parentOp)) { + return false; + } // ** is right-associative + // x ** y ** z --> x ** (y ** z) + + + if (parentOp === "**") { + return false; + } // x == y == z --> (x == y) == z + + + if (equalityOperators[parentOp] && equalityOperators[nodeOp]) { + return false; + } // x * y % z --> (x * y) % z + + + if (nodeOp === "%" && multiplicativeOperators[parentOp] || parentOp === "%" && multiplicativeOperators[nodeOp]) { + return false; + } // x * y / z --> (x * y) / z + // x / y * z --> (x / y) * z + + + if (nodeOp !== parentOp && multiplicativeOperators[nodeOp] && multiplicativeOperators[parentOp]) { + return false; + } // x << y << z --> (x << y) << z + + + if (bitshiftOperators[parentOp] && bitshiftOperators[nodeOp]) { + return false; + } + + return true; +} + +const PRECEDENCE = {}; +[["|>"], ["??"], ["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"], ["**"]].forEach((tier, i) => { + tier.forEach(op => { + PRECEDENCE[op] = i; + }); +}); + +function getPrecedence(op) { + return PRECEDENCE[op]; +} + +function getLeftMost(node) { + while (node.left) { + node = node.left; + } + + return node; +} + +function isBitwiseOperator(operator) { + return !!bitshiftOperators[operator] || operator === "|" || operator === "^" || operator === "&"; +} + +var utils$6 = { + classChildNeedsASIProtection, + classPropMayCauseASIProblems, + getFlowVariance, + getLeftSidePathName, + getParentExportDeclaration, + getTypeScriptMappedTypeModifier, + hasDanglingComments, + hasFlowAnnotationComment, + hasFlowShorthandAnnotationComment, + hasLeadingComment: hasLeadingComment$2, + hasLeadingOwnLineComment, + hasNakedLeftSide, + hasNewlineBetweenOrAfterDecorators, + hasNgSideEffect, + hasNode, + hasPrettierIgnore, + hasTrailingComment, + hasTrailingLineComment, + identity: identity$1, + isBinaryish, + isCallOrOptionalCallExpression, + isEmptyJSXElement, + isExportDeclaration, + isFlowAnnotationComment, + isFunctionCompositionArgs, + isFunctionNotation, + isFunctionOrArrowExpression, + isGetterOrSetter, + isJestEachTemplateLiteral, + isJSXNode, + isJSXWhitespaceExpression, + isLastStatement, + isLiteral, + isLongCurriedCallExpression, + isSimpleCallArgument, + isMeaningfulJSXText, + isMemberExpressionChain, + isMemberish, + isNgForOf, + isNumericLiteral, + isObjectType, + isObjectTypePropertyAFunction, + isSimpleFlowType, + isSimpleNumber, + isSimpleTemplateLiteral, + isStringLiteral, + isStringPropSafeToUnquote, + isTemplateOnItsOwnLine, + isTestCall, + isTheOnlyJSXElementInMarkdown, + isTSXFile, + isTypeAnnotationAFunction, + matchJsxWhitespaceRegex, + needsHardlineAfterDanglingComment, + rawText, + returnArgumentHasLeadingComment, + shouldPrintComma, + isBitwiseOperator, + shouldFlatten, + startsWithNoLookaheadToken, + getPrecedence +}; + +/** @type {import("assert")} */ + + +const { + getLeftSidePathName: getLeftSidePathName$1, + hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$1, + hasNakedLeftSide: hasNakedLeftSide$1, + hasNode: hasNode$1, + isBitwiseOperator: isBitwiseOperator$1, + startsWithNoLookaheadToken: startsWithNoLookaheadToken$1, + shouldFlatten: shouldFlatten$1, + getPrecedence: getPrecedence$1 +} = utils$6; + +function needsParens(path, options) { + const parent = path.getParentNode(); + + if (!parent) { + return false; + } + + const name = path.getName(); + const node = path.getNode(); // If the value of this path is some child of a Node and not a Node + // itself, then it doesn't need parentheses. Only Node objects (in + // fact, only Expression nodes) need parentheses. + + if (path.getValue() !== node) { + return false; + } // to avoid unexpected `}}` in HTML interpolations + + + if (options.__isInHtmlInterpolation && !options.bracketSpacing && endsWithRightBracket(node) && isFollowedByRightBracket(path)) { + return true; + } // Only statements don't need parentheses. + + + if (isStatement(node)) { + return false; + } + + if ( // Preserve parens if we have a Flow annotation comment, unless we're using the Flow + // parser. The Flow parser turns Flow comments into type annotation nodes in its + // AST, which we handle separately. + options.parser !== "flow" && hasFlowShorthandAnnotationComment$1(path.getValue())) { + return true; + } // Identifiers never need parentheses. + + + if (node.type === "Identifier") { + // ...unless those identifiers are embed placeholders. They might be substituted by complex + // expressions, so the parens around them should not be dropped. Example (JS-in-HTML-in-JS): + // let tpl = html``; + // If the inner JS formatter removes the parens, the expression might change its meaning: + // f((a + b) / 2) vs f(a + b / 2) + if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) { + return true; + } + + return false; + } + + if (parent.type === "ParenthesizedExpression") { + return false; + } // Add parens around the extends clause of a class. It is needed for almost + // all expressions. + + + if ((parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression")) { + return true; + } + + if (parent.type === "ExportDefaultDeclaration") { + return (// `export default function` or `export default class` can't be followed by + // anything after. So an expression like `export default (function(){}).toString()` + // needs to be followed by a parentheses + shouldWrapFunctionForExportDefault(path, options) || // `export default (foo, bar)` also needs parentheses + node.type === "SequenceExpression" + ); + } + + if (parent.type === "Decorator" && parent.expression === node) { + let hasCallExpression = false; + let hasMemberExpression = false; + let current = node; + + while (current) { + switch (current.type) { + case "MemberExpression": + hasMemberExpression = true; + current = current.object; + break; + + case "CallExpression": + if ( + /** @(x().y) */ + hasMemberExpression || + /** @(x().y()) */ + hasCallExpression) { + return true; + } + + hasCallExpression = true; + current = current.callee; + break; + + case "Identifier": + return false; + + default: + return true; + } + } + + return true; + } + + if (parent.type === "ArrowFunctionExpression" && parent.body === node && node.type !== "SequenceExpression" && // these have parens added anyway + startsWithNoLookaheadToken$1(node, + /* forbidFunctionClassAndDoExpr */ + false) || parent.type === "ExpressionStatement" && startsWithNoLookaheadToken$1(node, + /* forbidFunctionClassAndDoExpr */ + true)) { + return true; + } + + switch (node.type) { + case "SpreadElement": + case "SpreadProperty": + return parent.type === "MemberExpression" && name === "object" && parent.object === node; + + case "UpdateExpression": + if (parent.type === "UnaryExpression") { + return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-"); + } + + // else fallthrough + + case "UnaryExpression": + switch (parent.type) { + case "UnaryExpression": + return node.operator === parent.operator && (node.operator === "+" || node.operator === "-"); + + case "BindExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "TaggedTemplateExpression": + return true; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "BinaryExpression": + return parent.operator === "**" && name === "left"; + + case "TSNonNullExpression": + return true; + + default: + return false; + } + + case "BinaryExpression": + { + if (parent.type === "UpdateExpression" || parent.type === "PipelineTopicExpression" && node.operator === "|>") { + return true; + } + + const isLeftOfAForStatement = node => { + let i = 0; + + while (node) { + const parent = path.getParentNode(i++); + + if (!parent) { + return false; + } + + if (parent.type === "ForStatement" && parent.init === node) { + return true; + } + + node = parent; + } + + return false; + }; + + if (node.operator === "in" && isLeftOfAForStatement(node)) { + return true; + } + + if (node.operator === "|>" && node.extra && node.extra.parenthesized) { + const grandParent = path.getParentNode(1); + + if (grandParent.type === "BinaryExpression" && grandParent.operator === "|>") { + return true; + } + } + } + // fallthrough + + case "TSTypeAssertion": + case "TSAsExpression": + case "LogicalExpression": + switch (parent.type) { + case "ConditionalExpression": + return node.type === "TSAsExpression"; + + case "CallExpression": + case "NewExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ClassExpression": + case "ClassDeclaration": + return name === "superClass" && parent.superClass === node; + + case "TSTypeAssertion": + case "TaggedTemplateExpression": + case "UnaryExpression": + case "JSXSpreadAttribute": + case "SpreadElement": + case "SpreadProperty": + case "BindExpression": + case "AwaitExpression": + case "TSAsExpression": + case "TSNonNullExpression": + case "UpdateExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "AssignmentExpression": + return parent.left === node && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression"); + + case "LogicalExpression": + if (node.type === "LogicalExpression") { + return parent.operator !== node.operator; + } + + // else fallthrough + + case "BinaryExpression": + { + if (!node.operator && node.type !== "TSTypeAssertion") { + return true; + } + + const po = parent.operator; + const pp = getPrecedence$1(po); + const no = node.operator; + const np = getPrecedence$1(no); + + if (pp > np) { + return true; + } + + if (pp === np && name === "right") { + assert__default['default'].strictEqual(parent.right, node); + return true; + } + + if (pp === np && !shouldFlatten$1(po, no)) { + return true; + } + + if (pp < np && no === "%") { + return po === "+" || po === "-"; + } // Add parenthesis when working with bitwise operators + // It's not strictly needed but helps with code understanding + + + if (isBitwiseOperator$1(po)) { + return true; + } + + return false; + } + + default: + return false; + } + + case "SequenceExpression": + switch (parent.type) { + case "ReturnStatement": + return false; + + case "ForStatement": + // Although parentheses wouldn't hurt around sequence + // expressions in the head of for loops, traditional style + // dictates that e.g. i++, j++ should not be wrapped with + // parentheses. + return false; + + case "ExpressionStatement": + return name !== "expression"; + + case "ArrowFunctionExpression": + // We do need parentheses, but SequenceExpressions are handled + // specially when printing bodies of arrow functions. + return name !== "body"; + + default: + // Otherwise err on the side of overparenthesization, adding + // explicit exceptions above if this proves overzealous. + return true; + } + + case "YieldExpression": + if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") { + return true; + } + + // else fallthrough + + case "AwaitExpression": + switch (parent.type) { + case "TaggedTemplateExpression": + case "UnaryExpression": + case "LogicalExpression": + case "SpreadElement": + case "SpreadProperty": + case "TSAsExpression": + case "TSNonNullExpression": + case "BindExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ConditionalExpression": + return parent.test === node; + + case "BinaryExpression": + { + if (!node.argument && parent.operator === "|>") { + return false; + } + + return true; + } + + default: + return false; + } + + case "TSJSDocFunctionType": + case "TSConditionalType": + if (parent.type === "TSConditionalType" && node === parent.extendsType) { + return true; + } + + // fallthrough + + case "TSFunctionType": + case "TSConstructorType": + if (parent.type === "TSConditionalType" && node === parent.checkType) { + return true; + } + + // fallthrough + + case "TSUnionType": + case "TSIntersectionType": + if (parent.type === "TSUnionType" || parent.type === "TSIntersectionType") { + return true; + } + + // fallthrough + + case "TSInferType": + if (node.type === "TSInferType" && parent.type === "TSRestType") { + return false; + } + + // fallthrough + + case "TSTypeOperator": + return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || parent.type === "TSIndexedAccessType" && node === parent.objectType || parent.type === "TSTypeOperator" || parent.type === "TSTypeAnnotation" && /^TSJSDoc/.test(path.getParentNode(1).type); + + case "ArrayTypeAnnotation": + return parent.type === "NullableTypeAnnotation"; + + case "IntersectionTypeAnnotation": + case "UnionTypeAnnotation": + return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation"; + + case "NullableTypeAnnotation": + return parent.type === "ArrayTypeAnnotation"; + + case "FunctionTypeAnnotation": + { + const ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent; + return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses + // are really needed, but since ??T doesn't make sense this check + // will almost never be true. + ancestor.type === "NullableTypeAnnotation" || // See #5283 + parent.type === "FunctionTypeParam" && parent.name === null && node.params && node.params.some(param => param.typeAnnotation && param.typeAnnotation.type === "NullableTypeAnnotation"); + } + + case "StringLiteral": + case "NumericLiteral": + case "Literal": + if (typeof node.value === "string" && parent.type === "ExpressionStatement" && !parent.directive) { + // To avoid becoming a directive + const grandParent = path.getParentNode(1); + return grandParent.type === "Program" || grandParent.type === "BlockStatement"; + } + + return parent.type === "MemberExpression" && typeof node.value === "number" && name === "object" && parent.object === node; + + case "AssignmentExpression": + { + const grandParent = path.getParentNode(1); + + if (parent.type === "ArrowFunctionExpression" && parent.body === node) { + return true; + } else if (parent.type === "ClassProperty" && parent.key === node && parent.computed) { + return false; + } else if (parent.type === "TSPropertySignature" && parent.name === node) { + return false; + } else if (parent.type === "ForStatement" && (parent.init === node || parent.update === node)) { + return false; + } else if (parent.type === "ExpressionStatement") { + return node.left.type === "ObjectPattern"; + } else if (parent.type === "TSPropertySignature" && parent.key === node) { + return false; + } else if (parent.type === "AssignmentExpression") { + return false; + } else if (parent.type === "SequenceExpression" && grandParent && grandParent.type === "ForStatement" && (grandParent.init === parent || grandParent.update === parent)) { + return false; + } else if (parent.type === "Property" && parent.value === node) { + return false; + } else if (parent.type === "NGChainedExpression") { + return false; + } + + return true; + } + + case "ConditionalExpression": + switch (parent.type) { + case "TaggedTemplateExpression": + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "BinaryExpression": + case "LogicalExpression": + case "NGPipeExpression": + case "ExportDefaultDeclaration": + case "AwaitExpression": + case "JSXSpreadAttribute": + case "TSTypeAssertion": + case "TypeCastExpression": + case "TSAsExpression": + case "TSNonNullExpression": + return true; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ConditionalExpression": + return name === "test" && parent.test === node; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + default: + return false; + } + + case "FunctionExpression": + switch (parent.type) { + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses. + // Is necessary if it is `expression` of `ExpressionStatement`. + return name === "callee"; + + case "TaggedTemplateExpression": + return true; + // This is basically a kind of IIFE. + + default: + return false; + } + + case "ArrowFunctionExpression": + switch (parent.type) { + case "PipelineTopicExpression": + return !!(node.extra && node.extra.parenthesized); + + case "BinaryExpression": + return parent.operator !== "|>" || node.extra && node.extra.parenthesized; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "TSAsExpression": + case "BindExpression": + case "TaggedTemplateExpression": + case "UnaryExpression": + case "LogicalExpression": + case "AwaitExpression": + case "TSTypeAssertion": + return true; + + case "ConditionalExpression": + return name === "test"; + + default: + return false; + } + + case "ClassExpression": + switch (parent.type) { + case "NewExpression": + return name === "callee" && parent.callee === node; + + default: + return false; + } + + case "OptionalMemberExpression": + case "OptionalCallExpression": + { + const parentParent = path.getParentNode(1); + + if (parent.type === "MemberExpression" && name === "object" || (parent.type === "CallExpression" || parent.type === "NewExpression") && name === "callee" || parent.type === "TSNonNullExpression" && parentParent.type === "MemberExpression" && parentParent.object === parent) { + return true; + } + } + // fallthrough + + case "CallExpression": + case "MemberExpression": + case "TaggedTemplateExpression": + case "TSNonNullExpression": + if ((parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee") { + let object = node; + + while (object) { + switch (object.type) { + case "CallExpression": + case "OptionalCallExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + case "BindExpression": + object = object.object; + break; + // tagged templates are basically member expressions from a grammar perspective + // see https://tc39.github.io/ecma262/#prod-MemberExpression + + case "TaggedTemplateExpression": + object = object.tag; + break; + + case "TSNonNullExpression": + object = object.expression; + break; + + default: + return false; + } + } + } + + return false; + + case "BindExpression": + return (parent.type === "BindExpression" || parent.type === "NewExpression") && name === "callee" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && name === "object"; + + case "NGPipeExpression": + if (parent.type === "NGRoot" || parent.type === "NGMicrosyntaxExpression" || parent.type === "ObjectProperty" && // Preserve parens for compatibility with AngularJS expressions + !(node.extra && node.extra.parenthesized) || parent.type === "ArrayExpression" || (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.arguments[name] === node || parent.type === "NGPipeExpression" && name === "right" || parent.type === "MemberExpression" && name === "property" || parent.type === "AssignmentExpression") { + return false; + } + + return true; + + case "JSXFragment": + case "JSXElement": + return name === "callee" || parent.type === "BinaryExpression" && parent.operator === "<" && name === "left" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "CallExpression" && parent.type !== "NewExpression" && parent.type !== "ConditionalExpression" && parent.type !== "ExpressionStatement" && parent.type !== "JsExpressionRoot" && parent.type !== "JSXAttribute" && parent.type !== "JSXElement" && parent.type !== "JSXExpressionContainer" && parent.type !== "JSXFragment" && parent.type !== "LogicalExpression" && parent.type !== "ObjectProperty" && parent.type !== "OptionalCallExpression" && parent.type !== "Property" && parent.type !== "ReturnStatement" && parent.type !== "ThrowStatement" && parent.type !== "TypeCastExpression" && parent.type !== "VariableDeclarator"; + + case "TypeAnnotation": + return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node); + } + + return false; +} + +function isStatement(node) { + return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "EnumDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSDeclareFunction" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement"; +} + +function includesFunctionTypeInObjectType(node) { + return hasNode$1(node, n1 => n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined) || undefined); +} + +function endsWithRightBracket(node) { + switch (node.type) { + case "ObjectExpression": + return true; + + default: + return false; + } +} + +function isFollowedByRightBracket(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + const name = path.getName(); + + switch (parent.type) { + case "NGPipeExpression": + if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "ObjectProperty": + if (name === "value") { + const parentParent = path.getParentNode(1); + return parentParent.properties[parentParent.properties.length - 1] === parent; + } + + break; + + case "BinaryExpression": + case "LogicalExpression": + if (name === "right") { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "ConditionalExpression": + if (name === "alternate") { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "UnaryExpression": + if (parent.prefix) { + return path.callParent(isFollowedByRightBracket); + } + + break; + } + + return false; +} + +function shouldWrapFunctionForExportDefault(path, options) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (node.type === "FunctionExpression" || node.type === "ClassExpression") { + return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped + // (e.g. `export default (function() {})();`) + // in this case we don't need to add extra parens + !needsParens(path, options); + } + + if (!hasNakedLeftSide$1(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) { + return false; + } + + return path.call(childPath => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName$1(path, node)); +} + +var needsParens_1 = needsParens; + +const { + builders: { + concat: concat$6, + join: join$3, + line: line$4 + } +} = document; + +function printHtmlBinding(path, options, print) { + const node = path.getValue(); + + if (options.__onHtmlBindingRoot && path.getName() === null) { + options.__onHtmlBindingRoot(node, options); + } + + if (node.type !== "File") { + return; + } + + if (options.__isVueForBindingLeft) { + return path.call(functionDeclarationPath => { + const { + params + } = functionDeclarationPath.getValue(); + return concat$6([params.length > 1 ? "(" : "", join$3(concat$6([",", line$4]), functionDeclarationPath.map(print, "params")), params.length > 1 ? ")" : ""]); + }, "program", "body", 0); + } + + if (options.__isVueSlotScope) { + return path.call(functionDeclarationPath => join$3(concat$6([",", line$4]), functionDeclarationPath.map(print, "params")), "program", "body", 0); + } +} // based on https://github.com/prettier/prettier/blob/master/src/language-html/syntax-vue.js isVueEventBindingExpression() + + +function isVueEventBindingExpression(node) { + switch (node.type) { + case "MemberExpression": + switch (node.property.type) { + case "Identifier": + case "NumericLiteral": + case "StringLiteral": + return isVueEventBindingExpression(node.object); + } + + return false; + + case "Identifier": + return true; + + default: + return false; + } +} + +var htmlBinding = { + isVueEventBindingExpression, + printHtmlBinding +}; + +function preprocess(ast, options) { + switch (options.parser) { + case "json": + case "json5": + case "json-stringify": + case "__js_expression": + case "__vue_expression": + return Object.assign({}, ast, { + type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot", + node: ast, + comments: [], + rootMarker: options.rootMarker + }); + + default: + return ast; + } +} + +var preprocess_1 = preprocess; + +const { + getLast: getLast$3, + getPenultimate: getPenultimate$1, + isNextLineEmpty: isNextLineEmpty$2 +} = util; +const { + hasLeadingComment: hasLeadingComment$3, + hasTrailingComment: hasTrailingComment$1, + isFunctionCompositionArgs: isFunctionCompositionArgs$1, + isJSXNode: isJSXNode$1, + isLongCurriedCallExpression: isLongCurriedCallExpression$1, + shouldPrintComma: shouldPrintComma$1 +} = utils$6; +const { + builders: { + concat: concat$7, + line: line$5, + hardline: hardline$4, + softline: softline$2, + group: group$2, + indent: indent$3, + conditionalGroup: conditionalGroup$1, + ifBreak: ifBreak$1, + breakParent: breakParent$2 + }, + utils: { + willBreak: willBreak$1 + } +} = document; + +function printCallArguments(path, options, print) { + const node = path.getValue(); + const isDynamicImport = node.type === "ImportExpression"; + const args = isDynamicImport ? [node.source] : node.arguments; + + if (args.length === 0) { + return concat$7(["(", comments.printDanglingComments(path, options, + /* sameIndent */ + true), ")"]); + } // useEffect(() => { ... }, [foo, bar, baz]) + + + if (args.length === 2 && args[0].type === "ArrowFunctionExpression" && args[0].params.length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.some(arg => arg.comments)) { + return concat$7(["(", path.call(print, "arguments", 0), ", ", path.call(print, "arguments", 1), ")"]); + } // func( + // ({ + // a, + // + // b + // }) => {} + // ); + + + function shouldBreakForArrowFunctionInArguments(arg, argPath) { + if (!arg || arg.type !== "ArrowFunctionExpression" || !arg.body || arg.body.type !== "BlockStatement" || !arg.params || arg.params.length < 1) { + return false; + } + + let shouldBreak = false; + argPath.each(paramPath => { + const printed = concat$7([print(paramPath)]); + shouldBreak = shouldBreak || willBreak$1(printed); + }, "params"); + return shouldBreak; + } + + let anyArgEmptyLine = false; + let shouldBreakForArrowFunction = false; + let hasEmptyLineFollowingFirstArg = false; + const lastArgIndex = args.length - 1; + + const printArgument = (argPath, index) => { + const arg = argPath.getNode(); + const parts = [print(argPath)]; + + if (index === lastArgIndex) ; else if (isNextLineEmpty$2(options.originalText, arg, options.locEnd)) { + if (index === 0) { + hasEmptyLineFollowingFirstArg = true; + } + + anyArgEmptyLine = true; + parts.push(",", hardline$4, hardline$4); + } else { + parts.push(",", line$5); + } + + shouldBreakForArrowFunction = shouldBreakForArrowFunctionInArguments(arg, argPath); + return concat$7(parts); + }; + + const printedArguments = isDynamicImport ? [path.call(path => printArgument(path, 0), "source")] : path.map(printArgument, "arguments"); + const maybeTrailingComma = // Dynamic imports cannot have trailing commas + !(isDynamicImport || node.callee && node.callee.type === "Import") && shouldPrintComma$1(options, "all") ? "," : ""; + + function allArgsBrokenOut() { + return group$2(concat$7(["(", indent$3(concat$7([line$5, concat$7(printedArguments)])), maybeTrailingComma, line$5, ")"]), { + shouldBreak: true + }); + } + + if (path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs$1(args)) { + return allArgsBrokenOut(); + } + + const shouldGroupFirst = shouldGroupFirstArg(args); + const shouldGroupLast = shouldGroupLastArg(args); + + if (shouldGroupFirst || shouldGroupLast) { + const shouldBreak = (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$1) : printedArguments.slice(0, -1).some(willBreak$1)) || anyArgEmptyLine || shouldBreakForArrowFunction; // We want to print the last argument with a special flag + + let printedExpanded = []; + let i = 0; + + const printArgument = argPath => { + if (shouldGroupFirst && i === 0) { + printedExpanded = [concat$7([argPath.call(p => print(p, { + expandFirstArg: true + })), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$4 : line$5, hasEmptyLineFollowingFirstArg ? hardline$4 : ""])].concat(printedArguments.slice(1)); + } + + if (shouldGroupLast && i === args.length - 1) { + printedExpanded = printedArguments.slice(0, -1).concat(argPath.call(p => print(p, { + expandLastArg: true + }))); + } + + i++; + }; + + if (isDynamicImport) { + path.call(printArgument, "source"); + } else { + path.each(printArgument, "arguments"); + } + + const somePrintedArgumentsWillBreak = printedArguments.some(willBreak$1); + const simpleConcat = concat$7(["(", concat$7(printedExpanded), ")"]); + return concat$7([somePrintedArgumentsWillBreak ? breakParent$2 : "", conditionalGroup$1([!somePrintedArgumentsWillBreak && !node.typeArguments && !node.typeParameters ? simpleConcat : ifBreak$1(allArgsBrokenOut(), simpleConcat), shouldGroupFirst ? concat$7(["(", group$2(printedExpanded[0], { + shouldBreak: true + }), concat$7(printedExpanded.slice(1)), ")"]) : concat$7(["(", concat$7(printedArguments.slice(0, -1)), group$2(getLast$3(printedExpanded), { + shouldBreak: true + }), ")"]), allArgsBrokenOut()], { + shouldBreak + })]); + } + + const contents = concat$7(["(", indent$3(concat$7([softline$2, concat$7(printedArguments)])), ifBreak$1(maybeTrailingComma), softline$2, ")"]); + + if (isLongCurriedCallExpression$1(path)) { + // By not wrapping the arguments in a group, the printer prioritizes + // breaking up these arguments rather than the args of the parent call. + return contents; + } + + return group$2(contents, { + shouldBreak: printedArguments.some(willBreak$1) || anyArgEmptyLine + }); +} + +function couldGroupArg(arg) { + return arg.type === "ObjectExpression" && (arg.properties.length > 0 || arg.comments) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || arg.comments) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords + // https://github.com/prettier/prettier/issues/4070 + // export class Thing implements OtherThing { + // do: (type: Type) => Provider = memoize( + // (type: ObjectType): Provider => {} + // ); + // } + // https://github.com/prettier/prettier/issues/6099 + // app.get("/", (req, res): void => { + // res.send("Hello World!"); + // }); + !arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference") && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || arg.body.type === "CallExpression" || arg.body.type === "OptionalCallExpression" || arg.body.type === "ConditionalExpression" || isJSXNode$1(arg.body)); +} + +function shouldGroupLastArg(args) { + const lastArg = getLast$3(args); + const penultimateArg = getPenultimate$1(args); + return !hasLeadingComment$3(lastArg) && !hasTrailingComment$1(lastArg) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type, + // disable last element expansion. + !penultimateArg || penultimateArg.type !== lastArg.type); +} + +function shouldGroupFirstArg(args) { + if (args.length !== 2) { + return false; + } + + const [firstArg, secondArg] = args; + return (!firstArg.comments || !firstArg.comments.length) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg); +} + +var callArguments = printCallArguments; + +const { + isNumericLiteral: isNumericLiteral$1 +} = utils$6; +const { + builders: { + concat: concat$8, + softline: softline$3, + group: group$3, + indent: indent$4 + } +} = document; + +function printOptionalToken(path) { + const node = path.getValue(); + + if (!node.optional || // It's an optional computed method parsed by typescript-estree. + // "?" is printed in `printMethod`. + node.type === "Identifier" && node === path.getParentNode().key) { + return ""; + } + + if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) { + return "?."; + } + + return "?"; +} + +function printFunctionTypeParameters(path, options, print) { + const fun = path.getValue(); + + if (fun.typeArguments) { + return path.call(print, "typeArguments"); + } + + if (fun.typeParameters) { + return path.call(print, "typeParameters"); + } + + return ""; +} + +function printMemberLookup(path, options, print) { + const property = path.call(print, "property"); + const n = path.getValue(); + const optional = printOptionalToken(path); + + if (!n.computed) { + return concat$8([optional, ".", property]); + } + + if (!n.property || isNumericLiteral$1(n.property)) { + return concat$8([optional, "[", property, "]"]); + } + + return group$3(concat$8([optional, "[", indent$4(concat$8([softline$3, property])), softline$3, "]"])); +} + +function printBindExpressionCallee(path, options, print) { + return concat$8(["::", path.call(print, "callee")]); +} + +var misc = { + printOptionalToken, + printFunctionTypeParameters, + printMemberLookup, + printBindExpressionCallee +}; + +const { + getLast: getLast$4, + isNextLineEmpty: isNextLineEmpty$3, + isNextLineEmptyAfterIndex: isNextLineEmptyAfterIndex$2, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$3 +} = util; +const { + hasLeadingComment: hasLeadingComment$4, + hasTrailingComment: hasTrailingComment$2, + isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$1, + isFunctionOrArrowExpression: isFunctionOrArrowExpression$1, + isLongCurriedCallExpression: isLongCurriedCallExpression$2, + isMemberish: isMemberish$1, + isNumericLiteral: isNumericLiteral$2, + isSimpleCallArgument: isSimpleCallArgument$1 +} = utils$6; +const { + builders: { + concat: concat$9, + join: join$4, + hardline: hardline$5, + group: group$4, + indent: indent$5, + conditionalGroup: conditionalGroup$2, + breakParent: breakParent$3 + }, + utils: { + willBreak: willBreak$2 + } +} = document; +const { + printOptionalToken: printOptionalToken$1, + printFunctionTypeParameters: printFunctionTypeParameters$1, + printMemberLookup: printMemberLookup$1, + printBindExpressionCallee: printBindExpressionCallee$1 +} = misc; // We detect calls on member expressions specially to format a +// common pattern better. The pattern we are looking for is this: +// +// arr +// .map(x => x + 1) +// .filter(x => x > 10) +// .some(x => x % 2) +// +// The way it is structured in the AST is via a nested sequence of +// MemberExpression and CallExpression. We need to traverse the AST +// and make groups out of it to print it in the desired way. + +function printMemberChain(path, options, print) { + const parent = path.getParentNode(); + const isExpressionStatement = !parent || parent.type === "ExpressionStatement"; // The first phase is to linearize the AST by traversing it down. + // + // a().b() + // has the following AST structure: + // CallExpression(MemberExpression(CallExpression(Identifier))) + // and we transform it into + // [Identifier, CallExpression, MemberExpression, CallExpression] + + const printedNodes = []; // Here we try to retain one typed empty line after each call expression or + // the first group whether it is in parentheses or not + + function shouldInsertEmptyLineAfter(node) { + const { + originalText + } = options; + const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$3(originalText, node, options.locEnd); + const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty + // line after that parenthesis + + if (nextChar === ")") { + return nextCharIndex !== false && isNextLineEmptyAfterIndex$2(originalText, nextCharIndex + 1); + } + + return isNextLineEmpty$3(originalText, node, options.locEnd); + } + + function rec(path) { + const node = path.getValue(); + + if (isCallOrOptionalCallExpression$1(node) && (isMemberish$1(node.callee) || isCallOrOptionalCallExpression$1(node.callee))) { + printedNodes.unshift({ + node, + printed: concat$9([comments.printComments(path, () => concat$9([printOptionalToken$1(path), printFunctionTypeParameters$1(path, options, print), callArguments(path, options, print)]), options), shouldInsertEmptyLineAfter(node) ? hardline$5 : ""]) + }); + path.call(callee => rec(callee), "callee"); + } else if (isMemberish$1(node)) { + printedNodes.unshift({ + node, + needsParens: needsParens_1(path, options), + printed: comments.printComments(path, () => node.type === "OptionalMemberExpression" || node.type === "MemberExpression" ? printMemberLookup$1(path, options, print) : printBindExpressionCallee$1(path, options, print), options) + }); + path.call(object => rec(object), "object"); + } else if (node.type === "TSNonNullExpression") { + printedNodes.unshift({ + node, + printed: comments.printComments(path, () => "!", options) + }); + path.call(expression => rec(expression), "expression"); + } else { + printedNodes.unshift({ + node, + printed: path.call(print) + }); + } + } // Note: the comments of the root node have already been printed, so we + // need to extract this first call without printing them as they would + // if handled inside of the recursive call. + + + const node = path.getValue(); + printedNodes.unshift({ + node, + printed: concat$9([printOptionalToken$1(path), printFunctionTypeParameters$1(path, options, print), callArguments(path, options, print)]) + }); + + if (node.callee) { + path.call(callee => rec(callee), "callee"); + } // Once we have a linear list of printed nodes, we want to create groups out + // of it. + // + // a().b.c().d().e + // will be grouped as + // [ + // [Identifier, CallExpression], + // [MemberExpression, MemberExpression, CallExpression], + // [MemberExpression, CallExpression], + // [MemberExpression], + // ] + // so that we can print it as + // a() + // .b.c() + // .d() + // .e + // The first group is the first node followed by + // - as many CallExpression as possible + // < fn()()() >.something() + // - as many array accessors as possible + // < fn()[0][1][2] >.something() + // - then, as many MemberExpression as possible but the last one + // < this.items >.something() + + + const groups = []; + let currentGroup = [printedNodes[0]]; + let i = 1; + + for (; i < printedNodes.length; ++i) { + if (printedNodes[i].node.type === "TSNonNullExpression" || isCallOrOptionalCallExpression$1(printedNodes[i].node) || (printedNodes[i].node.type === "MemberExpression" || printedNodes[i].node.type === "OptionalMemberExpression") && printedNodes[i].node.computed && isNumericLiteral$2(printedNodes[i].node.property)) { + currentGroup.push(printedNodes[i]); + } else { + break; + } + } + + if (!isCallOrOptionalCallExpression$1(printedNodes[0].node)) { + for (; i + 1 < printedNodes.length; ++i) { + if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) { + currentGroup.push(printedNodes[i]); + } else { + break; + } + } + } + + groups.push(currentGroup); + currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by + // a sequence of CallExpression. To compute it, we keep adding things to the + // group until we has seen a CallExpression in the past and reach a + // MemberExpression + + let hasSeenCallExpression = false; + + for (; i < printedNodes.length; ++i) { + if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) { + // [0] should be appended at the end of the group instead of the + // beginning of the next one + if (printedNodes[i].node.computed && isNumericLiteral$2(printedNodes[i].node.property)) { + currentGroup.push(printedNodes[i]); + continue; + } + + groups.push(currentGroup); + currentGroup = []; + hasSeenCallExpression = false; + } + + if (isCallOrOptionalCallExpression$1(printedNodes[i].node) || printedNodes[i].node.type === "ImportExpression") { + hasSeenCallExpression = true; + } + + currentGroup.push(printedNodes[i]); + + if (printedNodes[i].node.comments && printedNodes[i].node.comments.some(comment => comment.trailing)) { + groups.push(currentGroup); + currentGroup = []; + hasSeenCallExpression = false; + } + } + + if (currentGroup.length > 0) { + groups.push(currentGroup); + } // There are cases like Object.keys(), Observable.of(), _.values() where + // they are the subject of all the chained calls and therefore should + // be kept on the same line: + // + // Object.keys(items) + // .filter(x => x) + // .map(x => x) + // + // In order to detect those cases, we use an heuristic: if the first + // node is an identifier with the name starting with a capital + // letter or just a sequence of _$. The rationale is that they are + // likely to be factories. + + + function isFactory(name) { + return /^[A-Z]|^[$_]+$/.test(name); + } // In case the Identifier is shorter than tab width, we can keep the + // first call in a single line, if it's an ExpressionStatement. + // + // d3.scaleLinear() + // .domain([0, 100]) + // .range([0, width]); + // + + + function isShort(name) { + return name.length <= options.tabWidth; + } + + function shouldNotWrap(groups) { + const hasComputed = groups[1].length && groups[1][0].node.computed; + + if (groups[0].length === 1) { + const firstNode = groups[0][0].node; + return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpressionStatement && isShort(firstNode.name) || hasComputed); + } + + const lastNode = getLast$4(groups[0]).node; + return (lastNode.type === "MemberExpression" || lastNode.type === "OptionalMemberExpression") && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed); + } + + const shouldMerge = groups.length >= 2 && !groups[1][0].node.comments && shouldNotWrap(groups); + + function printGroup(printedGroup) { + const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print + // accordingly + + if (printedGroup.length > 0 && printedGroup[printedGroup.length - 1].needsParens) { + return concat$9(["(", ...printed, ")"]); + } + + return concat$9(printed); + } + + function printIndentedGroup(groups) { + /* istanbul ignore next */ + if (groups.length === 0) { + return ""; + } + + return indent$5(group$4(concat$9([hardline$5, join$4(hardline$5, groups.map(printGroup))]))); + } + + const printedGroups = groups.map(printGroup); + const oneLine = concat$9(printedGroups); + const cutoff = shouldMerge ? 3 : 2; + const flatGroups = flatten_1(groups); + const hasComment = flatGroups.slice(1, -1).some(node => hasLeadingComment$4(node.node)) || flatGroups.slice(0, -1).some(node => hasTrailingComment$2(node.node)) || groups[cutoff] && hasLeadingComment$4(groups[cutoff][0].node); // If we only have a single `.`, we shouldn't do anything fancy and just + // render everything concatenated together. + + if (groups.length <= cutoff && !hasComment) { + if (isLongCurriedCallExpression$2(path)) { + return oneLine; + } + + return group$4(oneLine); + } // Find out the last node in the first group and check if it has an + // empty line after + + + const lastNodeBeforeIndent = getLast$4(groups[shouldMerge ? 1 : 0]).node; + const shouldHaveEmptyLineBeforeIndent = !isCallOrOptionalCallExpression$1(lastNodeBeforeIndent) && shouldInsertEmptyLineAfter(lastNodeBeforeIndent); + const expanded = concat$9([printGroup(groups[0]), shouldMerge ? concat$9(groups.slice(1, 2).map(printGroup)) : "", shouldHaveEmptyLineBeforeIndent ? hardline$5 : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]); + const callExpressions = printedNodes.map(({ + node + }) => node).filter(isCallOrOptionalCallExpression$1); + + function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() { + const lastGroupNode = getLast$4(getLast$4(groups)).node; + const lastGroupDoc = getLast$4(printedGroups); + return isCallOrOptionalCallExpression$1(lastGroupNode) && willBreak$2(lastGroupDoc) && callExpressions.slice(0, -1).some(n => n.arguments.some(isFunctionOrArrowExpression$1)); + } // We don't want to print in one line if at least one of these conditions occurs: + // * the chain has comments, + // * the chain is an expression statement and all the arguments are literal-like ("fluent configuration" pattern), + // * the chain is longer than 2 calls and has non-trivial arguments or more than 2 arguments in any call but the first one, + // * any group but the last one has a hard line, + // * the last call's arguments have a hard line and other calls have non-trivial arguments. + + + if (hasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument$1(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$2) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments()) { + return group$4(expanded); + } + + return concat$9([// We only need to check `oneLine` because if `expanded` is chosen + // that means that the parent group has already been broken + // naturally + willBreak$2(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$3 : "", conditionalGroup$2([oneLine, expanded])]); +} + +var memberChain = printMemberChain; + +const { + builders: { + concat: concat$a, + softline: softline$4, + group: group$5, + indent: indent$6, + join: join$5, + line: line$6, + ifBreak: ifBreak$2 + } +} = document; +const { + shouldPrintComma: shouldPrintComma$2 +} = utils$6; +/** + * @typedef {import("../../document").Doc} Doc + */ + +function printModuleSource(path, options, print) { + const node = path.getValue(); + return node.source ? concat$a([" from ", path.call(print, "source")]) : ""; +} + +function printModuleSpecifiers(path, options, print) { + const node = path.getValue(); + /** @type{Doc[]} */ + + const parts = [node.type === "ImportDeclaration" ? " " : ""]; + + if (node.specifiers && node.specifiers.length > 0) { + const standalonesSpecifiers = []; + const groupedSpecifiers = []; + path.each(specifierPath => { + const specifierType = path.getValue().type; + + if (specifierType === "ExportNamespaceSpecifier" || specifierType === "ExportDefaultSpecifier" || specifierType === "ImportNamespaceSpecifier" || specifierType === "ImportDefaultSpecifier") { + standalonesSpecifiers.push(print(specifierPath)); + } else if (specifierType === "ExportSpecifier" || specifierType === "ImportSpecifier") { + groupedSpecifiers.push(print(specifierPath)); + } else { + /* istanbul ignore next */ + throw new Error(`Unknown specifier type ${JSON.stringify(specifierType)}`); + } + }, "specifiers"); + parts.push(join$5(", ", standalonesSpecifiers)); + + if (groupedSpecifiers.length !== 0) { + if (standalonesSpecifiers.length !== 0) { + parts.push(", "); + } + + const canBreak = groupedSpecifiers.length > 1 || standalonesSpecifiers.length > 0 || node.specifiers.some(node => node.comments); + + if (canBreak) { + parts.push(group$5(concat$a(["{", indent$6(concat$a([options.bracketSpacing ? line$6 : softline$4, join$5(concat$a([",", line$6]), groupedSpecifiers)])), ifBreak$2(shouldPrintComma$2(options) ? "," : ""), options.bracketSpacing ? line$6 : softline$4, "}"]))); + } else { + parts.push(concat$a(["{", options.bracketSpacing ? " " : "", concat$a(groupedSpecifiers), options.bracketSpacing ? " " : "", "}"])); + } + } + } else { + parts.push("{}"); + } + + return concat$a(parts); +} + +var module$2 = { + printModuleSource, + printModuleSpecifiers +}; + +const { + isJSXNode: isJSXNode$2 +} = utils$6; +const { + hasNewlineInRange: hasNewlineInRange$4 +} = util; +const { + builders: { + concat: concat$b, + line: line$7, + softline: softline$5, + group: group$6, + indent: indent$7, + align: align$1, + ifBreak: ifBreak$3, + dedent: dedent$1, + breakParent: breakParent$4 + } +} = document; +/** + * @typedef {import("../../document").Doc} Doc + * @typedef {import("../../common/fast-path")} FastPath + * + * @typedef {any} Options - Prettier options (TBD ...) + * + * @typedef {Object} OperatorOptions + * @property {() => Array} beforeParts - Parts to print before the `?`. + * @property {(breakClosingParen: boolean) => Array} afterParts - Parts to print after the conditional expression. + * @property {boolean} shouldCheckJsx - Whether to check for and print in JSX mode. + * @property {string} conditionalNodeType - The type of the conditional expression node, ie "ConditionalExpression" or "TSConditionalType". + * @property {string} consequentNodePropertyName - The property at which the consequent node can be found on the main node, eg "consequent". + * @property {string} alternateNodePropertyName - The property at which the alternate node can be found on the main node, eg "alternate". + * @property {string[]} testNodePropertyNames - The properties at which the test nodes can be found on the main node, eg "test". + */ +// If we have nested conditional expressions, we want to print them in JSX mode +// if there's at least one JSXElement somewhere in the tree. +// +// A conditional expression chain like this should be printed in normal mode, +// because there aren't JSXElements anywhere in it: +// +// isA ? "A" : isB ? "B" : isC ? "C" : "Unknown"; +// +// But a conditional expression chain like this should be printed in JSX mode, +// because there is a JSXElement in the last ConditionalExpression: +// +// isA ? "A" : isB ? "B" : isC ? "C" : Unknown; +// +// This type of ConditionalExpression chain is structured like this in the AST: +// +// ConditionalExpression { +// test: ..., +// consequent: ..., +// alternate: ConditionalExpression { +// test: ..., +// consequent: ..., +// alternate: ConditionalExpression { +// test: ..., +// consequent: ..., +// alternate: ..., +// } +// } +// } +// +// We want to traverse over that shape and convert it into a flat structure so +// that we can find if there's a JSXElement somewhere inside. + +function getConditionalChainContents(node) { + // Given this code: + // + // // Using a ConditionalExpression as the consequent is uncommon, but should + // // be handled. + // A ? B : C ? D : E ? F ? G : H : I + // + // which has this AST: + // + // ConditionalExpression { + // test: Identifier(A), + // consequent: Identifier(B), + // alternate: ConditionalExpression { + // test: Identifier(C), + // consequent: Identifier(D), + // alternate: ConditionalExpression { + // test: Identifier(E), + // consequent: ConditionalExpression { + // test: Identifier(F), + // consequent: Identifier(G), + // alternate: Identifier(H), + // }, + // alternate: Identifier(I), + // } + // } + // } + // + // we should return this Array: + // + // [ + // Identifier(A), + // Identifier(B), + // Identifier(C), + // Identifier(D), + // Identifier(E), + // Identifier(F), + // Identifier(G), + // Identifier(H), + // Identifier(I) + // ]; + // + // This loses the information about whether each node was the test, + // consequent, or alternate, but we don't care about that here- we are only + // flattening this structure to find if there's any JSXElements inside. + const nonConditionalExpressions = []; + + function recurse(node) { + if (node.type === "ConditionalExpression") { + recurse(node.test); + recurse(node.consequent); + recurse(node.alternate); + } else { + nonConditionalExpressions.push(node); + } + } + + recurse(node); + return nonConditionalExpressions; +} + +function conditionalExpressionChainContainsJSX(node) { + return getConditionalChainContents(node).some(isJSXNode$2); +} +/** + * The following is the shared logic for + * ternary operators, namely ConditionalExpression + * and TSConditionalType + * @param {FastPath} path - The path to the ConditionalExpression/TSConditionalType node. + * @param {Options} options - Prettier options + * @param {Function} print - Print function to call recursively + * @param {OperatorOptions} operatorOptions + * @returns {Doc} + */ + + +function printTernaryOperator(path, options, print, operatorOptions) { + const node = path.getValue(); + const consequentNode = node[operatorOptions.consequentNodePropertyName]; + const alternateNode = node[operatorOptions.alternateNodePropertyName]; + const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode". + // See tests/jsx/conditional-expression.js for more info. + + let jsxMode = false; + const parent = path.getParentNode(); + const isParentTest = parent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.some(prop => parent[prop] === node); + let forceNoIndent = parent.type === operatorOptions.conditionalNodeType && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost + // ConditionalExpression parent. We'll use these to determine if we should + // print in JSX mode. + + let currentParent; + let previousParent; + let i = 0; + + do { + previousParent = currentParent || node; + currentParent = path.getParentNode(i); + i++; + } while (currentParent && currentParent.type === operatorOptions.conditionalNodeType && operatorOptions.testNodePropertyNames.every(prop => currentParent[prop] !== previousParent)); + + const firstNonConditionalParent = currentParent || parent; + const lastConditionalParent = previousParent; + + if (operatorOptions.shouldCheckJsx && (isJSXNode$2(node[operatorOptions.testNodePropertyNames[0]]) || isJSXNode$2(consequentNode) || isJSXNode$2(alternateNode) || conditionalExpressionChainContainsJSX(lastConditionalParent))) { + jsxMode = true; + forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in + // parens when using ?: within JSX, because the parens are analogous to + // curly braces in an if statement. + + const wrap = doc => concat$b([ifBreak$3("(", ""), indent$7(concat$b([softline$5, doc])), softline$5, ifBreak$3(")", "")]); // The only things we don't wrap are: + // * Nested conditional expressions in alternates + // * null + // * undefined + + + const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined"; + + parts.push(" ? ", isNil(consequentNode) ? path.call(print, operatorOptions.consequentNodePropertyName) : wrap(path.call(print, operatorOptions.consequentNodePropertyName)), " : ", alternateNode.type === operatorOptions.conditionalNodeType || isNil(alternateNode) ? path.call(print, operatorOptions.alternateNodePropertyName) : wrap(path.call(print, operatorOptions.alternateNodePropertyName))); + } else { + // normal mode + const part = concat$b([line$7, "? ", consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$3("", "(") : "", align$1(2, path.call(print, operatorOptions.consequentNodePropertyName)), consequentNode.type === operatorOptions.conditionalNodeType ? ifBreak$3("", ")") : "", line$7, ": ", alternateNode.type === operatorOptions.conditionalNodeType ? path.call(print, operatorOptions.alternateNodePropertyName) : align$1(2, path.call(print, operatorOptions.alternateNodePropertyName))]); + parts.push(parent.type !== operatorOptions.conditionalNodeType || parent[operatorOptions.alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$1(indent$7(part)) : align$1(Math.max(0, options.tabWidth - 2), part)); + } // We want a whole chain of ConditionalExpressions to all + // break if any of them break. That means we should only group around the + // outer-most ConditionalExpression. + + + const comments = flatten_1([...operatorOptions.testNodePropertyNames.map(propertyName => node[propertyName].comments), consequentNode.comments, alternateNode.comments]).filter(Boolean); + const shouldBreak = comments.some(comment => comments$1.isBlockComment(comment) && hasNewlineInRange$4(options.originalText, options.locStart(comment), options.locEnd(comment))); + + const maybeGroup = doc => parent === firstNonConditionalParent ? group$6(doc, { + shouldBreak + }) : shouldBreak ? concat$b([doc, breakParent$4]) : doc; // Break the closing paren to keep the chain right after it: + // (a + // ? b + // : c + // ).call() + + + const breakClosingParen = !jsxMode && (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression" || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed; + const result = maybeGroup(concat$b([].concat((testDoc => + /** + * a + * ? b + * : multiline + * test + * node + * ^^ align(2) + * ? d + * : e + */ + parent.type === operatorOptions.conditionalNodeType && parent[operatorOptions.alternateNodePropertyName] === node ? align$1(2, testDoc) : testDoc)(concat$b(operatorOptions.beforeParts())), forceNoIndent ? concat$b(parts) : indent$7(concat$b(parts)), operatorOptions.afterParts(breakClosingParen)))); + return isParentTest ? group$6(concat$b([indent$7(concat$b([softline$5, result])), softline$5])) : result; +} + +var ternary = printTernaryOperator; + +/** @typedef {import("../document").Doc} Doc */ + +/** @type {import("assert")} */ +// TODO(azz): anything that imports from main shouldn't be in a `language-*` dir. + + +const { + getNextNonSpaceNonCommentCharacter: getNextNonSpaceNonCommentCharacter$2, + hasNewline: hasNewline$5, + hasNewlineInRange: hasNewlineInRange$5, + getLast: getLast$5, + getStringWidth: getStringWidth$3, + printString: printString$1, + printNumber: printNumber$1, + hasIgnoreComment: hasIgnoreComment$2, + hasNodeIgnoreComment: hasNodeIgnoreComment$2, + getIndentSize: getIndentSize$2, + getPreferredQuote: getPreferredQuote$1 +} = util; +const { + isNextLineEmpty: isNextLineEmpty$4, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$4 +} = utilShared; +const { + builders: { + concat: concat$c, + join: join$6, + line: line$8, + hardline: hardline$6, + softline: softline$6, + literalline: literalline$3, + group: group$7, + indent: indent$8, + align: align$2, + conditionalGroup: conditionalGroup$3, + fill: fill$3, + ifBreak: ifBreak$4, + lineSuffixBoundary: lineSuffixBoundary$1, + addAlignmentToDoc: addAlignmentToDoc$2 + }, + utils: { + willBreak: willBreak$3, + isLineNext: isLineNext$1, + isEmpty: isEmpty$1, + removeLines: removeLines$1, + normalizeParts: normalizeParts$1 + }, + printer: { + printDocToString: printDocToString$2 + } +} = document; +const { + insertPragma: insertPragma$1 +} = pragma; +const { + printHtmlBinding: printHtmlBinding$1, + isVueEventBindingExpression: isVueEventBindingExpression$1 +} = htmlBinding; +const { + classChildNeedsASIProtection: classChildNeedsASIProtection$1, + classPropMayCauseASIProblems: classPropMayCauseASIProblems$1, + getFlowVariance: getFlowVariance$1, + getLeftSidePathName: getLeftSidePathName$2, + getParentExportDeclaration: getParentExportDeclaration$1, + getTypeScriptMappedTypeModifier: getTypeScriptMappedTypeModifier$1, + hasDanglingComments: hasDanglingComments$1, + hasFlowAnnotationComment: hasFlowAnnotationComment$1, + hasFlowShorthandAnnotationComment: hasFlowShorthandAnnotationComment$2, + hasLeadingOwnLineComment: hasLeadingOwnLineComment$1, + hasNakedLeftSide: hasNakedLeftSide$2, + hasNewlineBetweenOrAfterDecorators: hasNewlineBetweenOrAfterDecorators$1, + hasNgSideEffect: hasNgSideEffect$1, + hasPrettierIgnore: hasPrettierIgnore$1, + hasTrailingComment: hasTrailingComment$3, + hasTrailingLineComment: hasTrailingLineComment$1, + identity: identity$2, + isBinaryish: isBinaryish$1, + isCallOrOptionalCallExpression: isCallOrOptionalCallExpression$2, + isEmptyJSXElement: isEmptyJSXElement$1, + isExportDeclaration: isExportDeclaration$1, + isFlowAnnotationComment: isFlowAnnotationComment$1, + isFunctionNotation: isFunctionNotation$1, + isGetterOrSetter: isGetterOrSetter$1, + isJestEachTemplateLiteral: isJestEachTemplateLiteral$1, + isJSXNode: isJSXNode$3, + isJSXWhitespaceExpression: isJSXWhitespaceExpression$1, + isLastStatement: isLastStatement$1, + isLiteral: isLiteral$1, + isMeaningfulJSXText: isMeaningfulJSXText$1, + isMemberExpressionChain: isMemberExpressionChain$1, + isMemberish: isMemberish$2, + isNgForOf: isNgForOf$1, + isNumericLiteral: isNumericLiteral$3, + isObjectType: isObjectType$1, + isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1, + isSimpleFlowType: isSimpleFlowType$1, + isSimpleNumber: isSimpleNumber$1, + isSimpleTemplateLiteral: isSimpleTemplateLiteral$1, + isStringLiteral: isStringLiteral$1, + isStringPropSafeToUnquote: isStringPropSafeToUnquote$1, + isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1, + isTestCall: isTestCall$1, + isTheOnlyJSXElementInMarkdown: isTheOnlyJSXElementInMarkdown$1, + isTSXFile: isTSXFile$1, + isTypeAnnotationAFunction: isTypeAnnotationAFunction$1, + matchJsxWhitespaceRegex: matchJsxWhitespaceRegex$1, + needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1, + rawText: rawText$1, + returnArgumentHasLeadingComment: returnArgumentHasLeadingComment$1, + shouldPrintComma: shouldPrintComma$3, + shouldFlatten: shouldFlatten$2, + startsWithNoLookaheadToken: startsWithNoLookaheadToken$2 +} = utils$6; +const { + printOptionalToken: printOptionalToken$2, + printFunctionTypeParameters: printFunctionTypeParameters$2, + printMemberLookup: printMemberLookup$2, + printBindExpressionCallee: printBindExpressionCallee$2 +} = misc; +const { + printModuleSource: printModuleSource$1, + printModuleSpecifiers: printModuleSpecifiers$1 +} = module$2; +const needsQuoteProps = new WeakMap(); +let uid = 0; + +function genericPrint(path, options, printPath, args) { + const node = path.getValue(); + let needsParens = false; + const linesWithoutParens = printPathNoParens(path, options, printPath, args); + + if (!node || isEmpty$1(linesWithoutParens)) { + return linesWithoutParens; + } + + const parentExportDecl = getParentExportDeclaration$1(path); + const decorators = []; + + if (node.type === "ClassMethod" || node.type === "ClassPrivateMethod" || node.type === "ClassProperty" || node.type === "TSAbstractClassProperty" || node.type === "ClassPrivateProperty" || node.type === "MethodDefinition" || node.type === "TSAbstractMethodDefinition" || node.type === "TSDeclareMethod") ; else if (node.decorators && node.decorators.length > 0 && // If the parent node is an export declaration and the decorator + // was written before the export, the export will be responsible + // for printing the decorators. + !(parentExportDecl && options.locStart(parentExportDecl, { + ignoreDecorators: true + }) > options.locStart(node.decorators[0]))) { + const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators$1(node, options); + const separator = shouldBreak ? hardline$6 : line$8; + path.each(decoratorPath => { + let decorator = decoratorPath.getValue(); + + if (decorator.expression) { + decorator = decorator.expression; + } else { + decorator = decorator.callee; + } + + decorators.push(printPath(decoratorPath), separator); + }, "decorators"); + + if (parentExportDecl) { + decorators.unshift(hardline$6); + } + } else if (isExportDeclaration$1(node) && node.declaration && node.declaration.decorators && node.declaration.decorators.length > 0 && // Only print decorators here if they were written before the export, + // otherwise they are printed by the node.declaration + options.locStart(node, { + ignoreDecorators: true + }) > options.locStart(node.declaration.decorators[0])) { + // Export declarations are responsible for printing any decorators + // that logically apply to node.declaration. + path.each(decoratorPath => { + const decorator = decoratorPath.getValue(); + const prefix = decorator.type === "Decorator" ? "" : "@"; + decorators.push(prefix, printPath(decoratorPath), hardline$6); + }, "declaration", "decorators"); + } else { + // Nodes with decorators can't have parentheses, so we can avoid + // computing pathNeedsParens() except in this case. + needsParens = needsParens_1(path, options); + } + + const parts = []; + + if (needsParens) { + parts.unshift("("); + } + + parts.push(linesWithoutParens); + + if (needsParens) { + const node = path.getValue(); + + if (hasFlowShorthandAnnotationComment$2(node)) { + parts.push(" /*"); + parts.push(node.trailingComments[0].value.trimStart()); + parts.push("*/"); + node.trailingComments[0].printed = true; + } + + parts.push(")"); + } + + if (decorators.length > 0) { + return group$7(concat$c(decorators.concat(parts))); + } + + return concat$c(parts); +} + +function printDecorators(path, options, print) { + const node = path.getValue(); + return group$7(concat$c([join$6(line$8, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators$1(node, options) ? hardline$6 : line$8])); +} + +function printPathNoParens(path, options, print, args) { + const n = path.getValue(); + const semi = options.semi ? ";" : ""; + + if (!n) { + return ""; + } + + if (typeof n === "string") { + return n; + } + + const htmlBinding = printHtmlBinding$1(path, options, print); + + if (htmlBinding) { + return htmlBinding; + } + /** @type{Doc[]} */ + + + let parts = []; + + switch (n.type) { + case "JsExpressionRoot": + return path.call(print, "node"); + + case "JsonRoot": + return concat$c([path.call(print, "node"), hardline$6]); + + case "File": + // Print @babel/parser's InterpreterDirective here so that + // leading comments on the `Program` node get printed after the hashbang. + if (n.program && n.program.interpreter) { + parts.push(path.call(programPath => programPath.call(print, "interpreter"), "program")); + } + + parts.push(path.call(print, "program")); + return concat$c(parts); + + case "Program": + { + const hasContents = !n.body.every(({ + type + }) => type === "EmptyStatement") || n.comments; // Babel 6 + + if (n.directives) { + const directivesCount = n.directives.length; + path.map((childPath, index) => { + parts.push(print(childPath), semi, hardline$6); + + if ((index < directivesCount - 1 || hasContents) && isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) { + parts.push(hardline$6); + } + }, "directives"); + } + + parts.push(path.call(bodyPath => { + return printStatementSequence(bodyPath, options, print); + }, "body")); + parts.push(comments.printDanglingComments(path, options, + /* sameIndent */ + true)); // Only force a trailing newline if there were any contents. + + if (hasContents) { + parts.push(hardline$6); + } + + return concat$c(parts); + } + // Babel extension. + + case "EmptyStatement": + return ""; + + case "ExpressionStatement": + // Detect Flow and TypeScript directives + if (n.directive) { + return concat$c([nodeStr(n.expression, options, true), semi]); + } + + if (options.parser === "__vue_event_binding") { + const parent = path.getParentNode(); + + if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === n) { + return concat$c([path.call(print, "expression"), isVueEventBindingExpression$1(n.expression) ? ";" : ""]); + } + } // Do not append semicolon after the only JSX element in a program + + + return concat$c([path.call(print, "expression"), isTheOnlyJSXElementInMarkdown$1(options, path) ? "" : semi]); + // Babel non-standard node. Used for Closure-style type casts. See postprocess.js. + + case "ParenthesizedExpression": + { + const shouldHug = !n.expression.comments; + + if (shouldHug) { + return concat$c(["(", path.call(print, "expression"), ")"]); + } + + return group$7(concat$c(["(", indent$8(concat$c([softline$6, path.call(print, "expression")])), softline$6, ")"])); + } + + case "AssignmentExpression": + return printAssignment(n.left, path.call(print, "left"), concat$c([" ", n.operator]), n.right, path.call(print, "right"), options); + + case "BinaryExpression": + case "LogicalExpression": + case "NGPipeExpression": + { + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + const isInsideParenthesis = n !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement"); + const parts = printBinaryishExpressions(path, print, options, + /* isNested */ + false, isInsideParenthesis); // if ( + // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft + // ) { + // + // looks super weird, we want to break the children if the parent breaks + // + // if ( + // this.hasPlugin("dynamicImports") && + // this.lookahead().type === tt.parenLeft + // ) { + + if (isInsideParenthesis) { + return concat$c(parts); + } // Break between the parens in + // unaries or in a member or specific call expression, i.e. + // + // ( + // a && + // b && + // c + // ).call() + + + if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || parent.type === "UnaryExpression" || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && !parent.computed) { + return group$7(concat$c([indent$8(concat$c([softline$6, concat$c(parts)])), softline$6])); + } // Avoid indenting sub-expressions in some cases where the first sub-expression is already + // indented accordingly. We should indent sub-expressions where the first case isn't indented. + + + const shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "ThrowStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || n.operator !== "|" && parent.type === "JsExpressionRoot" || n.type !== "NGPipeExpression" && (parent.type === "NGRoot" && options.parser === "__ng_binding" || parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || n === parent.body && parent.type === "ArrowFunctionExpression" || n !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "ThrowStatement" && parentParent.type !== "CallExpression" && parentParent.type !== "OptionalCallExpression" || parent.type === "TemplateLiteral"; + const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || parent.type === "ObjectProperty" || parent.type === "Property"; + const samePrecedenceSubExpression = isBinaryish$1(n.left) && shouldFlatten$2(n.operator, n.left.operator); + + if (shouldNotIndent || shouldInlineLogicalExpression(n) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression(n) && shouldIndentIfInlining) { + return group$7(concat$c(parts)); + } + + if (parts.length === 0) { + return ""; + } // If the right part is a JSX node, we include it in a separate group to + // prevent it breaking the whole chain, so we can print the expression like: + // + // foo && bar && ( + // + // + // + // ) + + + const hasJSX = isJSXNode$3(n.right); + const firstGroupIndex = parts.findIndex(part => typeof part !== "string" && part.type === "group"); // Separate the leftmost expression, possibly with its leading comments. + + const headParts = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1); + const rest = concat$c(parts.slice(headParts.length, hasJSX ? -1 : undefined)); + const groupId = Symbol("logicalChain-" + ++uid); + const chain = group$7(concat$c([// Don't include the initial expression in the indentation + // level. The first item is guaranteed to be the first + // left-most expression. + ...headParts, indent$8(rest)]), { + id: groupId + }); + + if (!hasJSX) { + return chain; + } + + const jsxPart = getLast$5(parts); + return group$7(concat$c([chain, ifBreak$4(indent$8(jsxPart), jsxPart, { + groupId + })])); + } + + case "AssignmentPattern": + return concat$c([path.call(print, "left"), " = ", path.call(print, "right")]); + + case "TSTypeAssertion": + { + const shouldBreakAfterCast = !(n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression"); + const castGroup = group$7(concat$c(["<", indent$8(concat$c([softline$6, path.call(print, "typeAnnotation")])), softline$6, ">"])); + const exprContents = concat$c([ifBreak$4("("), indent$8(concat$c([softline$6, path.call(print, "expression")])), softline$6, ifBreak$4(")")]); + + if (shouldBreakAfterCast) { + return conditionalGroup$3([concat$c([castGroup, path.call(print, "expression")]), concat$c([castGroup, group$7(exprContents, { + shouldBreak: true + })]), concat$c([castGroup, path.call(print, "expression")])]); + } + + return group$7(concat$c([castGroup, path.call(print, "expression")])); + } + + case "OptionalMemberExpression": + case "MemberExpression": + { + const parent = path.getParentNode(); + let firstNonMemberParent; + let i = 0; + + do { + firstNonMemberParent = path.getParentNode(i); + i++; + } while (firstNonMemberParent && (firstNonMemberParent.type === "MemberExpression" || firstNonMemberParent.type === "OptionalMemberExpression" || firstNonMemberParent.type === "TSNonNullExpression")); + + const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "VariableDeclarator" && firstNonMemberParent.id.type !== "Identifier" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || n.computed || n.object.type === "Identifier" && n.property.type === "Identifier" && parent.type !== "MemberExpression" && parent.type !== "OptionalMemberExpression"; + return concat$c([path.call(print, "object"), shouldInline ? printMemberLookup$2(path, options, print) : group$7(indent$8(concat$c([softline$6, printMemberLookup$2(path, options, print)])))]); + } + + case "MetaProperty": + return concat$c([path.call(print, "meta"), ".", path.call(print, "property")]); + + case "BindExpression": + if (n.object) { + parts.push(path.call(print, "object")); + } + + parts.push(group$7(indent$8(concat$c([softline$6, printBindExpressionCallee$2(path, options, print)])))); + return concat$c(parts); + + case "Identifier": + { + return concat$c([n.name, printOptionalToken$2(path), printTypeAnnotation(path, options, print)]); + } + + case "V8IntrinsicIdentifier": + return concat$c(["%", n.name]); + + case "SpreadElement": + case "SpreadElementPattern": + case "SpreadProperty": + case "SpreadPropertyPattern": + case "RestElement": + case "ObjectTypeSpreadProperty": + return concat$c(["...", path.call(print, "argument"), printTypeAnnotation(path, options, print)]); + + case "FunctionDeclaration": + case "FunctionExpression": + parts.push(printFunctionDeclaration(path, print, options)); + + if (!n.body) { + parts.push(semi); + } + + return concat$c(parts); + + case "ArrowFunctionExpression": + { + if (n.async) { + parts.push("async "); + } + + if (shouldPrintParamsWithoutParens(path, options)) { + parts.push(path.call(print, "params", 0)); + } else { + parts.push(group$7(concat$c([printFunctionParams(path, print, options, + /* expandLast */ + args && (args.expandLastArg || args.expandFirstArg), + /* printTypeParams */ + true), printReturnType(path, print, options)]))); + } + + const dangling = comments.printDanglingComments(path, options, + /* sameIndent */ + true, comment => { + const nextCharacter = getNextNonSpaceNonCommentCharacterIndex$4(options.originalText, comment, options.locEnd); + return nextCharacter !== false && options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>"; + }); + + if (dangling) { + parts.push(" ", dangling); + } + + parts.push(" =>"); + const body = path.call(bodyPath => print(bodyPath, args), "body"); // We want to always keep these types of nodes on the same line + // as the arrow. + + if (!hasLeadingOwnLineComment$1(options.originalText, n.body, options) && (n.body.type === "ArrayExpression" || n.body.type === "ObjectExpression" || n.body.type === "BlockStatement" || isJSXNode$3(n.body) || isTemplateOnItsOwnLine$1(n.body, options.originalText, options) || n.body.type === "ArrowFunctionExpression" || n.body.type === "DoExpression")) { + return group$7(concat$c([concat$c(parts), " ", body])); + } // We handle sequence expressions as the body of arrows specially, + // so that the required parentheses end up on their own lines. + + + if (n.body.type === "SequenceExpression") { + return group$7(concat$c([concat$c(parts), group$7(concat$c([" (", indent$8(concat$c([softline$6, body])), softline$6, ")"]))])); + } // if the arrow function is expanded as last argument, we are adding a + // level of indentation and need to add a softline to align the closing ) + // with the opening (, or if it's inside a JSXExpression (e.g. an attribute) + // we should align the expression's closing } with the line with the opening {. + + + const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !(n.comments && n.comments.length); + const printTrailingComma = args && args.expandLastArg && shouldPrintComma$3(options, "all"); // In order to avoid confusion between + // a => a ? a : a + // a <= a ? a : a + + const shouldAddParens = n.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken$2(n.body, + /* forbidFunctionAndClass */ + false); + return group$7(concat$c([concat$c(parts), group$7(concat$c([indent$8(concat$c([line$8, shouldAddParens ? ifBreak$4("", "(") : "", body, shouldAddParens ? ifBreak$4("", ")") : ""])), shouldAddSoftLine ? concat$c([ifBreak$4(printTrailingComma ? "," : ""), softline$6]) : ""]))])); + } + + case "YieldExpression": + parts.push("yield"); + + if (n.delegate) { + parts.push("*"); + } + + if (n.argument) { + parts.push(" ", path.call(print, "argument")); + } + + return concat$c(parts); + + case "AwaitExpression": + { + parts.push("await"); + + if (n.argument) { + parts.push(" ", path.call(print, "argument")); + } + + const parent = path.getParentNode(); + + if ((parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && parent.callee === n || (parent.type === "MemberExpression" || parent.type === "OptionalMemberExpression") && parent.object === n) { + return group$7(concat$c([indent$8(concat$c([softline$6, concat$c(parts)])), softline$6])); + } + + return concat$c(parts); + } + + case "ImportSpecifier": + if (n.importKind) { + parts.push(path.call(print, "importKind"), " "); + } + + parts.push(path.call(print, "imported")); + + if (n.local && n.local.name !== n.imported.name) { + parts.push(" as ", path.call(print, "local")); + } + + return concat$c(parts); + + case "ExportSpecifier": + parts.push(path.call(print, "local")); + + if (n.exported && n.exported.name !== n.local.name) { + parts.push(" as ", path.call(print, "exported")); + } + + return concat$c(parts); + + case "ImportNamespaceSpecifier": + parts.push("* as "); + parts.push(path.call(print, "local")); + return concat$c(parts); + + case "ImportDefaultSpecifier": + return path.call(print, "local"); + + case "TSExportAssignment": + return concat$c(["export = ", path.call(print, "expression"), semi]); + + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + return printExportDeclaration(path, options, print); + + case "DeclareExportDeclaration": + return concat$c(["declare ", printExportDeclaration(path, options, print)]); + + case "ExportAllDeclaration": + parts.push("export"); + + if (n.exportKind === "type") { + parts.push(" type"); + } + + parts.push(" *"); + + if (n.exported) { + parts.push(" as ", path.call(print, "exported")); + } + + parts.push(printModuleSource$1(path, options, print), semi); + return concat$c(parts); + + case "ExportNamespaceSpecifier": + return concat$c(["* as ", path.call(print, "exported")]); + + case "ExportDefaultSpecifier": + return path.call(print, "exported"); + + case "ImportDeclaration": + { + parts.push("import"); + + if (n.importKind && n.importKind !== "value") { + parts.push(" ", n.importKind); + } + + if (n.specifiers && n.specifiers.length > 0) { + parts.push(printModuleSpecifiers$1(path, options, print)); + parts.push(printModuleSource$1(path, options, print)); + } else if (n.importKind && n.importKind === "type" || // import {} from 'x' + /{\s*}/.test(options.originalText.slice(options.locStart(n), options.locStart(n.source)))) { + parts.push(" {}", printModuleSource$1(path, options, print)); + } else { + parts.push(" ", path.call(print, "source")); + } + + if (Array.isArray(n.attributes) && n.attributes.length !== 0) { + parts.push(" with ", concat$c(path.map(print, "attributes"))); + } + + parts.push(semi); + return concat$c(parts); + } + + case "ImportAttribute": + return concat$c([path.call(print, "key"), ": ", path.call(print, "value")]); + + case "Import": + return "import"; + + case "TSModuleBlock": + case "BlockStatement": + { + const naked = path.call(bodyPath => { + return printStatementSequence(bodyPath, options, print); + }, "body"); + const hasContent = n.body.some(node => node.type !== "EmptyStatement"); + const hasDirectives = n.directives && n.directives.length > 0; + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + + if (!hasContent && !hasDirectives && !hasDanglingComments$1(n) && (parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration")) { + return "{}"; + } + + parts.push("{"); // Babel 6 + + if (hasDirectives) { + path.each(childPath => { + parts.push(indent$8(concat$c([hardline$6, print(childPath), semi]))); + + if (isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) { + parts.push(hardline$6); + } + }, "directives"); + } + + if (hasContent) { + parts.push(indent$8(concat$c([hardline$6, naked]))); + } + + parts.push(comments.printDanglingComments(path, options)); + parts.push(hardline$6, "}"); + return concat$c(parts); + } + + case "ReturnStatement": + return concat$c(["return", printReturnAndThrowArgument(path, options, print)]); + + case "NewExpression": + case "ImportExpression": + case "OptionalCallExpression": + case "CallExpression": + { + const isNew = n.type === "NewExpression"; + const isDynamicImport = n.type === "ImportExpression"; + const optional = printOptionalToken$2(path); + const args = isDynamicImport ? [n.source] : n.arguments; + + if ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style + // define calls, as a unit. + // e.g. `define(["some/lib", (lib) => {` + !isDynamicImport && !isNew && n.callee.type === "Identifier" && (n.callee.name === "require" || n.callee.name === "define") || // Template literals as single arguments + args.length === 1 && isTemplateOnItsOwnLine$1(args[0], options.originalText, options) || // Keep test declarations on a single line + // e.g. `it('long name', () => {` + !isNew && isTestCall$1(n, path.getParentNode())) { + return concat$c([isNew ? "new " : "", path.call(print, "callee"), optional, printFunctionTypeParameters$2(path, options, print), concat$c(["(", isDynamicImport ? path.call(print, "source") : join$6(", ", path.map(print, "arguments")), ")"])]); + } // Inline Flow annotation comments following Identifiers in Call nodes need to + // stay with the Identifier. For example: + // + // foo /*:: */(bar); + // + // Here, we ensure that such comments stay between the Identifier and the Callee. + + + const isIdentifierWithFlowAnnotation = n.callee && n.callee.type === "Identifier" && hasFlowAnnotationComment$1(n.callee.trailingComments); + + if (isIdentifierWithFlowAnnotation) { + n.callee.trailingComments[0].printed = true; + } // We detect calls on member lookups and possibly print them in a + // special chain format. See `printMemberChain` for more info. + + + if (!isDynamicImport && !isNew && isMemberish$2(n.callee) && !path.call(path => needsParens_1(path, options), "callee")) { + return memberChain(path, options, print); + } + + const contents = concat$c([isNew ? "new " : "", isDynamicImport ? "import" : path.call(print, "callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${n.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters$2(path, options, print), callArguments(path, options, print)]); // We group here when the callee is itself a call expression. + // See `isLongCurriedCallExpression` for more info. + + if (isDynamicImport || isCallOrOptionalCallExpression$2(n.callee)) { + return group$7(contents); + } + + return contents; + } + + case "ObjectTypeInternalSlot": + return concat$c([n.static ? "static " : "", "[[", path.call(print, "id"), "]]", printOptionalToken$2(path), n.method ? "" : ": ", path.call(print, "value")]); + + case "ObjectExpression": + case "ObjectPattern": + case "ObjectTypeAnnotation": + case "TSInterfaceBody": + case "TSTypeLiteral": + case "RecordExpression": + { + let propertiesField; + + if (n.type === "TSTypeLiteral") { + propertiesField = "members"; + } else if (n.type === "TSInterfaceBody") { + propertiesField = "body"; + } else { + propertiesField = "properties"; + } + + const isTypeAnnotation = n.type === "ObjectTypeAnnotation"; + const fields = []; + + if (isTypeAnnotation) { + fields.push("indexers", "callProperties", "internalSlots"); + } + + fields.push(propertiesField); + const firstProperty = fields.map(field => n[field][0]).sort((a, b) => options.locStart(a) - options.locStart(b))[0]; + const parent = path.getParentNode(0); + const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body"; + const shouldBreak = n.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || n.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && n.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || n.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$5(options.originalText, options.locStart(n), options.locStart(firstProperty)); + const separator = isFlowInterfaceLikeBody ? ";" : n.type === "TSInterfaceBody" || n.type === "TSTypeLiteral" ? ifBreak$4(semi, ";") : ","; + const leftBrace = n.type === "RecordExpression" ? "#{" : n.exact ? "{|" : "{"; + const rightBrace = n.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be + // interleaved in the source code. So we need to reorder them before + // printing them. + + const propsAndLoc = []; + fields.forEach(field => { + path.each(childPath => { + const node = childPath.getValue(); + propsAndLoc.push({ + node, + printed: print(childPath), + loc: options.locStart(node) + }); + }, field); + }); + let separatorParts = []; + const props = propsAndLoc.sort((a, b) => a.loc - b.loc).map(prop => { + const result = concat$c(separatorParts.concat(group$7(prop.printed))); + separatorParts = [separator, line$8]; + + if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasNodeIgnoreComment$2(prop.node)) { + separatorParts.shift(); + } + + if (isNextLineEmpty$4(options.originalText, prop.node, options.locEnd)) { + separatorParts.push(hardline$6); + } + + return result; + }); + + if (n.inexact) { + let printed; + + if (hasDanglingComments$1(n)) { + const hasLineComments = !n.comments.every(comments$1.isBlockComment); + const printedDanglingComments = comments.printDanglingComments(path, options, + /* sameIndent */ + true); + printed = concat$c([printedDanglingComments, hasLineComments || hasNewline$5(options.originalText, options.locEnd(n.comments[n.comments.length - 1])) ? hardline$6 : line$8, "..."]); + } else { + printed = "..."; + } + + props.push(concat$c(separatorParts.concat(printed))); + } + + const lastElem = getLast$5(n[propertiesField]); + const canHaveTrailingSeparator = !(n.inexact || lastElem && lastElem.type === "RestElement"); + let content; + + if (props.length === 0) { + if (!hasDanglingComments$1(n)) { + return concat$c([leftBrace, rightBrace, printTypeAnnotation(path, options, print)]); + } + + content = group$7(concat$c([leftBrace, comments.printDanglingComments(path, options), softline$6, rightBrace, printOptionalToken$2(path), printTypeAnnotation(path, options, print)])); + } else { + content = concat$c([leftBrace, indent$8(concat$c([options.bracketSpacing ? line$8 : softline$6, concat$c(props)])), ifBreak$4(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$3(options)) ? separator : ""), concat$c([options.bracketSpacing ? line$8 : softline$6, rightBrace]), printOptionalToken$2(path), printTypeAnnotation(path, options, print)]); + } // If we inline the object as first argument of the parent, we don't want + // to create another group so that the object breaks before the return + // type + + + if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugArguments(node) && (name === "params" || name === "parameters") && number === 0)) { + return content; + } + + return group$7(content, { + shouldBreak + }); + } + // Babel 6 + + case "ObjectProperty": // Non-standard AST node type. + + case "Property": + if (n.method || n.kind === "get" || n.kind === "set") { + return printMethod(path, options, print); + } + + if (n.shorthand) { + parts.push(path.call(print, "value")); + } else { + parts.push(printAssignment(n.key, printPropertyKey(path, options, print), ":", n.value, path.call(print, "value"), options)); + } + + return concat$c(parts); + // Babel 6 + + case "ClassMethod": + case "ClassPrivateMethod": + case "MethodDefinition": + case "TSAbstractMethodDefinition": + case "TSDeclareMethod": + if (n.decorators && n.decorators.length !== 0) { + parts.push(printDecorators(path, options, print)); + } + + if (n.accessibility) { + parts.push(n.accessibility + " "); + } + + if (n.static) { + parts.push("static "); + } + + if (n.type === "TSAbstractMethodDefinition" || n.abstract) { + parts.push("abstract "); + } + + parts.push(printMethod(path, options, print)); + return concat$c(parts); + + case "ObjectMethod": + return printMethod(path, options, print); + + case "Decorator": + return concat$c(["@", path.call(print, "expression"), path.call(print, "callee")]); + + case "ArrayExpression": + case "ArrayPattern": + case "TupleExpression": + { + const openBracket = n.type === "TupleExpression" ? "#[" : "["; + const closeBracket = "]"; + + if (n.elements.length === 0) { + if (!hasDanglingComments$1(n)) { + parts.push(openBracket, closeBracket); + } else { + parts.push(group$7(concat$c([openBracket, comments.printDanglingComments(path, options), softline$6, closeBracket]))); + } + } else { + const lastElem = getLast$5(n.elements); + const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which + // changes its length based on the number of commas. The algorithm + // is that if the last argument is null, we need to force insert + // a comma to ensure JavaScript recognizes it. + // [,].length === 1 + // [1,].length === 1 + // [1,,].length === 2 + // + // Note that getLast returns null if the array is empty, but + // we already check for an empty array just above so we are safe + + const needsForcedTrailingComma = canHaveTrailingComma && lastElem === null; + const shouldBreak = !options.__inJestEach && n.elements.length > 1 && n.elements.every((element, i, elements) => { + const elementType = element && element.type; + + if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") { + return false; + } + + const nextElement = elements[i + 1]; + + if (nextElement && elementType !== nextElement.type) { + return false; + } + + const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties"; + return element[itemsKey] && element[itemsKey].length > 1; + }); + parts.push(group$7(concat$c([openBracket, indent$8(concat$c([softline$6, printArrayItems(path, options, "elements", print)])), needsForcedTrailingComma ? "," : "", ifBreak$4(canHaveTrailingComma && !needsForcedTrailingComma && shouldPrintComma$3(options) ? "," : ""), comments.printDanglingComments(path, options, + /* sameIndent */ + true), softline$6, closeBracket]), { + shouldBreak + })); + } + + parts.push(printOptionalToken$2(path), printTypeAnnotation(path, options, print)); + return concat$c(parts); + } + + case "SequenceExpression": + { + const parent = path.getParentNode(0); + + if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") { + // For ExpressionStatements and for-loop heads, which are among + // the few places a SequenceExpression appears unparenthesized, we want + // to indent expressions after the first. + const parts = []; + path.each(p => { + if (p.getName() === 0) { + parts.push(print(p)); + } else { + parts.push(",", indent$8(concat$c([line$8, print(p)]))); + } + }, "expressions"); + return group$7(concat$c(parts)); + } + + return group$7(concat$c([join$6(concat$c([",", line$8]), path.map(print, "expressions"))])); + } + + case "ThisExpression": + return "this"; + + case "Super": + return "super"; + + case "NullLiteral": + // Babel 6 Literal split + return "null"; + + case "RegExpLiteral": + // Babel 6 Literal split + return printRegex(n); + + case "NumericLiteral": + // Babel 6 Literal split + return printNumber$1(n.extra.raw); + + case "DecimalLiteral": + return printNumber$1(n.value) + "m"; + + case "BigIntLiteral": + // babel: n.extra.raw, flow: n.bigint + return (n.bigint || n.extra.raw).toLowerCase(); + + case "BooleanLiteral": // Babel 6 Literal split + + case "StringLiteral": // Babel 6 Literal split + + case "Literal": + if (n.regex) { + return printRegex(n.regex); + } // typescript + + + if (n.bigint) { + return n.raw.toLowerCase(); + } + + if (typeof n.value === "number") { + return printNumber$1(n.raw); + } + + if (typeof n.value !== "string") { + return "" + n.value; + } + + return nodeStr(n, options); + + case "Directive": + return path.call(print, "value"); + // Babel 6 + + case "DirectiveLiteral": + return nodeStr(n, options); + + case "UnaryExpression": + parts.push(n.operator); + + if (/[a-z]$/.test(n.operator)) { + parts.push(" "); + } + + if (n.argument.comments && n.argument.comments.length > 0) { + parts.push(group$7(concat$c(["(", indent$8(concat$c([softline$6, path.call(print, "argument")])), softline$6, ")"]))); + } else { + parts.push(path.call(print, "argument")); + } + + return concat$c(parts); + + case "UpdateExpression": + parts.push(path.call(print, "argument"), n.operator); + + if (n.prefix) { + parts.reverse(); + } + + return concat$c(parts); + + case "ConditionalExpression": + return ternary(path, options, print, { + beforeParts: () => [path.call(print, "test")], + afterParts: breakClosingParen => [breakClosingParen ? softline$6 : ""], + shouldCheckJsx: true, + conditionalNodeType: "ConditionalExpression", + consequentNodePropertyName: "consequent", + alternateNodePropertyName: "alternate", + testNodePropertyNames: ["test"] + }); + + case "VariableDeclaration": + { + const printed = path.map(childPath => { + return print(childPath); + }, "declarations"); // We generally want to terminate all variable declarations with a + // semicolon, except when they in the () part of for loops. + + const parentNode = path.getParentNode(); + const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement"; + const hasValue = n.declarations.some(decl => decl.init); + let firstVariable; + + if (printed.length === 1 && !n.declarations[0].comments) { + firstVariable = printed[0]; + } else if (printed.length > 0) { + // Indent first var to comply with eslint one-var rule + firstVariable = indent$8(printed[0]); + } + + parts = [n.declare ? "declare " : "", n.kind, firstVariable ? concat$c([" ", firstVariable]) : "", indent$8(concat$c(printed.slice(1).map(p => concat$c([",", hasValue && !isParentForLoop ? hardline$6 : line$8, p]))))]; + + if (!(isParentForLoop && parentNode.body !== n)) { + parts.push(semi); + } + + return group$7(concat$c(parts)); + } + + case "TSTypeAliasDeclaration": + { + if (n.declare) { + parts.push("declare "); + } + + const printed = printAssignmentRight(n.id, n.typeAnnotation, n.typeAnnotation && path.call(print, "typeAnnotation"), options); + parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi); + return group$7(concat$c(parts)); + } + + case "VariableDeclarator": + return printAssignment(n.id, path.call(print, "id"), " =", n.init, n.init && path.call(print, "init"), options); + + case "WithStatement": + return group$7(concat$c(["with (", path.call(print, "object"), ")", adjustClause(n.body, path.call(print, "body"))])); + + case "IfStatement": + { + const con = adjustClause(n.consequent, path.call(print, "consequent")); + const opening = group$7(concat$c(["if (", group$7(concat$c([indent$8(concat$c([softline$6, path.call(print, "test")])), softline$6])), ")", con])); + parts.push(opening); + + if (n.alternate) { + const commentOnOwnLine = hasTrailingComment$3(n.consequent) && n.consequent.comments.some(comment => comment.trailing && !comments$1.isBlockComment(comment)) || needsHardlineAfterDanglingComment$1(n); + const elseOnSameLine = n.consequent.type === "BlockStatement" && !commentOnOwnLine; + parts.push(elseOnSameLine ? " " : hardline$6); + + if (hasDanglingComments$1(n)) { + parts.push(comments.printDanglingComments(path, options, true), commentOnOwnLine ? hardline$6 : " "); + } + + parts.push("else", group$7(adjustClause(n.alternate, path.call(print, "alternate"), n.alternate.type === "IfStatement"))); + } + + return concat$c(parts); + } + + case "ForStatement": + { + const body = adjustClause(n.body, path.call(print, "body")); // We want to keep dangling comments above the loop to stay consistent. + // Any comment positioned between the for statement and the parentheses + // is going to be printed before the statement. + + const dangling = comments.printDanglingComments(path, options, + /* sameLine */ + true); + const printedComments = dangling ? concat$c([dangling, softline$6]) : ""; + + if (!n.init && !n.test && !n.update) { + return concat$c([printedComments, group$7(concat$c(["for (;;)", body]))]); + } + + return concat$c([printedComments, group$7(concat$c(["for (", group$7(concat$c([indent$8(concat$c([softline$6, path.call(print, "init"), ";", line$8, path.call(print, "test"), ";", line$8, path.call(print, "update")])), softline$6])), ")", body]))]); + } + + case "WhileStatement": + return group$7(concat$c(["while (", group$7(concat$c([indent$8(concat$c([softline$6, path.call(print, "test")])), softline$6])), ")", adjustClause(n.body, path.call(print, "body"))])); + + case "ForInStatement": + // Note: esprima can't actually parse "for each (". + return group$7(concat$c([n.each ? "for each (" : "for (", path.call(print, "left"), " in ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))])); + + case "ForOfStatement": + return group$7(concat$c(["for", n.await ? " await" : "", " (", path.call(print, "left"), " of ", path.call(print, "right"), ")", adjustClause(n.body, path.call(print, "body"))])); + + case "DoWhileStatement": + { + const clause = adjustClause(n.body, path.call(print, "body")); + const doBody = group$7(concat$c(["do", clause])); + parts = [doBody]; + + if (n.body.type === "BlockStatement") { + parts.push(" "); + } else { + parts.push(hardline$6); + } + + parts.push("while ("); + parts.push(group$7(concat$c([indent$8(concat$c([softline$6, path.call(print, "test")])), softline$6])), ")", semi); + return concat$c(parts); + } + + case "DoExpression": + return concat$c(["do ", path.call(print, "body")]); + + case "BreakStatement": + parts.push("break"); + + if (n.label) { + parts.push(" ", path.call(print, "label")); + } + + parts.push(semi); + return concat$c(parts); + + case "ContinueStatement": + parts.push("continue"); + + if (n.label) { + parts.push(" ", path.call(print, "label")); + } + + parts.push(semi); + return concat$c(parts); + + case "LabeledStatement": + if (n.body.type === "EmptyStatement") { + return concat$c([path.call(print, "label"), ":;"]); + } + + return concat$c([path.call(print, "label"), ": ", path.call(print, "body")]); + + case "TryStatement": + return concat$c(["try ", path.call(print, "block"), n.handler ? concat$c([" ", path.call(print, "handler")]) : "", n.finalizer ? concat$c([" finally ", path.call(print, "finalizer")]) : ""]); + + case "CatchClause": + if (n.param) { + const hasComments = n.param.comments && n.param.comments.some(comment => !comments$1.isBlockComment(comment) || comment.leading && hasNewline$5(options.originalText, options.locEnd(comment)) || comment.trailing && hasNewline$5(options.originalText, options.locStart(comment), { + backwards: true + })); + const param = path.call(print, "param"); + return concat$c(["catch ", hasComments ? concat$c(["(", indent$8(concat$c([softline$6, param])), softline$6, ") "]) : concat$c(["(", param, ") "]), path.call(print, "body")]); + } + + return concat$c(["catch ", path.call(print, "body")]); + + case "ThrowStatement": + return concat$c(["throw", printReturnAndThrowArgument(path, options, print)]); + // Note: ignoring n.lexical because it has no printing consequences. + + case "SwitchStatement": + return concat$c([group$7(concat$c(["switch (", indent$8(concat$c([softline$6, path.call(print, "discriminant")])), softline$6, ")"])), " {", n.cases.length > 0 ? indent$8(concat$c([hardline$6, join$6(hardline$6, path.map(casePath => { + const caseNode = casePath.getValue(); + return concat$c([casePath.call(print), n.cases.indexOf(caseNode) !== n.cases.length - 1 && isNextLineEmpty$4(options.originalText, caseNode, options.locEnd) ? hardline$6 : ""]); + }, "cases"))])) : "", hardline$6, "}"]); + + case "SwitchCase": + { + if (n.test) { + parts.push("case ", path.call(print, "test"), ":"); + } else { + parts.push("default:"); + } + + const consequent = n.consequent.filter(node => node.type !== "EmptyStatement"); + + if (consequent.length > 0) { + const cons = path.call(consequentPath => { + return printStatementSequence(consequentPath, options, print); + }, "consequent"); + parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? concat$c([" ", cons]) : indent$8(concat$c([hardline$6, cons]))); + } + + return concat$c(parts); + } + // JSX extensions below. + + case "DebuggerStatement": + return concat$c(["debugger", semi]); + + case "JSXAttribute": + parts.push(path.call(print, "name")); + + if (n.value) { + let res; + + if (isStringLiteral$1(n.value)) { + const raw = rawText$1(n.value); // Unescape all quotes so we get an accurate preferred quote + + let final = raw.replace(/'/g, "'").replace(/"/g, '"'); + const quote = getPreferredQuote$1(final, options.jsxSingleQuote ? "'" : '"'); + const escape = quote === "'" ? "'" : """; + final = final.slice(1, -1).replace(new RegExp(quote, "g"), escape); + res = concat$c([quote, final, quote]); + } else { + res = path.call(print, "value"); + } + + parts.push("=", res); + } + + return concat$c(parts); + + case "JSXIdentifier": + return "" + n.name; + + case "JSXNamespacedName": + return join$6(":", [path.call(print, "namespace"), path.call(print, "name")]); + + case "JSXMemberExpression": + return join$6(".", [path.call(print, "object"), path.call(print, "property")]); + + case "TSQualifiedName": + return join$6(".", [path.call(print, "left"), path.call(print, "right")]); + + case "JSXSpreadAttribute": + case "JSXSpreadChild": + { + return concat$c(["{", path.call(p => { + const printed = concat$c(["...", print(p)]); + const n = p.getValue(); + + if (!n.comments || !n.comments.length || !willPrintOwnComments(p)) { + return printed; + } + + return concat$c([indent$8(concat$c([softline$6, comments.printComments(p, () => printed, options)])), softline$6]); + }, n.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]); + } + + case "JSXExpressionContainer": + { + const parent = path.getParentNode(0); + const hasComments = n.expression.comments && n.expression.comments.length > 0; + const shouldInline = n.expression.type === "JSXEmptyExpression" || !hasComments && (n.expression.type === "ArrayExpression" || n.expression.type === "ObjectExpression" || n.expression.type === "ArrowFunctionExpression" || n.expression.type === "CallExpression" || n.expression.type === "OptionalCallExpression" || n.expression.type === "FunctionExpression" || n.expression.type === "TemplateLiteral" || n.expression.type === "TaggedTemplateExpression" || n.expression.type === "DoExpression" || isJSXNode$3(parent) && (n.expression.type === "ConditionalExpression" || isBinaryish$1(n.expression))); + + if (shouldInline) { + return group$7(concat$c(["{", path.call(print, "expression"), lineSuffixBoundary$1, "}"])); + } + + return group$7(concat$c(["{", indent$8(concat$c([softline$6, path.call(print, "expression")])), softline$6, lineSuffixBoundary$1, "}"])); + } + + case "JSXFragment": + case "JSXElement": + { + const elem = comments.printComments(path, () => printJSXElement(path, options, print), options); + return maybeWrapJSXElementInParens(path, elem, options); + } + + case "JSXOpeningElement": + { + const n = path.getValue(); + const nameHasComments = n.name && n.name.comments && n.name.comments.length > 0 || n.typeParameters && n.typeParameters.comments && n.typeParameters.comments.length > 0; // Don't break self-closing elements with no attributes and no comments + + if (n.selfClosing && !n.attributes.length && !nameHasComments) { + return concat$c(["<", path.call(print, "name"), path.call(print, "typeParameters"), " />"]); + } // don't break up opening elements with a single long text attribute + + + if (n.attributes && n.attributes.length === 1 && n.attributes[0].value && isStringLiteral$1(n.attributes[0].value) && !n.attributes[0].value.value.includes("\n") && // We should break for the following cases: + //
+ //
+ !nameHasComments && (!n.attributes[0].comments || !n.attributes[0].comments.length)) { + return group$7(concat$c(["<", path.call(print, "name"), path.call(print, "typeParameters"), " ", concat$c(path.map(print, "attributes")), n.selfClosing ? " />" : ">"])); + } + + const lastAttrHasTrailingComments = n.attributes.length && hasTrailingComment$3(getLast$5(n.attributes)); + const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be + // kept unbroken regardless of `jsxBracketSameLine` + !n.attributes.length && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases: + //
+ //
+ !nameHasComments || n.attributes.length) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a + // string literal with newlines + + const shouldBreak = n.attributes && n.attributes.some(attr => attr.value && isStringLiteral$1(attr.value) && attr.value.value.includes("\n")); + return group$7(concat$c(["<", path.call(print, "name"), path.call(print, "typeParameters"), concat$c([indent$8(concat$c(path.map(attr => concat$c([line$8, print(attr)]), "attributes"))), n.selfClosing ? line$8 : bracketSameLine ? ">" : softline$6]), n.selfClosing ? "/>" : bracketSameLine ? "" : ">"]), { + shouldBreak + }); + } + + case "JSXClosingElement": + return concat$c([""]); + + case "JSXOpeningFragment": + case "JSXClosingFragment": + { + const hasComment = n.comments && n.comments.length; + const hasOwnLineComment = hasComment && !n.comments.every(comments$1.isBlockComment); + const isOpeningFragment = n.type === "JSXOpeningFragment"; + return concat$c([isOpeningFragment ? "<" : ""]); + } + + case "JSXText": + /* istanbul ignore next */ + throw new Error("JSXTest should be handled by JSXElement"); + + case "JSXEmptyExpression": + { + const requiresHardline = n.comments && !n.comments.every(comments$1.isBlockComment); + return concat$c([comments.printDanglingComments(path, options, + /* sameIndent */ + !requiresHardline), requiresHardline ? hardline$6 : ""]); + } + + case "ClassBody": + if (!n.comments && n.body.length === 0) { + return "{}"; + } + + return concat$c(["{", n.body.length > 0 ? indent$8(concat$c([hardline$6, path.call(bodyPath => { + return printStatementSequence(bodyPath, options, print); + }, "body")])) : comments.printDanglingComments(path, options), hardline$6, "}"]); + + case "ClassProperty": + case "TSAbstractClassProperty": + case "ClassPrivateProperty": + { + if (n.decorators && n.decorators.length !== 0) { + parts.push(printDecorators(path, options, print)); + } + + if (n.accessibility) { + parts.push(n.accessibility + " "); + } + + if (n.declare) { + parts.push("declare "); + } + + if (n.static) { + parts.push("static "); + } + + if (n.type === "TSAbstractClassProperty" || n.abstract) { + parts.push("abstract "); + } + + if (n.readonly) { + parts.push("readonly "); + } + + const variance = getFlowVariance$1(n); + + if (variance) { + parts.push(variance); + } + + parts.push(printPropertyKey(path, options, print), printOptionalToken$2(path), printTypeAnnotation(path, options, print)); + + if (n.value) { + parts.push(" =", printAssignmentRight(n.key, n.value, path.call(print, "value"), options)); + } + + parts.push(semi); + return group$7(concat$c(parts)); + } + + case "ClassDeclaration": + case "ClassExpression": + if (n.declare) { + parts.push("declare "); + } + + parts.push(concat$c(printClass(path, options, print))); + return concat$c(parts); + + case "TSInterfaceHeritage": + case "TSExpressionWithTypeArguments": + // Babel AST + parts.push(path.call(print, "expression")); + + if (n.typeParameters) { + parts.push(path.call(print, "typeParameters")); + } + + return concat$c(parts); + + case "TemplateElement": + return join$6(literalline$3, n.value.raw.split(/\r?\n/g)); + + case "TemplateLiteral": + { + const parentNode = path.getParentNode(); + + if (isJestEachTemplateLiteral$1(n, parentNode)) { + const printed = printJestEachTemplateLiteral(path, options, print); + + if (printed) { + return printed; + } + } + + let expressions = path.map(print, "expressions"); + const isSimple = isSimpleTemplateLiteral$1(n); + + if (isSimple) { + expressions = expressions.map(doc => printDocToString$2(doc, Object.assign({}, options, { + printWidth: Infinity + })).formatted); + } + + parts.push(lineSuffixBoundary$1, "`"); + path.each(childPath => { + const i = childPath.getName(); + parts.push(print(childPath)); + + if (i < expressions.length) { + // For a template literal of the following form: + // `someQuery { + // ${call({ + // a, + // b, + // })} + // }` + // the expression is on its own line (there is a \n in the previous + // quasi literal), therefore we want to indent the JavaScript + // expression inside at the beginning of ${ instead of the beginning + // of the `. + const { + tabWidth + } = options; + const quasi = childPath.getValue(); + const indentSize = getIndentSize$2(quasi.value.raw, tabWidth); + let printed = expressions[i]; + + if (!isSimple) { + // Breaks at the template element boundaries (${ and }) are preferred to breaking + // in the middle of a MemberExpression + if (n.expressions[i].comments && n.expressions[i].comments.length || n.expressions[i].type === "MemberExpression" || n.expressions[i].type === "OptionalMemberExpression" || n.expressions[i].type === "ConditionalExpression" || n.expressions[i].type === "SequenceExpression" || n.expressions[i].type === "TSAsExpression" || isBinaryish$1(n.expressions[i])) { + printed = concat$c([indent$8(concat$c([softline$6, printed])), softline$6]); + } + } + + const aligned = indentSize === 0 && quasi.value.raw.endsWith("\n") ? align$2(-Infinity, printed) : addAlignmentToDoc$2(printed, indentSize, tabWidth); + parts.push(group$7(concat$c(["${", aligned, lineSuffixBoundary$1, "}"]))); + } + }, "quasis"); + parts.push("`"); + return concat$c(parts); + } + + case "TaggedTemplateExpression": + return concat$c([path.call(print, "tag"), path.call(print, "typeParameters"), path.call(print, "quasi")]); + // These types are unprintable because they serve as abstract + // supertypes for other (printable) types. + + case "Node": + case "Printable": + case "SourceLocation": + case "Position": + case "Statement": + case "Function": + case "Pattern": + case "Expression": + case "Declaration": + case "Specifier": + case "NamedSpecifier": + case "Comment": + case "MemberTypeAnnotation": // Flow + + case "Type": + /* istanbul ignore next */ + throw new Error("unprintable type: " + JSON.stringify(n.type)); + // Type Annotations for Facebook Flow, typically stripped out or + // transformed away before printing. + + case "TypeAnnotation": + case "TSTypeAnnotation": + if (n.typeAnnotation) { + return path.call(print, "typeAnnotation"); + } + /* istanbul ignore next */ + + + return ""; + + case "TSNamedTupleMember": + return concat$c([path.call(print, "label"), n.optional ? "?" : "", ": ", path.call(print, "elementType")]); + + case "TSTupleType": + case "TupleTypeAnnotation": + { + const typesField = n.type === "TSTupleType" ? "elementTypes" : "types"; + const hasRest = n[typesField].length > 0 && getLast$5(n[typesField]).type === "TSRestType"; + return group$7(concat$c(["[", indent$8(concat$c([softline$6, printArrayItems(path, options, typesField, print)])), ifBreak$4(shouldPrintComma$3(options, "all") && !hasRest ? "," : ""), comments.printDanglingComments(path, options, + /* sameIndent */ + true), softline$6, "]"])); + } + + case "ExistsTypeAnnotation": + return "*"; + + case "EmptyTypeAnnotation": + return "empty"; + + case "AnyTypeAnnotation": + return "any"; + + case "MixedTypeAnnotation": + return "mixed"; + + case "ArrayTypeAnnotation": + return concat$c([path.call(print, "elementType"), "[]"]); + + case "BooleanTypeAnnotation": + return "boolean"; + + case "BooleanLiteralTypeAnnotation": + return "" + n.value; + + case "DeclareClass": + return printFlowDeclaration(path, printClass(path, options, print)); + + case "TSDeclareFunction": + // For TypeScript the TSDeclareFunction node shares the AST + // structure with FunctionDeclaration + return concat$c([n.declare ? "declare " : "", printFunctionDeclaration(path, print, options), semi]); + + case "DeclareFunction": + return printFlowDeclaration(path, ["function ", path.call(print, "id"), n.predicate ? " " : "", path.call(print, "predicate"), semi]); + + case "DeclareModule": + return printFlowDeclaration(path, ["module ", path.call(print, "id"), " ", path.call(print, "body")]); + + case "DeclareModuleExports": + return printFlowDeclaration(path, ["module.exports", ": ", path.call(print, "typeAnnotation"), semi]); + + case "DeclareVariable": + return printFlowDeclaration(path, ["var ", path.call(print, "id"), semi]); + + case "DeclareExportAllDeclaration": + return concat$c(["declare export *", printModuleSource$1(path, options, print)]); + + case "DeclareOpaqueType": + case "OpaqueType": + { + parts.push("opaque type ", path.call(print, "id"), path.call(print, "typeParameters")); + + if (n.supertype) { + parts.push(": ", path.call(print, "supertype")); + } + + if (n.impltype) { + parts.push(" = ", path.call(print, "impltype")); + } + + parts.push(semi); + + if (n.type === "DeclareOpaqueType") { + return printFlowDeclaration(path, parts); + } + + return concat$c(parts); + } + + case "EnumDeclaration": + return concat$c(["enum ", path.call(print, "id"), " ", path.call(print, "body")]); + + case "EnumBooleanBody": + case "EnumNumberBody": + case "EnumStringBody": + case "EnumSymbolBody": + { + if (n.type === "EnumSymbolBody" || n.explicitType) { + let type = null; + + switch (n.type) { + case "EnumBooleanBody": + type = "boolean"; + break; + + case "EnumNumberBody": + type = "number"; + break; + + case "EnumStringBody": + type = "string"; + break; + + case "EnumSymbolBody": + type = "symbol"; + break; + } + + parts.push("of ", type, " "); + } + + if (n.members.length === 0) { + parts.push(group$7(concat$c(["{", comments.printDanglingComments(path, options), softline$6, "}"]))); + } else { + parts.push(group$7(concat$c(["{", indent$8(concat$c([hardline$6, printArrayItems(path, options, "members", print), shouldPrintComma$3(options) ? "," : ""])), comments.printDanglingComments(path, options, + /* sameIndent */ + true), hardline$6, "}"]))); + } + + return concat$c(parts); + } + + case "EnumBooleanMember": + case "EnumNumberMember": + case "EnumStringMember": + return concat$c([path.call(print, "id"), " = ", typeof n.init === "object" ? path.call(print, "init") : String(n.init)]); + + case "EnumDefaultedMember": + return path.call(print, "id"); + + case "FunctionTypeAnnotation": + case "TSFunctionType": + { + // FunctionTypeAnnotation is ambiguous: + // declare function foo(a: B): void; OR + // var A: (a: B) => void; + const parent = path.getParentNode(0); + const parentParent = path.getParentNode(1); + const parentParentParent = path.getParentNode(2); + let isArrowFunctionTypeAnnotation = n.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !getFlowVariance$1(parent) && !parent.optional && options.locStart(parent) === options.locStart(n) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction"); + let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of FastPath::needsColon because we are + // printing ":" as part of the expression and it would put parenthesis + // around :( + + const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression"; + + if (isObjectTypePropertyAFunction$1(parent, options)) { + isArrowFunctionTypeAnnotation = true; + needsColon = true; + } + + if (needsParens) { + parts.push("("); + } + + parts.push(printFunctionParams(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true)); // The returnType is not wrapped in a TypeAnnotation, so the colon + // needs to be added separately. + + if (n.returnType || n.predicate || n.typeAnnotation) { + parts.push(isArrowFunctionTypeAnnotation ? " => " : ": ", path.call(print, "returnType"), path.call(print, "predicate"), path.call(print, "typeAnnotation")); + } + + if (needsParens) { + parts.push(")"); + } + + return group$7(concat$c(parts)); + } + + case "TSRestType": + return concat$c(["...", path.call(print, "typeAnnotation")]); + + case "TSOptionalType": + return concat$c([path.call(print, "typeAnnotation"), "?"]); + + case "FunctionTypeParam": + return concat$c([path.call(print, "name"), printOptionalToken$2(path), n.name ? ": " : "", path.call(print, "typeAnnotation")]); + + case "GenericTypeAnnotation": + return concat$c([path.call(print, "id"), path.call(print, "typeParameters")]); + + case "DeclareInterface": + case "InterfaceDeclaration": + case "InterfaceTypeAnnotation": + case "TSInterfaceDeclaration": + { + if (n.type === "DeclareInterface" || n.declare) { + parts.push("declare "); + } + + if (n.type === "TSInterfaceDeclaration") { + parts.push(n.abstract ? "abstract " : "", printTypeScriptModifiers(path, options, print)); + } + + parts.push("interface"); + const partsGroup = []; + const extendsParts = []; + + if (n.type !== "InterfaceTypeAnnotation") { + partsGroup.push(" ", path.call(print, "id"), path.call(print, "typeParameters")); + } + + const shouldIndentOnlyHeritageClauses = n.typeParameters && !hasTrailingLineComment$1(n.typeParameters); + + if (n.extends && n.extends.length !== 0) { + extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$4(" ", line$8, { + groupId: getTypeParametersGroupId(n.typeParameters) + }) : line$8, "extends ", (n.extends.length === 1 ? identity$2 : indent$8)(join$6(concat$c([",", line$8]), path.map(print, "extends")))); + } + + if (n.id && hasTrailingComment$3(n.id) || n.extends && n.extends.length !== 0) { + const printedExtends = concat$c(extendsParts); + + if (shouldIndentOnlyHeritageClauses) { + parts.push(group$7(concat$c(partsGroup.concat(ifBreak$4(indent$8(printedExtends), printedExtends))))); + } else { + parts.push(group$7(indent$8(concat$c(partsGroup.concat(printedExtends))))); + } + } else { + parts.push(...partsGroup, ...extendsParts); + } + + parts.push(" ", path.call(print, "body")); + return group$7(concat$c(parts)); + } + + case "ClassImplements": + case "InterfaceExtends": + return concat$c([path.call(print, "id"), path.call(print, "typeParameters")]); + + case "TSClassImplements": + return concat$c([path.call(print, "expression"), path.call(print, "typeParameters")]); + + case "TSIntersectionType": + case "IntersectionTypeAnnotation": + { + const types = path.map(print, "types"); + const result = []; + let wasIndented = false; + + for (let i = 0; i < types.length; ++i) { + if (i === 0) { + result.push(types[i]); + } else if (isObjectType$1(n.types[i - 1]) && isObjectType$1(n.types[i])) { + // If both are objects, don't indent + result.push(concat$c([" & ", wasIndented ? indent$8(types[i]) : types[i]])); + } else if (!isObjectType$1(n.types[i - 1]) && !isObjectType$1(n.types[i])) { + // If no object is involved, go to the next line if it breaks + result.push(indent$8(concat$c([" &", line$8, types[i]]))); + } else { + // If you go from object to non-object or vis-versa, then inline it + if (i > 1) { + wasIndented = true; + } + + result.push(" & ", i > 1 ? indent$8(types[i]) : types[i]); + } + } + + return group$7(concat$c(result)); + } + + case "TSUnionType": + case "UnionTypeAnnotation": + { + // single-line variation + // A | B | C + // multi-line variation + // | A + // | B + // | C + const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation + + const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, n, options)); // { + // a: string + // } | null | void + // should be inlined and not be printed in the multi-line variant + + const shouldHug = shouldHugType(n); // We want to align the children but without its comment, so it looks like + // | child1 + // // comment + // | child2 + + const printed = path.map(typePath => { + let printedType = typePath.call(print); + + if (!shouldHug) { + printedType = align$2(2, printedType); + } + + return comments.printComments(typePath, () => printedType, options); + }, "types"); + + if (shouldHug) { + return join$6(" | ", printed); + } + + const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, n, options); + const code = concat$c([ifBreak$4(concat$c([shouldAddStartLine ? line$8 : "", "| "])), join$6(concat$c([line$8, "| "]), printed)]); + + if (needsParens_1(path, options)) { + return group$7(concat$c([indent$8(code), softline$6])); + } + + if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) { + return group$7(concat$c([indent$8(concat$c([ifBreak$4(concat$c(["(", softline$6])), code])), softline$6, ifBreak$4(")")])); + } + + return group$7(shouldIndent ? indent$8(code) : code); + } + + case "NullableTypeAnnotation": + return concat$c(["?", path.call(print, "typeAnnotation")]); + + case "TSNullKeyword": + case "NullLiteralTypeAnnotation": + return "null"; + + case "ThisTypeAnnotation": + return "this"; + + case "NumberTypeAnnotation": + return "number"; + + case "SymbolTypeAnnotation": + return "symbol"; + + case "ObjectTypeCallProperty": + if (n.static) { + parts.push("static "); + } + + parts.push(path.call(print, "value")); + return concat$c(parts); + + case "ObjectTypeIndexer": + { + const variance = getFlowVariance$1(n); + return concat$c([variance || "", "[", path.call(print, "id"), n.id ? ": " : "", path.call(print, "key"), "]: ", path.call(print, "value")]); + } + + case "ObjectTypeProperty": + { + const variance = getFlowVariance$1(n); + let modifier = ""; + + if (n.proto) { + modifier = "proto "; + } else if (n.static) { + modifier = "static "; + } + + return concat$c([modifier, isGetterOrSetter$1(n) ? n.kind + " " : "", variance || "", printPropertyKey(path, options, print), printOptionalToken$2(path), isFunctionNotation$1(n, options) ? "" : ": ", path.call(print, "value")]); + } + + case "QualifiedTypeIdentifier": + return concat$c([path.call(print, "qualification"), ".", path.call(print, "id")]); + + case "StringLiteralTypeAnnotation": + return nodeStr(n, options); + + case "NumberLiteralTypeAnnotation": + assert__default['default'].strictEqual(typeof n.value, "number"); + + if (n.extra != null) { + return printNumber$1(n.extra.raw); + } + + return printNumber$1(n.raw); + + case "StringTypeAnnotation": + return "string"; + + case "DeclareTypeAlias": + case "TypeAlias": + { + if (n.type === "DeclareTypeAlias" || n.declare) { + parts.push("declare "); + } + + const printed = printAssignmentRight(n.id, n.right, path.call(print, "right"), options); + parts.push("type ", path.call(print, "id"), path.call(print, "typeParameters"), " =", printed, semi); + return group$7(concat$c(parts)); + } + + case "TypeCastExpression": + { + return concat$c(["(", path.call(print, "expression"), printTypeAnnotation(path, options, print), ")"]); + } + + case "TypeParameterDeclaration": + case "TypeParameterInstantiation": + { + const value = path.getValue(); + const commentStart = options.originalText.slice(0, options.locStart(value)).lastIndexOf("/*"); // As noted in the TypeCastExpression comments above, we're able to use a normal whitespace regex here + // because we know for sure that this is a type definition. + + const commentSyntax = commentStart >= 0 && options.originalText.slice(commentStart).match(/^\/\*\s*::/); + + if (commentSyntax) { + return concat$c(["/*:: ", printTypeParameters(path, options, print, "params"), " */"]); + } + + return printTypeParameters(path, options, print, "params"); + } + + case "TSTypeParameterDeclaration": + case "TSTypeParameterInstantiation": + return printTypeParameters(path, options, print, "params"); + + case "TSTypeParameter": + case "TypeParameter": + { + const parent = path.getParentNode(); + + if (parent.type === "TSMappedType") { + parts.push("[", path.call(print, "name")); + + if (n.constraint) { + parts.push(" in ", path.call(print, "constraint")); + } + + parts.push("]"); + return concat$c(parts); + } + + const variance = getFlowVariance$1(n); + + if (variance) { + parts.push(variance); + } + + parts.push(path.call(print, "name")); + + if (n.bound) { + parts.push(": "); + parts.push(path.call(print, "bound")); + } + + if (n.constraint) { + parts.push(" extends ", path.call(print, "constraint")); + } + + if (n.default) { + parts.push(" = ", path.call(print, "default")); + } // Keep comma if the file extension is .tsx and + // has one type parameter that isn't extend with any types. + // Because, otherwise formatted result will be invalid as tsx. + + + const grandParent = path.getNode(2); + + if (parent.params && parent.params.length === 1 && isTSXFile$1(options) && !n.constraint && grandParent.type === "ArrowFunctionExpression") { + parts.push(","); + } + + return concat$c(parts); + } + + case "TypeofTypeAnnotation": + return concat$c(["typeof ", path.call(print, "argument")]); + + case "VoidTypeAnnotation": + return "void"; + + case "InferredPredicate": + return "%checks"; + // Unhandled types below. If encountered, nodes of these types should + // be either left alone or desugared into AST types that are fully + // supported by the pretty-printer. + + case "DeclaredPredicate": + return concat$c(["%checks(", path.call(print, "value"), ")"]); + + case "TSAbstractKeyword": + return "abstract"; + + case "TSAnyKeyword": + return "any"; + + case "TSAsyncKeyword": + return "async"; + + case "TSBooleanKeyword": + return "boolean"; + + case "TSBigIntKeyword": + return "bigint"; + + case "TSConstKeyword": + return "const"; + + case "TSDeclareKeyword": + return "declare"; + + case "TSExportKeyword": + return "export"; + + case "TSNeverKeyword": + return "never"; + + case "TSNumberKeyword": + return "number"; + + case "TSObjectKeyword": + return "object"; + + case "TSProtectedKeyword": + return "protected"; + + case "TSPrivateKeyword": + return "private"; + + case "TSPublicKeyword": + return "public"; + + case "TSReadonlyKeyword": + return "readonly"; + + case "TSSymbolKeyword": + return "symbol"; + + case "TSStaticKeyword": + return "static"; + + case "TSStringKeyword": + return "string"; + + case "TSUndefinedKeyword": + return "undefined"; + + case "TSUnknownKeyword": + return "unknown"; + + case "TSVoidKeyword": + return "void"; + + case "TSAsExpression": + return concat$c([path.call(print, "expression"), " as ", path.call(print, "typeAnnotation")]); + + case "TSArrayType": + return concat$c([path.call(print, "elementType"), "[]"]); + + case "TSPropertySignature": + { + if (n.export) { + parts.push("export "); + } + + if (n.accessibility) { + parts.push(n.accessibility + " "); + } + + if (n.static) { + parts.push("static "); + } + + if (n.readonly) { + parts.push("readonly "); + } + + parts.push(printPropertyKey(path, options, print), printOptionalToken$2(path)); + + if (n.typeAnnotation) { + parts.push(": "); + parts.push(path.call(print, "typeAnnotation")); + } // This isn't valid semantically, but it's in the AST so we can print it. + + + if (n.initializer) { + parts.push(" = ", path.call(print, "initializer")); + } + + return concat$c(parts); + } + + case "TSParameterProperty": + if (n.accessibility) { + parts.push(n.accessibility + " "); + } + + if (n.export) { + parts.push("export "); + } + + if (n.static) { + parts.push("static "); + } + + if (n.readonly) { + parts.push("readonly "); + } + + parts.push(path.call(print, "parameter")); + return concat$c(parts); + + case "TSTypeReference": + return concat$c([path.call(print, "typeName"), printTypeParameters(path, options, print, "typeParameters")]); + + case "TSTypeQuery": + return concat$c(["typeof ", path.call(print, "exprName")]); + + case "TSIndexSignature": + { + const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're + // using them, it makes sense to have a trailing comma. But if you + // aren't, this is more like a computed property name than an array. + // So we leave off the trailing comma when there's just one parameter. + + const trailingComma = n.parameters.length > 1 ? ifBreak$4(shouldPrintComma$3(options) ? "," : "") : ""; + const parametersGroup = group$7(concat$c([indent$8(concat$c([softline$6, join$6(concat$c([", ", softline$6]), path.map(print, "parameters"))])), trailingComma, softline$6])); + return concat$c([n.export ? "export " : "", n.accessibility ? concat$c([n.accessibility, " "]) : "", n.static ? "static " : "", n.readonly ? "readonly " : "", "[", n.parameters ? parametersGroup : "", n.typeAnnotation ? "]: " : "]", n.typeAnnotation ? path.call(print, "typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]); + } + + case "TSTypePredicate": + return concat$c([n.asserts ? "asserts " : "", path.call(print, "parameterName"), n.typeAnnotation ? concat$c([" is ", path.call(print, "typeAnnotation")]) : ""]); + + case "TSNonNullExpression": + return concat$c([path.call(print, "expression"), "!"]); + + case "TSThisType": + return "this"; + + case "TSImportType": + return concat$c([!n.isTypeOf ? "" : "typeof ", "import(", path.call(print, n.parameter ? "parameter" : "argument"), ")", !n.qualifier ? "" : concat$c([".", path.call(print, "qualifier")]), printTypeParameters(path, options, print, "typeParameters")]); + + case "TSLiteralType": + return path.call(print, "literal"); + + case "TSIndexedAccessType": + return concat$c([path.call(print, "objectType"), "[", path.call(print, "indexType"), "]"]); + + case "TSConstructSignatureDeclaration": + case "TSCallSignatureDeclaration": + case "TSConstructorType": + { + if (n.type !== "TSCallSignatureDeclaration") { + parts.push("new "); + } + + parts.push(group$7(printFunctionParams(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true))); + + if (n.returnType || n.typeAnnotation) { + const isType = n.type === "TSConstructorType"; + parts.push(isType ? " => " : ": ", path.call(print, "returnType"), path.call(print, "typeAnnotation")); + } + + return concat$c(parts); + } + + case "TSTypeOperator": + return concat$c([n.operator, " ", path.call(print, "typeAnnotation")]); + + case "TSMappedType": + { + const shouldBreak = hasNewlineInRange$5(options.originalText, options.locStart(n), options.locEnd(n)); + return group$7(concat$c(["{", indent$8(concat$c([options.bracketSpacing ? line$8 : softline$6, n.readonly ? concat$c([getTypeScriptMappedTypeModifier$1(n.readonly, "readonly"), " "]) : "", printTypeScriptModifiers(path, options, print), path.call(print, "typeParameter"), n.optional ? getTypeScriptMappedTypeModifier$1(n.optional, "?") : "", n.typeAnnotation ? ": " : "", path.call(print, "typeAnnotation"), ifBreak$4(semi, "")])), comments.printDanglingComments(path, options, + /* sameIndent */ + true), options.bracketSpacing ? line$8 : softline$6, "}"]), { + shouldBreak + }); + } + + case "TSMethodSignature": + parts.push(n.accessibility ? concat$c([n.accessibility, " "]) : "", n.export ? "export " : "", n.static ? "static " : "", n.readonly ? "readonly " : "", n.computed ? "[" : "", path.call(print, "key"), n.computed ? "]" : "", printOptionalToken$2(path), printFunctionParams(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true)); + + if (n.returnType || n.typeAnnotation) { + parts.push(": ", path.call(print, "returnType"), path.call(print, "typeAnnotation")); + } + + return group$7(concat$c(parts)); + + case "TSNamespaceExportDeclaration": + parts.push("export as namespace ", path.call(print, "id")); + + if (options.semi) { + parts.push(";"); + } + + return group$7(concat$c(parts)); + + case "TSEnumDeclaration": + if (n.declare) { + parts.push("declare "); + } + + if (n.modifiers) { + parts.push(printTypeScriptModifiers(path, options, print)); + } + + if (n.const) { + parts.push("const "); + } + + parts.push("enum ", path.call(print, "id"), " "); + + if (n.members.length === 0) { + parts.push(group$7(concat$c(["{", comments.printDanglingComments(path, options), softline$6, "}"]))); + } else { + parts.push(group$7(concat$c(["{", indent$8(concat$c([hardline$6, printArrayItems(path, options, "members", print), shouldPrintComma$3(options, "es5") ? "," : ""])), comments.printDanglingComments(path, options, + /* sameIndent */ + true), hardline$6, "}"]))); + } + + return concat$c(parts); + + case "TSEnumMember": + parts.push(path.call(print, "id")); + + if (n.initializer) { + parts.push(" = ", path.call(print, "initializer")); + } + + return concat$c(parts); + + case "TSImportEqualsDeclaration": + if (n.isExport) { + parts.push("export "); + } + + parts.push("import ", path.call(print, "id"), " = ", path.call(print, "moduleReference")); + + if (options.semi) { + parts.push(";"); + } + + return group$7(concat$c(parts)); + + case "TSExternalModuleReference": + return concat$c(["require(", path.call(print, "expression"), ")"]); + + case "TSModuleDeclaration": + { + const parent = path.getParentNode(); + const isExternalModule = isLiteral$1(n.id); + const parentIsDeclaration = parent.type === "TSModuleDeclaration"; + const bodyIsDeclaration = n.body && n.body.type === "TSModuleDeclaration"; + + if (parentIsDeclaration) { + parts.push("."); + } else { + if (n.declare) { + parts.push("declare "); + } + + parts.push(printTypeScriptModifiers(path, options, print)); + const textBetweenNodeAndItsId = options.originalText.slice(options.locStart(n), options.locStart(n.id)); // Global declaration looks like this: + // (declare)? global { ... } + + const isGlobalDeclaration = n.id.type === "Identifier" && n.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId); + + if (!isGlobalDeclaration) { + parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace "); + } + } + + parts.push(path.call(print, "id")); + + if (bodyIsDeclaration) { + parts.push(path.call(print, "body")); + } else if (n.body) { + parts.push(" ", group$7(path.call(print, "body"))); + } else { + parts.push(semi); + } + + return concat$c(parts); + } + + case "PrivateName": + return concat$c(["#", path.call(print, "id")]); + // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields. + + case "TSPrivateIdentifier": + return n.escapedText; + + case "TSConditionalType": + return ternary(path, options, print, { + beforeParts: () => [path.call(print, "checkType"), " ", "extends", " ", path.call(print, "extendsType")], + afterParts: () => [], + shouldCheckJsx: false, + conditionalNodeType: "TSConditionalType", + consequentNodePropertyName: "trueType", + alternateNodePropertyName: "falseType", + testNodePropertyNames: ["checkType", "extendsType"] + }); + + case "TSInferType": + return concat$c(["infer", " ", path.call(print, "typeParameter")]); + + case "InterpreterDirective": + parts.push("#!", n.value, hardline$6); + + if (isNextLineEmpty$4(options.originalText, n, options.locEnd)) { + parts.push(hardline$6); + } + + return concat$c(parts); + + case "NGRoot": + return concat$c([].concat(path.call(print, "node"), !n.node.comments || n.node.comments.length === 0 ? [] : concat$c([" //", n.node.comments[0].value.trimEnd()]))); + + case "NGChainedExpression": + return group$7(join$6(concat$c([";", line$8]), path.map(childPath => hasNgSideEffect$1(childPath) ? print(childPath) : concat$c(["(", print(childPath), ")"]), "expressions"))); + + case "NGEmptyExpression": + return ""; + + case "NGQuotedExpression": + return concat$c([n.prefix, ": ", n.value.trim()]); + + case "NGMicrosyntax": + return concat$c(path.map((childPath, index) => concat$c([index === 0 ? "" : isNgForOf$1(childPath.getValue(), index, n) ? " " : concat$c([";", line$8]), print(childPath)]), "body")); + + case "NGMicrosyntaxKey": + return /^[$_a-z][\w$]*(-[$_a-z][\w$])*$/i.test(n.name) ? n.name : JSON.stringify(n.name); + + case "NGMicrosyntaxExpression": + return concat$c([path.call(print, "expression"), n.alias === null ? "" : concat$c([" as ", path.call(print, "alias")])]); + + case "NGMicrosyntaxKeyedExpression": + { + const index = path.getName(); + const parentNode = path.getParentNode(); + const shouldNotPrintColon = isNgForOf$1(n, index, parentNode) || (index === 1 && (n.key.name === "then" || n.key.name === "else") || index === 2 && n.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression"; + return concat$c([path.call(print, "key"), shouldNotPrintColon ? " " : ": ", path.call(print, "expression")]); + } + + case "NGMicrosyntaxLet": + return concat$c(["let ", path.call(print, "key"), n.value === null ? "" : concat$c([" = ", path.call(print, "value")])]); + + case "NGMicrosyntaxAs": + return concat$c([path.call(print, "key"), " as ", path.call(print, "alias")]); + + case "PipelineBareFunction": + return path.call(print, "callee"); + + case "PipelineTopicExpression": + return path.call(print, "expression"); + + case "PipelinePrimaryTopicReference": + { + parts.push("#"); + return concat$c(parts); + } + + case "ArgumentPlaceholder": + return "?"; + // These are not valid TypeScript. Printing them just for the sake of error recovery. + + case "TSJSDocAllType": + return "*"; + + case "TSJSDocUnknownType": + return "?"; + + case "TSJSDocNullableType": + return concat$c(["?", path.call(print, "typeAnnotation")]); + + case "TSJSDocNonNullableType": + return concat$c(["!", path.call(print, "typeAnnotation")]); + + case "TSJSDocFunctionType": + return concat$c(["function(", // The parameters could be here, but typescript-estree doesn't convert them anyway (throws an error). + "): ", path.call(print, "typeAnnotation")]); + + default: + /* istanbul ignore next */ + throw new Error("unknown type: " + JSON.stringify(n.type)); + } +} + +function printStatementSequence(path, options, print) { + const printed = []; + const bodyNode = path.getNode(); + const isClass = bodyNode.type === "ClassBody"; + path.map((stmtPath, i) => { + const stmt = stmtPath.getValue(); // Just in case the AST has been modified to contain falsy + // "statements," it's safer simply to skip them. + + /* istanbul ignore if */ + + if (!stmt) { + return; + } // Skip printing EmptyStatement nodes to avoid leaving stray + // semicolons lying around. + + + if (stmt.type === "EmptyStatement") { + return; + } + + const stmtPrinted = print(stmtPath); + const text = options.originalText; + const parts = []; // in no-semi mode, prepend statement with semicolon if it might break ASI + // don't prepend the only JSX element in a program with semicolon + + if (!options.semi && !isClass && !isTheOnlyJSXElementInMarkdown$1(options, stmtPath) && stmtNeedsASIProtection(stmtPath, options)) { + if (stmt.comments && stmt.comments.some(comment => comment.leading)) { + parts.push(print(stmtPath, { + needsSemi: true + })); + } else { + parts.push(";", stmtPrinted); + } + } else { + parts.push(stmtPrinted); + } + + if (!options.semi && isClass) { + if (classPropMayCauseASIProblems$1(stmtPath)) { + parts.push(";"); + } else if (stmt.type === "ClassProperty") { + const nextChild = bodyNode.body[i + 1]; + + if (classChildNeedsASIProtection$1(nextChild)) { + parts.push(";"); + } + } + } + + if (isNextLineEmpty$4(text, stmt, options.locEnd) && !isLastStatement$1(stmtPath)) { + parts.push(hardline$6); + } + + printed.push(concat$c(parts)); + }); + return join$6(hardline$6, printed); +} + +function printPropertyKey(path, options, print) { + const node = path.getNode(); + + if (node.computed) { + return concat$c(["[", path.call(print, "key"), "]"]); + } + + const parent = path.getParentNode(); + const { + key + } = node; + + if (node.type === "ClassPrivateProperty" && // flow has `Identifier` key, and babel has `PrivateName` key + key.type === "Identifier") { + return concat$c(["#", path.call(print, "key")]); + } + + if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) { + const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral$1(prop.key) && !isStringPropSafeToUnquote$1(prop, options)); + needsQuoteProps.set(parent, objectHasStringProp); + } + + if ((key.type === "Identifier" || isNumericLiteral$3(key) && isSimpleNumber$1(printNumber$1(rawText$1(key))) && // Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1. + String(key.value) === printNumber$1(rawText$1(key)) && // Quoting number keys is safe in JS and Flow, but not in TypeScript (as + // mentioned in `isStringPropSafeToUnquote`). + !(options.parser === "typescript" || options.parser === "babel-ts")) && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) { + // a -> "a" + // 1 -> "1" + // 1.5 -> "1.5" + const prop = printString$1(JSON.stringify(key.type === "Identifier" ? key.name : key.value.toString()), options); + return path.call(keyPath => comments.printComments(keyPath, () => prop, options), "key"); + } + + if (isStringPropSafeToUnquote$1(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) { + // 'a' -> a + // '1' -> 1 + // '1.5' -> 1.5 + return path.call(keyPath => comments.printComments(keyPath, () => /^\d/.test(key.value) ? printNumber$1(key.value) : key.value, options), "key"); + } + + return path.call(print, "key"); +} + +function printMethod(path, options, print) { + const node = path.getNode(); + const { + kind + } = node; + const value = node.value || node; + const parts = []; + + if (!kind || kind === "init" || kind === "method" || kind === "constructor") { + if (value.async) { + parts.push("async "); + } + + if (value.generator) { + parts.push("*"); + } + } else { + assert__default['default'].ok(kind === "get" || kind === "set"); + parts.push(kind, " "); + } + + parts.push(printPropertyKey(path, options, print), node.optional || node.key.optional ? "?" : "", node === value ? printMethodInternal(path, options, print) : path.call(path => printMethodInternal(path, options, print), "value")); + return concat$c(parts); +} + +function printMethodInternal(path, options, print) { + const parts = [printFunctionTypeParameters$2(path, options, print), group$7(concat$c([printFunctionParams(path, print, options), printReturnType(path, print, options)]))]; + + if (path.getNode().body) { + parts.push(" ", path.call(print, "body")); + } else { + parts.push(options.semi ? ";" : ""); + } + + return concat$c(parts); +} + +function printJestEachTemplateLiteral(path, options, print) { + /** + * a | b | expected + * ${1} | ${1} | ${2} + * ${1} | ${2} | ${3} + * ${2} | ${1} | ${3} + */ + const node = path.getNode(); + const headerNames = node.quasis[0].value.raw.trim().split(/\s*\|\s*/); + + if (headerNames.length > 1 || headerNames.some(headerName => headerName.length !== 0)) { + options.__inJestEach = true; + const expressions = path.map(print, "expressions"); + options.__inJestEach = false; + const parts = []; + const stringifiedExpressions = expressions.map(doc => "${" + printDocToString$2(doc, Object.assign({}, options, { + printWidth: Infinity, + endOfLine: "lf" + })).formatted + "}"); + const tableBody = [{ + hasLineBreak: false, + cells: [] + }]; + + for (let i = 1; i < node.quasis.length; i++) { + const row = tableBody[tableBody.length - 1]; + const correspondingExpression = stringifiedExpressions[i - 1]; + row.cells.push(correspondingExpression); + + if (correspondingExpression.includes("\n")) { + row.hasLineBreak = true; + } + + if (node.quasis[i].value.raw.includes("\n")) { + tableBody.push({ + hasLineBreak: false, + cells: [] + }); + } + } + + const maxColumnCount = Math.max(headerNames.length, ...tableBody.map(row => row.cells.length)); + const maxColumnWidths = Array.from({ + length: maxColumnCount + }).fill(0); + const table = [{ + cells: headerNames + }, ...tableBody.filter(row => row.cells.length !== 0)]; + + for (const { + cells + } of table.filter(row => !row.hasLineBreak)) { + cells.forEach((cell, index) => { + maxColumnWidths[index] = Math.max(maxColumnWidths[index], getStringWidth$3(cell)); + }); + } + + parts.push(lineSuffixBoundary$1, "`", indent$8(concat$c([hardline$6, join$6(hardline$6, table.map(row => join$6(" | ", row.cells.map((cell, index) => row.hasLineBreak ? cell : cell + " ".repeat(maxColumnWidths[index] - getStringWidth$3(cell))))))])), hardline$6, "`"); + return concat$c(parts); + } +} + +function printTypeAnnotation(path, options, print) { + const node = path.getValue(); + + if (!node.typeAnnotation) { + return ""; + } + + const parentNode = path.getParentNode(); + const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite; + const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node; + + if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation, options)) { + return concat$c([" /*: ", path.call(print, "typeAnnotation"), " */"]); + } + + return concat$c([isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", path.call(print, "typeAnnotation")]); +} + +function printFunctionParams(path, print, options, expandArg, printTypeParams) { + const fun = path.getValue(); + const parent = path.getParentNode(); + const paramsField = fun.parameters ? "parameters" : "params"; + const isParametersInTestCall = isTestCall$1(parent); + const shouldHugParameters = shouldHugArguments(fun); + const shouldExpandParameters = expandArg && !(fun[paramsField] && fun[paramsField].some(n => n.comments)); + const typeParams = printTypeParams ? printFunctionTypeParameters$2(path, options, print) : ""; + let printed = []; + + if (fun[paramsField]) { + const lastArgIndex = fun[paramsField].length - 1; + printed = path.map((childPath, index) => { + const parts = []; + const param = childPath.getValue(); + parts.push(print(childPath)); + + if (index === lastArgIndex) { + if (fun.rest) { + parts.push(",", line$8); + } + } else if (isParametersInTestCall || shouldHugParameters || shouldExpandParameters) { + parts.push(", "); + } else if (isNextLineEmpty$4(options.originalText, param, options.locEnd)) { + parts.push(",", hardline$6, hardline$6); + } else { + parts.push(",", line$8); + } + + return concat$c(parts); + }, paramsField); + } + + if (fun.rest) { + printed.push(concat$c(["...", path.call(print, "rest")])); + } + + if (printed.length === 0) { + return concat$c([typeParams, "(", comments.printDanglingComments(path, options, + /* sameIndent */ + true, comment => getNextNonSpaceNonCommentCharacter$2(options.originalText, comment, options.locEnd) === ")"), ")"]); + } + + const lastParam = getLast$5(fun[paramsField]); // If the parent is a call with the first/last argument expansion and this is the + // params of the first/last argument, we don't want the arguments to break and instead + // want the whole expression to be on a new line. + // + // Good: Bad: + // verylongcall( verylongcall(( + // (a, b) => { a, + // } b, + // }) ) => { + // }) + + if (shouldExpandParameters) { + return group$7(concat$c([removeLines$1(typeParams), "(", concat$c(printed.map(removeLines$1)), ")"])); + } // Single object destructuring should hug + // + // function({ + // a, + // b, + // c + // }) {} + + + const hasNotParameterDecorator = fun[paramsField].every(param => !param.decorators); + + if (shouldHugParameters && hasNotParameterDecorator) { + return concat$c([typeParams, "(", concat$c(printed), ")"]); + } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})` + + + if (isParametersInTestCall) { + return concat$c([typeParams, "(", concat$c(printed), ")"]); + } + + const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent, options) || isTypeAnnotationAFunction$1(parent, options) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === fun) && fun[paramsField].length === 1 && fun[paramsField][0].name === null && fun[paramsField][0].typeAnnotation && fun.typeParameters === null && isSimpleFlowType$1(fun[paramsField][0].typeAnnotation) && !fun.rest; + + if (isFlowShorthandWithOneArg) { + if (options.arrowParens === "always") { + return concat$c(["(", concat$c(printed), ")"]); + } + + return concat$c(printed); + } + + const canHaveTrailingComma = !(lastParam && lastParam.type === "RestElement") && !fun.rest; + return concat$c([typeParams, "(", indent$8(concat$c([softline$6, concat$c(printed)])), ifBreak$4(canHaveTrailingComma && shouldPrintComma$3(options, "all") ? "," : ""), softline$6, ")"]); +} + +function shouldPrintParamsWithoutParens(path, options) { + if (options.arrowParens === "always") { + return false; + } + + if (options.arrowParens === "avoid") { + const node = path.getValue(); + return canPrintParamsWithoutParens(node); + } // Fallback default; should be unreachable + + /* istanbul ignore next */ + + + return false; +} + +function canPrintParamsWithoutParens(node) { + return node.params.length === 1 && !node.rest && !node.typeParameters && !hasDanglingComments$1(node) && node.params[0].type === "Identifier" && !node.params[0].typeAnnotation && !node.params[0].comments && !node.params[0].optional && !node.predicate && !node.returnType; +} + +function printFunctionDeclaration(path, print, options) { + const n = path.getValue(); + const parts = []; + + if (n.async) { + parts.push("async "); + } + + if (n.generator) { + parts.push("function* "); + } else { + parts.push("function "); + } + + if (n.id) { + parts.push(path.call(print, "id")); + } + + parts.push(printFunctionTypeParameters$2(path, options, print), group$7(concat$c([printFunctionParams(path, print, options), printReturnType(path, print, options)])), n.body ? " " : "", path.call(print, "body")); + return concat$c(parts); +} + +function printReturnType(path, print, options) { + const n = path.getValue(); + const returnType = path.call(print, "returnType"); + + if (n.returnType && isFlowAnnotationComment$1(options.originalText, n.returnType, options)) { + return concat$c([" /*: ", returnType, " */"]); + } + + const parts = [returnType]; // prepend colon to TypeScript type annotation + + if (n.returnType && n.returnType.typeAnnotation) { + parts.unshift(": "); + } + + if (n.predicate) { + // The return type will already add the colon, but otherwise we + // need to do it ourselves + parts.push(n.returnType ? " " : ": ", path.call(print, "predicate")); + } + + return concat$c(parts); +} + +function printExportDeclaration(path, options, print) { + const decl = path.getValue(); + const semi = options.semi ? ";" : ""; + /** @type{Doc[]} */ + + const parts = ["export "]; + const isDefault = decl.default || decl.type === "ExportDefaultDeclaration"; + + if (isDefault) { + parts.push("default "); + } + + parts.push(comments.printDanglingComments(path, options, + /* sameIndent */ + true)); + + if (needsHardlineAfterDanglingComment$1(decl)) { + parts.push(hardline$6); + } + + if (decl.declaration) { + parts.push(path.call(print, "declaration")); + + if (isDefault && decl.declaration.type !== "ClassDeclaration" && decl.declaration.type !== "FunctionDeclaration" && decl.declaration.type !== "TSInterfaceDeclaration" && decl.declaration.type !== "DeclareClass" && decl.declaration.type !== "DeclareFunction" && decl.declaration.type !== "TSDeclareFunction" && decl.declaration.type !== "EnumDeclaration") { + parts.push(semi); + } + } else { + parts.push(decl.exportKind === "type" ? "type " : ""); + parts.push(printModuleSpecifiers$1(path, options, print)); + parts.push(printModuleSource$1(path, options, print)); + parts.push(semi); + } + + return concat$c(parts); +} + +function printFlowDeclaration(path, parts) { + const parentExportDecl = getParentExportDeclaration$1(path); + + if (parentExportDecl) { + assert__default['default'].strictEqual(parentExportDecl.type, "DeclareExportDeclaration"); + } else { + // If the parent node has type DeclareExportDeclaration, then it + // will be responsible for printing the "declare" token. Otherwise + // it needs to be printed with this non-exported declaration node. + parts.unshift("declare "); + } + + return concat$c(parts); +} + +function printTypeScriptModifiers(path, options, print) { + const n = path.getValue(); + + if (!n.modifiers || !n.modifiers.length) { + return ""; + } + + return concat$c([join$6(" ", path.map(print, "modifiers")), " "]); +} + +const typeParametersGroupIds = new WeakMap(); + +function getTypeParametersGroupId(node) { + if (!typeParametersGroupIds.has(node)) { + typeParametersGroupIds.set(node, Symbol("typeParameters")); + } + + return typeParametersGroupIds.get(node); +} + +function printTypeParameters(path, options, print, paramsKey) { + const n = path.getValue(); + + if (!n[paramsKey]) { + return ""; + } // for TypeParameterDeclaration typeParameters is a single node + + + if (!Array.isArray(n[paramsKey])) { + return path.call(print, paramsKey); + } + + const grandparent = path.getNode(2); + const greatGrandParent = path.getNode(3); + const greatGreatGrandParent = path.getNode(4); + const isParameterInTestCall = grandparent != null && isTestCall$1(grandparent); + const shouldInline = isParameterInTestCall || n[paramsKey].length === 0 || n[paramsKey].length === 1 && (shouldHugType(n[paramsKey][0]) || n[paramsKey][0].type === "GenericTypeAnnotation" && shouldHugType(n[paramsKey][0].id) || n[paramsKey][0].type === "TSTypeReference" && shouldHugType(n[paramsKey][0].typeName) || n[paramsKey][0].type === "NullableTypeAnnotation" || // See https://github.com/prettier/prettier/pull/6467 for the context. + greatGreatGrandParent && greatGreatGrandParent.type === "VariableDeclarator" && grandparent.type === "TSTypeAnnotation" && greatGrandParent.type !== "ArrowFunctionExpression" && n[paramsKey][0].type !== "TSUnionType" && n[paramsKey][0].type !== "UnionTypeAnnotation" && n[paramsKey][0].type !== "TSIntersectionType" && n[paramsKey][0].type !== "IntersectionTypeAnnotation" && n[paramsKey][0].type !== "TSConditionalType" && n[paramsKey][0].type !== "TSMappedType" && n[paramsKey][0].type !== "TSTypeOperator" && n[paramsKey][0].type !== "TSIndexedAccessType" && n[paramsKey][0].type !== "TSArrayType"); + + function printDanglingCommentsForInline(n) { + if (!hasDanglingComments$1(n)) { + return ""; + } + + const hasOnlyBlockComments = n.comments.every(comments$1.isBlockComment); + const printed = comments.printDanglingComments(path, options, + /* sameIndent */ + hasOnlyBlockComments); + + if (hasOnlyBlockComments) { + return printed; + } + + return concat$c([printed, hardline$6]); + } + + if (shouldInline) { + return concat$c(["<", join$6(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(n), ">"]); + } + + return group$7(concat$c(["<", indent$8(concat$c([softline$6, join$6(concat$c([",", line$8]), path.map(print, paramsKey))])), ifBreak$4(options.parser !== "typescript" && options.parser !== "babel-ts" && shouldPrintComma$3(options, "all") ? "," : ""), softline$6, ">"]), { + id: getTypeParametersGroupId(n) + }); +} + +function printClass(path, options, print) { + const n = path.getValue(); + const parts = []; + + if (n.abstract) { + parts.push("abstract "); + } + + parts.push("class"); // Keep old behaviour of extends in same line + // If there is only on extends and there are not comments + + const groupMode = n.id && hasTrailingComment$3(n.id) || n.superClass && n.superClass.comments && n.superClass.comments.length !== 0 || n.extends && n.extends.length !== 0 || // DeclareClass + n.mixins && n.mixins.length !== 0 || n.implements && n.implements.length !== 0; + const partsGroup = []; + const extendsParts = []; + + if (n.id) { + partsGroup.push(" ", path.call(print, "id")); + } + + partsGroup.push(path.call(print, "typeParameters")); + const hasMultipleHeritage = ["superClass", "extends", "mixins", "implements"].filter(key => !!n[key]).length > 1; + const shouldIndentOnlyHeritageClauses = n.typeParameters && !hasTrailingLineComment$1(n.typeParameters) && !hasMultipleHeritage; + + function printList(listName) { + if (n[listName] && n[listName].length !== 0) { + const printedLeadingComments = comments.printDanglingComments(path, options, + /* sameIndent */ + true, ({ + marker + }) => marker === listName); + extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$4(" ", line$8, { + groupId: getTypeParametersGroupId(n.typeParameters) + }) : line$8, printedLeadingComments, printedLeadingComments && hardline$6, listName, group$7(indent$8(concat$c([line$8, join$6(concat$c([",", line$8]), path.map(print, listName))])))); + } + } + + if (n.superClass) { + const printed = concat$c(["extends ", path.call(print, "superClass"), path.call(print, "superTypeParameters")]); + const printedWithComments = path.call(superClass => comments.printComments(superClass, () => printed, options), "superClass"); + + if (groupMode) { + extendsParts.push(line$8, group$7(printedWithComments)); + } else { + extendsParts.push(" ", printedWithComments); + } + } else { + printList("extends"); + } + + printList("mixins"); + printList("implements"); + + if (groupMode) { + const printedExtends = concat$c(extendsParts); + + if (shouldIndentOnlyHeritageClauses) { + parts.push(group$7(concat$c(partsGroup.concat(ifBreak$4(indent$8(printedExtends), printedExtends))))); + } else { + parts.push(group$7(indent$8(concat$c(partsGroup.concat(printedExtends))))); + } + } else { + parts.push(...partsGroup, ...extendsParts); + } + + parts.push(" ", path.call(print, "body")); + return parts; +} + +function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) { + if (isFacebookTranslationTag) { + return ""; + } + + if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) { + return child.length === 1 ? softline$6 : hardline$6; + } + + return softline$6; +} + +function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) { + if (isFacebookTranslationTag) { + return hardline$6; + } + + if (child.length === 1) { + return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$6 : softline$6; + } + + return hardline$6; +} // JSX Children are strange, mostly for two reasons: +// 1. JSX reads newlines into string values, instead of skipping them like JS +// 2. up to one whitespace between elements within a line is significant, +// but not between lines. +// +// Leading, trailing, and lone whitespace all need to +// turn themselves into the rather ugly `{' '}` when breaking. +// +// We print JSX using the `fill` doc primitive. +// This requires that we give it an array of alternating +// content and whitespace elements. +// To ensure this we add dummy `""` content elements as needed. + + +function printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) { + const n = path.getValue(); + const children = []; // using `map` instead of `each` because it provides `i` + + path.map((childPath, i) => { + const child = childPath.getValue(); + + if (isLiteral$1(child)) { + const text = rawText$1(child); // Contains a non-whitespace character + + if (isMeaningfulJSXText$1(child)) { + const words = text.split(matchJsxWhitespaceRegex$1); // Starts with whitespace + + if (words[0] === "") { + children.push(""); + words.shift(); + + if (/\n/.test(words[0])) { + const next = n.children[i + 1]; + children.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next)); + } else { + children.push(jsxWhitespace); + } + + words.shift(); + } + + let endWhitespace; // Ends with whitespace + + if (getLast$5(words) === "") { + words.pop(); + endWhitespace = words.pop(); + } // This was whitespace only without a new line. + + + if (words.length === 0) { + return; + } + + words.forEach((word, i) => { + if (i % 2 === 1) { + children.push(line$8); + } else { + children.push(word); + } + }); + + if (endWhitespace !== undefined) { + if (/\n/.test(endWhitespace)) { + const next = n.children[i + 1]; + children.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$5(children), child, next)); + } else { + children.push(jsxWhitespace); + } + } else { + const next = n.children[i + 1]; + children.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$5(children), child, next)); + } + } else if (/\n/.test(text)) { + // Keep (up to one) blank line between tags/expressions/text. + // Note: We don't keep blank lines between text elements. + if (text.match(/\n/g).length > 1) { + children.push(""); + children.push(hardline$6); + } + } else { + children.push(""); + children.push(jsxWhitespace); + } + } else { + const printedChild = print(childPath); + children.push(printedChild); + const next = n.children[i + 1]; + const directlyFollowedByMeaningfulText = next && isMeaningfulJSXText$1(next); + + if (directlyFollowedByMeaningfulText) { + const firstWord = rawText$1(next).trim().split(matchJsxWhitespaceRegex$1)[0]; + children.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next)); + } else { + children.push(hardline$6); + } + } + }, "children"); + return children; +} // JSX expands children from the inside-out, instead of the outside-in. +// This is both to break children before attributes, +// and to ensure that when children break, their parents do as well. +// +// Any element that is written without any newlines and fits on a single line +// is left that way. +// Not only that, any user-written-line containing multiple JSX siblings +// should also be kept on one line if possible, +// so each user-written-line is wrapped in its own group. +// +// Elements that contain newlines or don't fit on a single line (recursively) +// are fully-split, using hardline and shouldBreak: true. +// +// To support that case properly, all leading and trailing spaces +// are stripped from the list of children, and replaced with a single hardline. + + +function printJSXElement(path, options, print) { + const n = path.getValue(); + + if (n.type === "JSXElement" && isEmptyJSXElement$1(n)) { + return concat$c([path.call(print, "openingElement"), path.call(print, "closingElement")]); + } + + const openingLines = n.type === "JSXElement" ? path.call(print, "openingElement") : path.call(print, "openingFragment"); + const closingLines = n.type === "JSXElement" ? path.call(print, "closingElement") : path.call(print, "closingFragment"); + + if (n.children.length === 1 && n.children[0].type === "JSXExpressionContainer" && (n.children[0].expression.type === "TemplateLiteral" || n.children[0].expression.type === "TaggedTemplateExpression")) { + return concat$c([openingLines, concat$c(path.map(print, "children")), closingLines]); + } // Convert `{" "}` to text nodes containing a space. + // This makes it easy to turn them into `jsxWhitespace` which + // can then print as either a space or `{" "}` when breaking. + + + n.children = n.children.map(child => { + if (isJSXWhitespaceExpression$1(child)) { + return { + type: "JSXText", + value: " ", + raw: " " + }; + } + + return child; + }); + const containsTag = n.children.filter(isJSXNode$3).length > 0; + const containsMultipleExpressions = n.children.filter(child => child.type === "JSXExpressionContainer").length > 1; + const containsMultipleAttributes = n.type === "JSXElement" && n.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true. + + let forcedBreak = willBreak$3(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions; + const isMdxBlock = path.getParentNode().rootMarker === "mdx"; + const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}'; + const jsxWhitespace = isMdxBlock ? concat$c([" "]) : ifBreak$4(concat$c([rawJsxWhitespace, softline$6]), " "); + const isFacebookTranslationTag = n.openingElement && n.openingElement.name && n.openingElement.name.name === "fbt"; + const children = printJSXChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag); + const containsText = n.children.some(child => isMeaningfulJSXText$1(child)); // We can end up we multiple whitespace elements with empty string + // content between them. + // We need to remove empty whitespace and softlines before JSX whitespace + // to get the correct output. + + for (let i = children.length - 2; i >= 0; i--) { + const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === ""; + const isPairOfHardlines = children[i] === hardline$6 && children[i + 1] === "" && children[i + 2] === hardline$6; + const isLineFollowedByJSXWhitespace = (children[i] === softline$6 || children[i] === hardline$6) && children[i + 1] === "" && children[i + 2] === jsxWhitespace; + const isJSXWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$6 || children[i + 2] === hardline$6); + const isDoubleJSXWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace; + const isPairOfHardOrSoftLines = children[i] === softline$6 && children[i + 1] === "" && children[i + 2] === hardline$6 || children[i] === hardline$6 && children[i + 1] === "" && children[i + 2] === softline$6; + + if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJSXWhitespace || isDoubleJSXWhitespace || isPairOfHardOrSoftLines) { + children.splice(i, 2); + } else if (isJSXWhitespaceFollowedByLine) { + children.splice(i + 1, 2); + } + } // Trim trailing lines (or empty strings) + + + while (children.length && (isLineNext$1(getLast$5(children)) || isEmpty$1(getLast$5(children)))) { + children.pop(); + } // Trim leading lines (or empty strings) + + + while (children.length && (isLineNext$1(children[0]) || isEmpty$1(children[0])) && (isLineNext$1(children[1]) || isEmpty$1(children[1]))) { + children.shift(); + children.shift(); + } // Tweak how we format children if outputting this element over multiple lines. + // Also detect whether we will force this element to output over multiple lines. + + + const multilineChildren = []; + children.forEach((child, i) => { + // There are a number of situations where we need to ensure we display + // whitespace as `{" "}` when outputting this element over multiple lines. + if (child === jsxWhitespace) { + if (i === 1 && children[i - 1] === "") { + if (children.length === 2) { + // Solitary whitespace + multilineChildren.push(rawJsxWhitespace); + return; + } // Leading whitespace + + + multilineChildren.push(concat$c([rawJsxWhitespace, hardline$6])); + return; + } else if (i === children.length - 1) { + // Trailing whitespace + multilineChildren.push(rawJsxWhitespace); + return; + } else if (children[i - 1] === "" && children[i - 2] === hardline$6) { + // Whitespace after line break + multilineChildren.push(rawJsxWhitespace); + return; + } + } + + multilineChildren.push(child); + + if (willBreak$3(child)) { + forcedBreak = true; + } + }); // If there is text we use `fill` to fit as much onto each line as possible. + // When there is no text (just tags and expressions) we use `group` + // to output each on a separate line. + + const content = containsText ? fill$3(multilineChildren) : group$7(concat$c(multilineChildren), { + shouldBreak: true + }); + + if (isMdxBlock) { + return content; + } + + const multiLineElem = group$7(concat$c([openingLines, indent$8(concat$c([hardline$6, content])), hardline$6, closingLines])); + + if (forcedBreak) { + return multiLineElem; + } + + return conditionalGroup$3([group$7(concat$c([openingLines, concat$c(children), closingLines])), multiLineElem]); +} + +function maybeWrapJSXElementInParens(path, elem, options) { + const parent = path.getParentNode(); + /* istanbul ignore next */ + + if (!parent) { + return elem; + } + + const NO_WRAP_PARENTS = { + ArrayExpression: true, + JSXAttribute: true, + JSXElement: true, + JSXExpressionContainer: true, + JSXFragment: true, + ExpressionStatement: true, + CallExpression: true, + OptionalCallExpression: true, + ConditionalExpression: true, + JsExpressionRoot: true + }; + + if (NO_WRAP_PARENTS[parent.type]) { + return elem; + } + + const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallOrOptionalCallExpression$2, node => node.type === "JSXExpressionContainer"); + const needsParens = needsParens_1(path, options); + return group$7(concat$c([needsParens ? "" : ifBreak$4("("), indent$8(concat$c([softline$6, elem])), softline$6, needsParens ? "" : ifBreak$4(")")]), { + shouldBreak + }); +} + +function shouldInlineLogicalExpression(node) { + if (node.type !== "LogicalExpression") { + return false; + } + + if (node.right.type === "ObjectExpression" && node.right.properties.length !== 0) { + return true; + } + + if (node.right.type === "ArrayExpression" && node.right.elements.length !== 0) { + return true; + } + + if (isJSXNode$3(node.right)) { + return true; + } + + return false; +} // For binary expressions to be consistent, we need to group +// subsequent operators with the same precedence level under a single +// group. Otherwise they will be nested such that some of them break +// onto new lines but not all. Operators with the same precedence +// level should either all break or not. Because we group them by +// precedence level and the AST is structured based on precedence +// level, things are naturally broken up correctly, i.e. `&&` is +// broken before `+`. + + +function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) { + /** @type{Doc[]} */ + let parts = []; + const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same. + + if (isBinaryish$1(node)) { + // Put all operators with the same precedence level in the same + // group. The reason we only need to do this with the `left` + // expression is because given an expression like `1 + 2 - 3`, it + // is always parsed like `((1 + 2) - 3)`, meaning the `left` side + // is where the rest of the expression will exist. Binary + // expressions on the right side mean they have a difference + // precedence level and should be treated as a separate group, so + // print them normally. (This doesn't hold for the `**` operator, + // which is unique in that it is right-associative.) + if (shouldFlatten$2(node.operator, node.left.operator)) { + // Flatten them out by recursively calling this function. + parts = parts.concat(path.call(left => printBinaryishExpressions(left, print, options, + /* isNested */ + true, isInsideParenthesis), "left")); + } else { + parts.push(group$7(path.call(print, "left"))); + } + + const shouldInline = shouldInlineLogicalExpression(node); + const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$1(options.originalText, node.right, options); + const operator = node.type === "NGPipeExpression" ? "|" : node.operator; + const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length !== 0 ? group$7(indent$8(concat$c([softline$6, ": ", join$6(concat$c([softline$6, ":", ifBreak$4(" ")]), path.map(print, "arguments").map(arg => align$2(2, group$7(arg))))]))) : ""; + const right = shouldInline ? concat$c([operator, " ", path.call(print, "right"), rightSuffix]) : concat$c([lineBeforeOperator ? line$8 : "", operator, lineBeforeOperator ? " " : line$8, path.call(print, "right"), rightSuffix]); // If there's only a single binary expression, we want to create a group + // in order to avoid having a small right part like -1 be on its own line. + + const parent = path.getParentNode(); + const shouldBreak = hasTrailingLineComment$1(node.left); + const shouldGroup = shouldBreak || !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type; + parts.push(lineBeforeOperator ? "" : " ", shouldGroup ? group$7(right, { + shouldBreak + }) : right); // The root comments are already printed, but we need to manually print + // the other ones since we don't call the normal print on BinaryExpression, + // only for the left and right parts + + if (isNested && node.comments) { + parts = normalizeParts$1(comments.printComments(path, () => concat$c(parts), options).parts); + } + } else { + // Our stopping case. Simply print the node normally. + parts.push(group$7(path.call(print))); + } + + return parts; +} + +function printAssignmentRight(leftNode, rightNode, printedRight, options) { + if (hasLeadingOwnLineComment$1(options.originalText, rightNode, options)) { + return indent$8(concat$c([line$8, printedRight])); + } + + const canBreak = isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode) || rightNode.type === "ConditionalExpression" && isBinaryish$1(rightNode.test) && !shouldInlineLogicalExpression(rightNode.test) || rightNode.type === "StringLiteralTypeAnnotation" || rightNode.type === "ClassExpression" && rightNode.decorators && rightNode.decorators.length || (leftNode.type === "Identifier" || isStringLiteral$1(leftNode) || leftNode.type === "MemberExpression") && (isStringLiteral$1(rightNode) || isMemberExpressionChain$1(rightNode)) && // do not put values on a separate line from the key in json + options.parser !== "json" && options.parser !== "json5" || rightNode.type === "SequenceExpression"; + + if (canBreak) { + return group$7(indent$8(concat$c([line$8, printedRight]))); + } + + return concat$c([" ", printedRight]); +} + +function printAssignment(leftNode, printedLeft, operator, rightNode, printedRight, options) { + if (!rightNode) { + return printedLeft; + } + + const printed = printAssignmentRight(leftNode, rightNode, printedRight, options); + return group$7(concat$c([printedLeft, operator, printed])); +} + +function adjustClause(node, clause, forceSpace) { + if (node.type === "EmptyStatement") { + return ";"; + } + + if (node.type === "BlockStatement" || forceSpace) { + return concat$c([" ", clause]); + } + + return indent$8(concat$c([line$8, clause])); +} + +function nodeStr(node, options, isFlowOrTypeScriptDirectiveLiteral) { + const raw = rawText$1(node); + const isDirectiveLiteral = isFlowOrTypeScriptDirectiveLiteral || node.type === "DirectiveLiteral"; + return printString$1(raw, options, isDirectiveLiteral); +} + +function printRegex(node) { + const flags = node.flags.split("").sort().join(""); + return `/${node.pattern}/${flags}`; +} + +function exprNeedsASIProtection(path, options) { + const node = path.getValue(); + const maybeASIProblem = needsParens_1(path, options) || node.type === "ParenthesizedExpression" || node.type === "TypeCastExpression" || node.type === "ArrowFunctionExpression" && !shouldPrintParamsWithoutParens(path, options) || node.type === "ArrayExpression" || node.type === "ArrayPattern" || node.type === "UnaryExpression" && node.prefix && (node.operator === "+" || node.operator === "-") || node.type === "TemplateLiteral" || node.type === "TemplateElement" || isJSXNode$3(node) || node.type === "BindExpression" && !node.object || node.type === "RegExpLiteral" || node.type === "Literal" && node.pattern || node.type === "Literal" && node.regex; + + if (maybeASIProblem) { + return true; + } + + if (!hasNakedLeftSide$2(node)) { + return false; + } + + return path.call(childPath => exprNeedsASIProtection(childPath, options), ...getLeftSidePathName$2(path, node)); +} + +function stmtNeedsASIProtection(path, options) { + const node = path.getNode(); + + if (node.type !== "ExpressionStatement") { + return false; + } + + return path.call(childPath => exprNeedsASIProtection(childPath, options), "expression"); +} + +function shouldHugType(node) { + if (isSimpleFlowType$1(node) || isObjectType$1(node)) { + return true; + } + + if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") { + const voidCount = node.types.filter(n => n.type === "VoidTypeAnnotation" || n.type === "TSVoidKeyword" || n.type === "NullLiteralTypeAnnotation" || n.type === "TSNullKeyword").length; + const hasObject = node.types.some(n => n.type === "ObjectTypeAnnotation" || n.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}> + n.type === "GenericTypeAnnotation" || n.type === "TSTypeReference"); + + if (node.types.length - 1 === voidCount && hasObject) { + return true; + } + } + + return false; +} + +function shouldHugArguments(fun) { + if (!fun || fun.rest) { + return false; + } + + const params = fun.params || fun.parameters; + + if (!params || params.length !== 1) { + return false; + } + + const param = params[0]; + return !param.comments && (param.type === "ObjectPattern" || param.type === "ArrayPattern" || param.type === "Identifier" && param.typeAnnotation && (param.typeAnnotation.type === "TypeAnnotation" || param.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(param.typeAnnotation.typeAnnotation) || param.type === "FunctionTypeParam" && isObjectType$1(param.typeAnnotation) || param.type === "AssignmentPattern" && (param.left.type === "ObjectPattern" || param.left.type === "ArrayPattern") && (param.right.type === "Identifier" || param.right.type === "ObjectExpression" && param.right.properties.length === 0 || param.right.type === "ArrayExpression" && param.right.elements.length === 0)); +} + +function printArrayItems(path, options, printPath, print) { + const printedElements = []; + let separatorParts = []; + path.each(childPath => { + printedElements.push(concat$c(separatorParts)); + printedElements.push(group$7(print(childPath))); + separatorParts = [",", line$8]; + + if (childPath.getValue() && isNextLineEmpty$4(options.originalText, childPath.getValue(), options.locEnd)) { + separatorParts.push(softline$6); + } + }, printPath); + return concat$c(printedElements); +} + +function printReturnAndThrowArgument(path, options, print) { + const node = path.getValue(); + const semi = options.semi ? ";" : ""; + const parts = []; + + if (node.argument) { + if (returnArgumentHasLeadingComment$1(options, node.argument)) { + parts.push(concat$c([" (", indent$8(concat$c([hardline$6, path.call(print, "argument")])), hardline$6, ")"])); + } else if (isBinaryish$1(node.argument) || node.argument.type === "SequenceExpression") { + parts.push(group$7(concat$c([ifBreak$4(" (", " "), indent$8(concat$c([softline$6, path.call(print, "argument")])), softline$6, ifBreak$4(")")]))); + } else { + parts.push(" ", path.call(print, "argument")); + } + } + + const lastComment = Array.isArray(node.comments) && node.comments[node.comments.length - 1]; + const isLastCommentLine = lastComment && (lastComment.type === "CommentLine" || lastComment.type === "Line"); + + if (isLastCommentLine) { + parts.push(semi); + } + + if (hasDanglingComments$1(node)) { + parts.push(" ", comments.printDanglingComments(path, options, + /* sameIndent */ + true)); + } + + if (!isLastCommentLine) { + parts.push(semi); + } + + return concat$c(parts); +} + +function willPrintOwnComments(path +/*, options */ +) { + const node = path.getValue(); + const parent = path.getParentNode(); + return (node && (isJSXNode$3(node) || hasFlowShorthandAnnotationComment$2(node) || parent && (parent.type === "CallExpression" || parent.type === "OptionalCallExpression") && (hasFlowAnnotationComment$1(node.leadingComments) || hasFlowAnnotationComment$1(node.trailingComments))) || parent && (parent.type === "JSXSpreadAttribute" || parent.type === "JSXSpreadChild" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || (parent.type === "ClassDeclaration" || parent.type === "ClassExpression") && parent.superClass === node)) && (!hasIgnoreComment$2(path) || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType"); +} + +function canAttachComment(node) { + return node.type && node.type !== "CommentBlock" && node.type !== "CommentLine" && node.type !== "Line" && node.type !== "Block" && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import"; +} + +function printComment$1(commentPath, options) { + const comment = commentPath.getValue(); + + switch (comment.type) { + case "CommentBlock": + case "Block": + { + if (isIndentableBlockComment(comment)) { + const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment + // printed as a `lineSuffix` which causes the comments to be + // interleaved. See https://github.com/prettier/prettier/issues/4412 + + if (comment.trailing && !hasNewline$5(options.originalText, options.locStart(comment), { + backwards: true + })) { + return concat$c([hardline$6, printed]); + } + + return printed; + } + + const commentEnd = options.locEnd(comment); + const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/"; + return "/*" + comment.value + (isInsideFlowComment ? "*-/" : "*/"); + } + + case "CommentLine": + case "Line": + // Supports `//`, `#!`, `` + return options.originalText.slice(options.locStart(comment), options.locEnd(comment)).trimEnd(); + + default: + /* istanbul ignore next */ + throw new Error("Not a comment: " + JSON.stringify(comment)); + } +} + +function isIndentableBlockComment(comment) { + // If the comment has multiple lines and every line starts with a star + // we can fix the indentation of each line. The stars in the `/*` and + // `*/` delimiters are not included in the comment value, so add them + // back first. + const lines = `*${comment.value}*`.split("\n"); + return lines.length > 1 && lines.every(line => line.trim()[0] === "*"); +} + +function printIndentableBlockComment(comment) { + const lines = comment.value.split("\n"); + return concat$c(["/*", join$6(hardline$6, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]); +} + +var printerEstree = { + preprocess: preprocess_1, + print: genericPrint, + embed: embed_1, + insertPragma: insertPragma$1, + massageAstNode: clean_1, + hasPrettierIgnore: hasPrettierIgnore$1, + willPrintOwnComments, + canAttachComment, + printComment: printComment$1, + isBlockComment: comments$1.isBlockComment, + handleComments: { + ownLine: comments$1.handleOwnLineComment, + endOfLine: comments$1.handleEndOfLineComment, + remaining: comments$1.handleRemainingComment + }, + getGapRegex: comments$1.getGapRegex, + getCommentChildNodes: comments$1.getCommentChildNodes +}; + +const { + concat: concat$d, + hardline: hardline$7, + indent: indent$9, + join: join$7 +} = document.builders; + +function genericPrint$1(path, options, print) { + const node = path.getValue(); + + switch (node.type) { + case "JsonRoot": + return concat$d([path.call(print, "node"), hardline$7]); + + case "ArrayExpression": + return node.elements.length === 0 ? "[]" : concat$d(["[", indent$9(concat$d([hardline$7, join$7(concat$d([",", hardline$7]), path.map(print, "elements"))])), hardline$7, "]"]); + + case "ObjectExpression": + return node.properties.length === 0 ? "{}" : concat$d(["{", indent$9(concat$d([hardline$7, join$7(concat$d([",", hardline$7]), path.map(print, "properties"))])), hardline$7, "}"]); + + case "ObjectProperty": + return concat$d([path.call(print, "key"), ": ", path.call(print, "value")]); + + case "UnaryExpression": + return concat$d([node.operator === "+" ? "" : node.operator, path.call(print, "argument")]); + + case "NullLiteral": + return "null"; + + case "BooleanLiteral": + return node.value ? "true" : "false"; + + case "StringLiteral": + case "NumericLiteral": + return JSON.stringify(node.value); + + case "Identifier": + return JSON.stringify(node.name); + + default: + /* istanbul ignore next */ + throw new Error("unknown type: " + JSON.stringify(node.type)); + } +} + +function clean$1(node, newNode +/*, parent*/ +) { + delete newNode.start; + delete newNode.end; + delete newNode.extra; + delete newNode.loc; + delete newNode.comments; + delete newNode.errors; + delete newNode.range; + + if (node.type === "Identifier") { + return { + type: "StringLiteral", + value: node.name + }; + } + + if (node.type === "UnaryExpression" && node.operator === "+") { + return newNode.argument; + } +} + +var printerEstreeJson = { + preprocess: preprocess_1, + print: genericPrint$1, + massageAstNode: clean$1 +}; + +const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js + +var commonOptions = { + bracketSpacing: { + since: "0.0.0", + category: CATEGORY_COMMON, + type: "boolean", + default: true, + description: "Print spaces between brackets.", + oppositeDescription: "Do not print spaces between brackets." + }, + singleQuote: { + since: "0.0.0", + category: CATEGORY_COMMON, + type: "boolean", + default: false, + description: "Use single quotes instead of double quotes." + }, + proseWrap: { + since: "1.8.2", + category: CATEGORY_COMMON, + type: "choice", + default: [{ + since: "1.8.2", + value: true + }, { + since: "1.9.0", + value: "preserve" + }], + description: "How to wrap prose.", + choices: [{ + since: "1.9.0", + value: "always", + description: "Wrap prose if it exceeds the print width." + }, { + since: "1.9.0", + value: "never", + description: "Do not wrap prose." + }, { + since: "1.9.0", + value: "preserve", + description: "Wrap prose as-is." + }] + } +}; + +const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js + +var options$2 = { + arrowParens: { + since: "1.9.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: [{ + since: "1.9.0", + value: "avoid" + }, { + since: "2.0.0", + value: "always" + }], + description: "Include parentheses around a sole arrow function parameter.", + choices: [{ + value: "always", + description: "Always include parens. Example: `(x) => x`" + }, { + value: "avoid", + description: "Omit parens when possible. Example: `x => x`" + }] + }, + bracketSpacing: commonOptions.bracketSpacing, + jsxBracketSameLine: { + since: "0.17.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: false, + description: "Put > on the last line instead of at a new line." + }, + semi: { + since: "1.0.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: true, + description: "Print semicolons.", + oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them." + }, + singleQuote: commonOptions.singleQuote, + jsxSingleQuote: { + since: "1.15.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: false, + description: "Use single quotes in JSX." + }, + quoteProps: { + since: "1.17.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: "as-needed", + description: "Change when properties in objects are quoted.", + choices: [{ + value: "as-needed", + description: "Only add quotes around object properties where required." + }, { + value: "consistent", + description: "If at least one property in an object requires quotes, quote all properties." + }, { + value: "preserve", + description: "Respect the input use of quotes in object properties." + }] + }, + trailingComma: { + since: "0.0.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: [{ + since: "0.0.0", + value: false + }, { + since: "0.19.0", + value: "none" + }, { + since: "2.0.0", + value: "es5" + }], + description: "Print trailing commas wherever possible when multi-line.", + choices: [{ + value: "es5", + description: "Trailing commas where valid in ES5 (objects, arrays, etc.)" + }, { + value: "none", + description: "No trailing commas." + }, { + value: "all", + description: "Trailing commas wherever possible (including function arguments)." + }] + } +}; + +var name$2 = "JavaScript"; +var type = "programming"; +var tmScope = "source.js"; +var aceMode = "javascript"; +var codemirrorMode = "javascript"; +var codemirrorMimeType = "text/javascript"; +var color = "#f1e05a"; +var aliases = [ + "js", + "node" +]; +var extensions = [ + ".js", + "._js", + ".bones", + ".cjs", + ".es", + ".es6", + ".frag", + ".gs", + ".jake", + ".jsb", + ".jscad", + ".jsfl", + ".jsm", + ".jss", + ".mjs", + ".njs", + ".pac", + ".sjs", + ".ssjs", + ".xsjs", + ".xsjslib" +]; +var filenames = [ + "Jakefile" +]; +var interpreters = [ + "chakra", + "d8", + "gjs", + "js", + "node", + "qjs", + "rhino", + "v8", + "v8-shell" +]; +var languageId = 183; +var JavaScript = { + name: name$2, + type: type, + tmScope: tmScope, + aceMode: aceMode, + codemirrorMode: codemirrorMode, + codemirrorMimeType: codemirrorMimeType, + color: color, + aliases: aliases, + extensions: extensions, + filenames: filenames, + interpreters: interpreters, + languageId: languageId +}; + +var JavaScript$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$2, + type: type, + tmScope: tmScope, + aceMode: aceMode, + codemirrorMode: codemirrorMode, + codemirrorMimeType: codemirrorMimeType, + color: color, + aliases: aliases, + extensions: extensions, + filenames: filenames, + interpreters: interpreters, + languageId: languageId, + 'default': JavaScript +}); + +var name$3 = "JSX"; +var type$1 = "programming"; +var group$8 = "JavaScript"; +var extensions$1 = [ + ".jsx" +]; +var tmScope$1 = "source.js.jsx"; +var aceMode$1 = "javascript"; +var codemirrorMode$1 = "jsx"; +var codemirrorMimeType$1 = "text/jsx"; +var languageId$1 = 178; +var JSX = { + name: name$3, + type: type$1, + group: group$8, + extensions: extensions$1, + tmScope: tmScope$1, + aceMode: aceMode$1, + codemirrorMode: codemirrorMode$1, + codemirrorMimeType: codemirrorMimeType$1, + languageId: languageId$1 +}; + +var JSX$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$3, + type: type$1, + group: group$8, + extensions: extensions$1, + tmScope: tmScope$1, + aceMode: aceMode$1, + codemirrorMode: codemirrorMode$1, + codemirrorMimeType: codemirrorMimeType$1, + languageId: languageId$1, + 'default': JSX +}); + +var name$4 = "TypeScript"; +var type$2 = "programming"; +var color$1 = "#2b7489"; +var aliases$1 = [ + "ts" +]; +var interpreters$1 = [ + "deno", + "ts-node" +]; +var extensions$2 = [ + ".ts" +]; +var tmScope$2 = "source.ts"; +var aceMode$2 = "typescript"; +var codemirrorMode$2 = "javascript"; +var codemirrorMimeType$2 = "application/typescript"; +var languageId$2 = 378; +var TypeScript = { + name: name$4, + type: type$2, + color: color$1, + aliases: aliases$1, + interpreters: interpreters$1, + extensions: extensions$2, + tmScope: tmScope$2, + aceMode: aceMode$2, + codemirrorMode: codemirrorMode$2, + codemirrorMimeType: codemirrorMimeType$2, + languageId: languageId$2 +}; + +var TypeScript$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$4, + type: type$2, + color: color$1, + aliases: aliases$1, + interpreters: interpreters$1, + extensions: extensions$2, + tmScope: tmScope$2, + aceMode: aceMode$2, + codemirrorMode: codemirrorMode$2, + codemirrorMimeType: codemirrorMimeType$2, + languageId: languageId$2, + 'default': TypeScript +}); + +var name$5 = "TSX"; +var type$3 = "programming"; +var group$9 = "TypeScript"; +var extensions$3 = [ + ".tsx" +]; +var tmScope$3 = "source.tsx"; +var aceMode$3 = "javascript"; +var codemirrorMode$3 = "jsx"; +var codemirrorMimeType$3 = "text/jsx"; +var languageId$3 = 94901924; +var TSX = { + name: name$5, + type: type$3, + group: group$9, + extensions: extensions$3, + tmScope: tmScope$3, + aceMode: aceMode$3, + codemirrorMode: codemirrorMode$3, + codemirrorMimeType: codemirrorMimeType$3, + languageId: languageId$3 +}; + +var TSX$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$5, + type: type$3, + group: group$9, + extensions: extensions$3, + tmScope: tmScope$3, + aceMode: aceMode$3, + codemirrorMode: codemirrorMode$3, + codemirrorMimeType: codemirrorMimeType$3, + languageId: languageId$3, + 'default': TSX +}); + +var name$6 = "JSON"; +var type$4 = "data"; +var tmScope$4 = "source.json"; +var aceMode$4 = "json"; +var codemirrorMode$4 = "javascript"; +var codemirrorMimeType$4 = "application/json"; +var searchable = false; +var extensions$4 = [ + ".json", + ".avsc", + ".geojson", + ".gltf", + ".har", + ".ice", + ".JSON-tmLanguage", + ".jsonl", + ".mcmeta", + ".tfstate", + ".tfstate.backup", + ".topojson", + ".webapp", + ".webmanifest", + ".yy", + ".yyp" +]; +var filenames$1 = [ + ".arcconfig", + ".htmlhintrc", + ".tern-config", + ".tern-project", + ".watchmanconfig", + "composer.lock", + "mcmod.info" +]; +var languageId$4 = 174; +var _JSON = { + name: name$6, + type: type$4, + tmScope: tmScope$4, + aceMode: aceMode$4, + codemirrorMode: codemirrorMode$4, + codemirrorMimeType: codemirrorMimeType$4, + searchable: searchable, + extensions: extensions$4, + filenames: filenames$1, + languageId: languageId$4 +}; + +var _JSON$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$6, + type: type$4, + tmScope: tmScope$4, + aceMode: aceMode$4, + codemirrorMode: codemirrorMode$4, + codemirrorMimeType: codemirrorMimeType$4, + searchable: searchable, + extensions: extensions$4, + filenames: filenames$1, + languageId: languageId$4, + 'default': _JSON +}); + +var name$7 = "JSON with Comments"; +var type$5 = "data"; +var group$a = "JSON"; +var tmScope$5 = "source.js"; +var aceMode$5 = "javascript"; +var codemirrorMode$5 = "javascript"; +var codemirrorMimeType$5 = "text/javascript"; +var aliases$2 = [ + "jsonc" +]; +var extensions$5 = [ + ".jsonc", + ".sublime-build", + ".sublime-commands", + ".sublime-completions", + ".sublime-keymap", + ".sublime-macro", + ".sublime-menu", + ".sublime-mousemap", + ".sublime-project", + ".sublime-settings", + ".sublime-theme", + ".sublime-workspace", + ".sublime_metrics", + ".sublime_session" +]; +var filenames$2 = [ + ".babelrc", + ".eslintrc.json", + ".jscsrc", + ".jshintrc", + ".jslintrc", + "jsconfig.json", + "language-configuration.json", + "tsconfig.json" +]; +var languageId$5 = 423; +var JSON_with_Comments = { + name: name$7, + type: type$5, + group: group$a, + tmScope: tmScope$5, + aceMode: aceMode$5, + codemirrorMode: codemirrorMode$5, + codemirrorMimeType: codemirrorMimeType$5, + aliases: aliases$2, + extensions: extensions$5, + filenames: filenames$2, + languageId: languageId$5 +}; + +var JSON_with_Comments$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$7, + type: type$5, + group: group$a, + tmScope: tmScope$5, + aceMode: aceMode$5, + codemirrorMode: codemirrorMode$5, + codemirrorMimeType: codemirrorMimeType$5, + aliases: aliases$2, + extensions: extensions$5, + filenames: filenames$2, + languageId: languageId$5, + 'default': JSON_with_Comments +}); + +var name$8 = "JSON5"; +var type$6 = "data"; +var extensions$6 = [ + ".json5" +]; +var tmScope$6 = "source.js"; +var aceMode$6 = "javascript"; +var codemirrorMode$6 = "javascript"; +var codemirrorMimeType$6 = "application/json"; +var languageId$6 = 175; +var JSON5$1 = { + name: name$8, + type: type$6, + extensions: extensions$6, + tmScope: tmScope$6, + aceMode: aceMode$6, + codemirrorMode: codemirrorMode$6, + codemirrorMimeType: codemirrorMimeType$6, + languageId: languageId$6 +}; + +var JSON5$2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$8, + type: type$6, + extensions: extensions$6, + tmScope: tmScope$6, + aceMode: aceMode$6, + codemirrorMode: codemirrorMode$6, + codemirrorMimeType: codemirrorMimeType$6, + languageId: languageId$6, + 'default': JSON5$1 +}); + +var require$$0$2 = getCjsExportFromNamespace(JavaScript$1); + +var require$$1 = getCjsExportFromNamespace(JSX$1); + +var require$$2 = getCjsExportFromNamespace(TypeScript$1); + +var require$$3 = getCjsExportFromNamespace(TSX$1); + +var require$$4$1 = getCjsExportFromNamespace(_JSON$1); + +var require$$5 = getCjsExportFromNamespace(JSON_with_Comments$1); + +var require$$6 = getCjsExportFromNamespace(JSON5$2); + +const languages = [createLanguage(require$$0$2, data => ({ + since: "0.0.0", + parsers: ["babel", "flow"], + vscodeLanguageIds: ["javascript", "mongo"], + interpreters: data.interpreters.concat(["nodejs"]) +})), createLanguage(require$$0$2, () => ({ + name: "Flow", + since: "0.0.0", + parsers: ["babel", "flow"], + vscodeLanguageIds: ["javascript"], + aliases: [], + filenames: [], + extensions: [".js.flow"] +})), createLanguage(require$$1, () => ({ + since: "0.0.0", + parsers: ["babel", "flow"], + vscodeLanguageIds: ["javascriptreact"] +})), createLanguage(require$$2, () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescript"] +})), createLanguage(require$$3, () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescriptreact"] +})), createLanguage(require$$4$1, () => ({ + name: "JSON.stringify", + since: "1.13.0", + parsers: ["json-stringify"], + vscodeLanguageIds: ["json"], + extensions: [], + // .json file defaults to json instead of json-stringify + filenames: ["package.json", "package-lock.json", "composer.json"] +})), createLanguage(require$$4$1, data => ({ + since: "1.5.0", + parsers: ["json"], + vscodeLanguageIds: ["json"], + filenames: data.filenames.concat([".prettierrc"]) +})), createLanguage(require$$5, data => ({ + since: "1.5.0", + parsers: ["json"], + vscodeLanguageIds: ["jsonc"], + filenames: data.filenames.concat([".eslintrc"]) +})), createLanguage(require$$6, () => ({ + since: "1.13.0", + parsers: ["json5"], + vscodeLanguageIds: ["json5"] +}))]; +const printers = { + estree: printerEstree, + "estree-json": printerEstreeJson +}; +const parsers = { + // JS - Babel + get babel() { + return require("./parser-babel").parsers.babel; + }, + + get "babel-flow"() { + return require("./parser-babel").parsers["babel-flow"]; + }, + + get "babel-ts"() { + return require("./parser-babel").parsers["babel-ts"]; + }, + + get json() { + return require("./parser-babel").parsers.json; + }, + + get json5() { + return require("./parser-babel").parsers.json5; + }, + + get "json-stringify"() { + return require("./parser-babel").parsers["json-stringify"]; + }, + + get __js_expression() { + return require("./parser-babel").parsers.__js_expression; + }, + + get __vue_expression() { + return require("./parser-babel").parsers.__vue_expression; + }, + + get __vue_event_binding() { + return require("./parser-babel").parsers.__vue_event_binding; + }, + + // JS - Flow + get flow() { + return require("./parser-flow").parsers.flow; + }, + + // JS - TypeScript + get typescript() { + return require("./parser-typescript").parsers.typescript; + }, + + // JS - Angular Action + get __ng_action() { + return require("./parser-angular").parsers.__ng_action; + }, + + // JS - Angular Binding + get __ng_binding() { + return require("./parser-angular").parsers.__ng_binding; + }, + + // JS - Angular Interpolation + get __ng_interpolation() { + return require("./parser-angular").parsers.__ng_interpolation; + }, + + // JS - Angular Directive + get __ng_directive() { + return require("./parser-angular").parsers.__ng_directive; + } + +}; +var languageJs = { + languages, + options: options$2, + printers, + parsers +}; + +const { + isFrontMatterNode: isFrontMatterNode$1 +} = util; + +function clean$2(ast, newObj, parent) { + ["raw", // front-matter + "raws", "sourceIndex", "source", "before", "after", "trailingComma"].forEach(name => { + delete newObj[name]; + }); + + if (isFrontMatterNode$1(ast) && ast.lang === "yaml") { + delete newObj.value; + } + + if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length !== 0) { + // --insert-pragma + // first non-front-matter comment + if (parent.nodes[0] === ast || isFrontMatterNode$1(parent.nodes[0]) && parent.nodes[1] === ast) { + /** + * something + * + * @format + */ + delete newObj.text; // standalone pragma + + if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) { + return null; + } + } // Last comment is not parsed, when omitting semicolon, #8675 + + + if (parent.type === "css-root" && getLast(parent.nodes) === ast) { + return null; + } + } + + if (ast.type === "value-root") { + delete newObj.text; + } + + if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") { + delete newObj.value; + } + + if (ast.type === "css-rule") { + delete newObj.params; + } + + if (ast.type === "selector-combinator") { + newObj.value = newObj.value.replace(/\s+/g, " "); + } + + if (ast.type === "media-feature") { + newObj.value = newObj.value.replace(/ /g, ""); + } + + if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].includes(newObj.value.replace().toLowerCase())) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") { + newObj.value = newObj.value.toLowerCase(); + } + + if (ast.type === "css-decl") { + newObj.prop = newObj.prop.toLowerCase(); + } + + if (ast.type === "css-atrule" || ast.type === "css-import") { + newObj.name = newObj.name.toLowerCase(); + } + + if (ast.type === "value-number") { + newObj.unit = newObj.unit.toLowerCase(); + } + + if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) { + newObj.value = cleanCSSStrings(newObj.value); + } + + if (ast.type === "selector-attribute") { + newObj.attribute = newObj.attribute.trim(); + + if (newObj.namespace) { + if (typeof newObj.namespace === "string") { + newObj.namespace = newObj.namespace.trim(); + + if (newObj.namespace.length === 0) { + newObj.namespace = true; + } + } + } + + if (newObj.value) { + newObj.value = newObj.value.trim().replace(/^["']|["']$/g, ""); + delete newObj.quoted; + } + } + + if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) { + newObj.value = newObj.value.replace(/([\d+.Ee-]+)([A-Za-z]*)/g, (match, numStr, unit) => { + const num = Number(numStr); + return isNaN(num) ? match : num + unit.toLowerCase(); + }); + } + + if (ast.type === "selector-tag") { + const lowercasedValue = ast.value.toLowerCase(); + + if (["from", "to"].includes(lowercasedValue)) { + newObj.value = lowercasedValue; + } + } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func` + + + if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") { + delete newObj.value; + } // Workaround for SCSS nested properties + + + if (ast.type === "selector-unknown") { + delete newObj.value; + } +} + +function cleanCSSStrings(value) { + return value.replace(/'/g, '"').replace(/\\([^\dA-Fa-f])/g, "$1"); +} + +var clean_1$1 = clean$2; + +const { + builders: { + hardline: hardline$8, + concat: concat$e, + markAsRoot: markAsRoot$1 + } +} = document; +const DELIMITER_MAP = { + "---": "yaml", + "+++": "toml" +}; + +function parse$7(text) { + const delimiterRegex = Object.keys(DELIMITER_MAP).map(escapeStringRegexp).join("|"); + const match = text.match( // trailing spaces after delimiters are allowed + new RegExp(`^(${delimiterRegex})([^\\n]*)\\n(?:([\\s\\S]*?)\\n)?\\1[^\\n\\S]*(\\n|$)`)); + + if (match === null) { + return { + frontMatter: null, + content: text + }; + } + + const [raw, delimiter, language, value] = match; + let lang = DELIMITER_MAP[delimiter]; + + if (lang !== "toml" && language && language.trim()) { + lang = language.trim(); + } + + return { + frontMatter: { + type: "front-matter", + lang, + value, + raw: raw.replace(/\n$/, "") + }, + content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length) + }; +} + +function print$1(node, textToDoc) { + if (node.lang === "yaml") { + const value = node.value.trim(); + const doc = value ? textToDoc(value, { + parser: "yaml" + }, { + stripTrailingHardline: true + }) : ""; + return markAsRoot$1(concat$e(["---", hardline$8, doc, doc ? hardline$8 : "", "---"])); + } +} + +var frontMatter = { + parse: parse$7, + print: print$1 +}; + +const { + builders: { + hardline: hardline$9, + concat: concat$f + } +} = document; +const { + print: printFrontMatter +} = frontMatter; + +function embed$1(path, print, textToDoc +/*, options */ +) { + const node = path.getValue(); + + if (node.type === "front-matter") { + const doc = printFrontMatter(node, textToDoc); + return doc ? concat$f([doc, hardline$9]) : ""; + } +} + +var embed_1$1 = embed$1; + +const { + parse: parseFrontMatter +} = frontMatter; + +function hasPragma$1(text) { + return pragma.hasPragma(parseFrontMatter(text).content); +} + +function insertPragma$2(text) { + const { + frontMatter, + content + } = parseFrontMatter(text); + return (frontMatter ? frontMatter.raw + "\n\n" : "") + pragma.insertPragma(content); +} + +var pragma$1 = { + hasPragma: hasPragma$1, + insertPragma: insertPragma$2 +}; + +const colorAdjusterFunctions = new Set(["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"]); + +function getAncestorCounter(path, typeOrTypes) { + const types = [].concat(typeOrTypes); + let counter = -1; + let ancestorNode; + + while (ancestorNode = path.getParentNode(++counter)) { + if (types.includes(ancestorNode.type)) { + return counter; + } + } + + return -1; +} + +function getAncestorNode(path, typeOrTypes) { + const counter = getAncestorCounter(path, typeOrTypes); + return counter === -1 ? null : path.getParentNode(counter); +} + +function getPropOfDeclNode(path) { + const declAncestorNode = getAncestorNode(path, "css-decl"); + return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase(); +} + +function hasSCSSInterpolation(groupList) { + if (groupList && groupList.length) { + for (let i = groupList.length - 1; i > 0; i--) { + // If we find `#{`, return true. + if (groupList[i].type === "word" && groupList[i].value === "{" && groupList[i - 1].type === "word" && groupList[i - 1].value.endsWith("#")) { + return true; + } + } + } + + return false; +} + +function hasStringOrFunction(groupList) { + if (groupList && groupList.length) { + for (let i = 0; i < groupList.length; i++) { + if (groupList[i].type === "string" || groupList[i].type === "func") { + return true; + } + } + } + + return false; +} + +function isSCSS(parser, text) { + const hasExplicitParserChoice = parser === "less" || parser === "scss"; + const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^:}]+|#){|@import[^\n]+(?:url|,)/; + return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text); +} + +function isSCSSVariable(node) { + return !!(node && node.type === "word" && node.value.startsWith("$")); +} + +function isWideKeywords(value) { + return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase()); +} + +function isKeyframeAtRuleKeywords(path, value) { + const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); + return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase()); +} + +function maybeToLowerCase(value) { + return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase(); +} + +function insideValueFunctionNode(path, functionName) { + const funcAncestorNode = getAncestorNode(path, "value-func"); + return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName; +} + +function insideICSSRuleNode(path) { + const ruleAncestorNode = getAncestorNode(path, "css-rule"); + return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export")); +} + +function insideAtRuleNode(path, atRuleNameOrAtRuleNames) { + const atRuleNames = [].concat(atRuleNameOrAtRuleNames); + const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); + return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase()); +} + +function insideURLFunctionInImportAtRuleNode(path) { + const node = path.getValue(); + const atRuleAncestorNode = getAncestorNode(path, "css-atrule"); + return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2; +} + +function isURLFunctionNode(node) { + return node.type === "value-func" && node.value.toLowerCase() === "url"; +} + +function isLastNode(path, node) { + const parentNode = path.getParentNode(); + /* istanbul ignore next */ + + if (!parentNode) { + return false; + } + + const { + nodes + } = parentNode; + return nodes && nodes.indexOf(node) === nodes.length - 1; +} + +function isDetachedRulesetDeclarationNode(node) { + // If a Less file ends up being parsed with the SCSS parser, Less + // variable declarations will be parsed as atrules with names ending + // with a colon, so keep the original case then. + + /* istanbul ignore next */ + if (!node.selector) { + return false; + } + + return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value); +} + +function isForKeywordNode(node) { + return node.type === "value-word" && ["from", "through", "end"].includes(node.value); +} + +function isIfElseKeywordNode(node) { + return node.type === "value-word" && ["and", "or", "not"].includes(node.value); +} + +function isEachKeywordNode(node) { + return node.type === "value-word" && node.value === "in"; +} + +function isMultiplicationNode(node) { + return node.type === "value-operator" && node.value === "*"; +} + +function isDivisionNode(node) { + return node.type === "value-operator" && node.value === "/"; +} + +function isAdditionNode(node) { + return node.type === "value-operator" && node.value === "+"; +} + +function isSubtractionNode(node) { + return node.type === "value-operator" && node.value === "-"; +} + +function isModuloNode(node) { + return node.type === "value-operator" && node.value === "%"; +} + +function isMathOperatorNode(node) { + return isMultiplicationNode(node) || isDivisionNode(node) || isAdditionNode(node) || isSubtractionNode(node) || isModuloNode(node); +} + +function isEqualityOperatorNode(node) { + return node.type === "value-word" && ["==", "!="].includes(node.value); +} + +function isRelationalOperatorNode(node) { + return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value); +} + +function isSCSSControlDirectiveNode(node) { + return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name); +} + +function isSCSSNestedPropertyNode(node) { + /* istanbul ignore next */ + if (!node.selector) { + return false; + } + + return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":"); +} + +function isDetachedRulesetCallNode(node) { + return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params); +} + +function isTemplatePlaceholderNode(node) { + return node.name.startsWith("prettier-placeholder"); +} + +function isTemplatePropNode(node) { + return node.prop.startsWith("@prettier-placeholder"); +} + +function isPostcssSimpleVarNode(currentNode, nextNode) { + return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before; +} + +function hasComposesNode(node) { + return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes"; +} + +function hasParensAroundNode(node) { + return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null; +} + +function hasEmptyRawBefore(node) { + return node.raws && node.raws.before === ""; +} + +function isKeyValuePairNode(node) { + return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon"; +} + +function isKeyValuePairInParenGroupNode(node) { + return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode(node.groups[0]); +} + +function isSCSSMapItemNode(path) { + const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`) + + if (node.groups.length === 0) { + return false; + } + + const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`) + + if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) { + return false; + } + + const declNode = getAncestorNode(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`) + + if (declNode && declNode.prop && declNode.prop.startsWith("$")) { + return true; + } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`) + + + if (isKeyValuePairInParenGroupNode(parentParentNode)) { + return true; + } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`) + + + if (parentParentNode.type === "value-func") { + return true; + } + + return false; +} + +function isInlineValueCommentNode(node) { + return node.type === "value-comment" && node.inline; +} + +function isHashNode(node) { + return node.type === "value-word" && node.value === "#"; +} + +function isLeftCurlyBraceNode(node) { + return node.type === "value-word" && node.value === "{"; +} + +function isRightCurlyBraceNode(node) { + return node.type === "value-word" && node.value === "}"; +} + +function isWordNode(node) { + return ["value-word", "value-atword"].includes(node.type); +} + +function isColonNode(node) { + return node.type === "value-colon"; +} + +function isMediaAndSupportsKeywords(node) { + return node.value && ["not", "and", "or"].includes(node.value.toLowerCase()); +} + +function isColorAdjusterFuncNode(node) { + if (node.type !== "value-func") { + return false; + } + + return colorAdjusterFunctions.has(node.value.toLowerCase()); +} // TODO: only check `less` when we don't use `less` to parse `css` + + +function isLessParser(options) { + return options.parser === "css" || options.parser === "less"; +} + +function lastLineHasInlineComment(text) { + return /\/\//.test(text.split(/[\n\r]/).pop()); +} + +function stringifyNode(node) { + if (node.groups) { + const open = node.open && node.open.value ? node.open.value : ""; + const groups = node.groups.reduce((previousValue, currentValue, index) => { + return previousValue + stringifyNode(currentValue) + (node.groups[0].type === "comma_group" && index !== node.groups.length - 1 ? "," : ""); + }, ""); + const close = node.close && node.close.value ? node.close.value : ""; + return open + groups + close; + } + + const before = node.raws && node.raws.before ? node.raws.before : ""; + const quote = node.raws && node.raws.quote ? node.raws.quote : ""; + const atword = node.type === "atword" ? "@" : ""; + const value = node.value ? node.value : ""; + const unit = node.unit ? node.unit : ""; + const group = node.group ? stringifyNode(node.group) : ""; + const after = node.raws && node.raws.after ? node.raws.after : ""; + return before + quote + atword + value + quote + unit + group + after; +} + +var utils$7 = { + getAncestorCounter, + getAncestorNode, + getPropOfDeclNode, + hasSCSSInterpolation, + hasStringOrFunction, + maybeToLowerCase, + insideValueFunctionNode, + insideICSSRuleNode, + insideAtRuleNode, + insideURLFunctionInImportAtRuleNode, + isKeyframeAtRuleKeywords, + isWideKeywords, + isSCSS, + isSCSSVariable, + isLastNode, + isLessParser, + isSCSSControlDirectiveNode, + isDetachedRulesetDeclarationNode, + isRelationalOperatorNode, + isEqualityOperatorNode, + isMultiplicationNode, + isDivisionNode, + isAdditionNode, + isSubtractionNode, + isModuloNode, + isMathOperatorNode, + isEachKeywordNode, + isForKeywordNode, + isURLFunctionNode, + isIfElseKeywordNode, + hasComposesNode, + hasParensAroundNode, + hasEmptyRawBefore, + isSCSSNestedPropertyNode, + isDetachedRulesetCallNode, + isTemplatePlaceholderNode, + isTemplatePropNode, + isPostcssSimpleVarNode, + isKeyValuePairNode, + isKeyValuePairInParenGroupNode, + isSCSSMapItemNode, + isInlineValueCommentNode, + isHashNode, + isLeftCurlyBraceNode, + isRightCurlyBraceNode, + isWordNode, + isColonNode, + isMediaAndSupportsKeywords, + isColorAdjusterFuncNode, + lastLineHasInlineComment, + stringifyNode +}; + +const { + printNumber: printNumber$2, + printString: printString$2, + hasIgnoreComment: hasIgnoreComment$3, + hasNewline: hasNewline$6, + isFrontMatterNode: isFrontMatterNode$2, + isNextLineEmpty: isNextLineEmpty$5 +} = util; +const { + builders: { + concat: concat$g, + join: join$8, + line: line$9, + hardline: hardline$a, + softline: softline$7, + group: group$b, + fill: fill$4, + indent: indent$a, + dedent: dedent$2, + ifBreak: ifBreak$5, + breakParent: breakParent$5 + }, + utils: { + removeLines: removeLines$2 + } +} = document; +const { + insertPragma: insertPragma$3 +} = pragma$1; +const { + getAncestorNode: getAncestorNode$1, + getPropOfDeclNode: getPropOfDeclNode$1, + maybeToLowerCase: maybeToLowerCase$1, + insideValueFunctionNode: insideValueFunctionNode$1, + insideICSSRuleNode: insideICSSRuleNode$1, + insideAtRuleNode: insideAtRuleNode$1, + insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1, + isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1, + isWideKeywords: isWideKeywords$1, + isSCSS: isSCSS$1, + isLastNode: isLastNode$1, + isLessParser: isLessParser$1, + isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1, + isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1, + isRelationalOperatorNode: isRelationalOperatorNode$1, + isEqualityOperatorNode: isEqualityOperatorNode$1, + isMultiplicationNode: isMultiplicationNode$1, + isDivisionNode: isDivisionNode$1, + isAdditionNode: isAdditionNode$1, + isSubtractionNode: isSubtractionNode$1, + isMathOperatorNode: isMathOperatorNode$1, + isEachKeywordNode: isEachKeywordNode$1, + isForKeywordNode: isForKeywordNode$1, + isURLFunctionNode: isURLFunctionNode$1, + isIfElseKeywordNode: isIfElseKeywordNode$1, + hasComposesNode: hasComposesNode$1, + hasParensAroundNode: hasParensAroundNode$1, + hasEmptyRawBefore: hasEmptyRawBefore$1, + isKeyValuePairNode: isKeyValuePairNode$1, + isDetachedRulesetCallNode: isDetachedRulesetCallNode$1, + isTemplatePlaceholderNode: isTemplatePlaceholderNode$1, + isTemplatePropNode: isTemplatePropNode$1, + isPostcssSimpleVarNode: isPostcssSimpleVarNode$1, + isSCSSMapItemNode: isSCSSMapItemNode$1, + isInlineValueCommentNode: isInlineValueCommentNode$1, + isHashNode: isHashNode$1, + isLeftCurlyBraceNode: isLeftCurlyBraceNode$1, + isRightCurlyBraceNode: isRightCurlyBraceNode$1, + isWordNode: isWordNode$1, + isColonNode: isColonNode$1, + isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1, + isColorAdjusterFuncNode: isColorAdjusterFuncNode$1, + lastLineHasInlineComment: lastLineHasInlineComment$1 +} = utils$7; + +function shouldPrintComma$4(options) { + return options.trailingComma === "es5" || options.trailingComma === "all"; +} + +function genericPrint$2(path, options, print) { + const node = path.getValue(); + /* istanbul ignore if */ + + if (!node) { + return ""; + } + + if (typeof node === "string") { + return node; + } + + switch (node.type) { + case "front-matter": + return concat$g([node.raw, hardline$a]); + + case "css-root": + { + const nodes = printNodeSequence(path, options, print); + const after = node.raws.after.trim(); + return concat$g([nodes, after ? ` ${after}` : "", nodes.parts.length && !options.__isHTMLStyleAttribute ? hardline$a : ""]); + } + + case "css-comment": + { + const isInlineComment = node.inline || node.raws.inline; + const text = options.originalText.slice(options.locStart(node), options.locEnd(node)); + return isInlineComment ? text.trimEnd() : text; + } + + case "css-rule": + { + return concat$g([path.call(print, "selector"), node.important ? " !important" : "", node.nodes ? concat$g([node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment$1(node.selector.value) ? line$9 : " ", "{", node.nodes.length > 0 ? indent$a(concat$g([hardline$a, printNodeSequence(path, options, print)])) : "", hardline$a, "}", isDetachedRulesetDeclarationNode$1(node) ? ";" : ""]) : ";"]); + } + + case "css-decl": + { + const parentNode = path.getParentNode(); + const { + between: rawBetween + } = node.raws; + const trimmedBetween = rawBetween.trim(); + const isColon = trimmedBetween === ":"; + let value = hasComposesNode$1(node) ? removeLines$2(path.call(print, "value")) : path.call(print, "value"); + + if (!isColon && lastLineHasInlineComment$1(trimmedBetween)) { + value = indent$a(concat$g([hardline$a, dedent$2(value)])); + } + + return concat$g([node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode$1(path) ? node.prop : maybeToLowerCase$1(node.prop), trimmedBetween.startsWith("//") ? " " : "", trimmedBetween, node.extend ? "" : " ", isLessParser$1(options) && node.extend && node.selector ? concat$g(["extend(", path.call(print, "selector"), ")"]) : "", value, node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? concat$g([" {", indent$a(concat$g([softline$7, printNodeSequence(path, options, print)])), softline$7, "}"]) : isTemplatePropNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";" ? "" : options.__isHTMLStyleAttribute && isLastNode$1(path, node) ? ifBreak$5(";", "") : ";"]); + } + + case "css-atrule": + { + const parentNode = path.getParentNode(); + const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode$1(node) && !parentNode.raws.semicolon && options.originalText[options.locEnd(node) - 1] !== ";"; + + if (isLessParser$1(options)) { + if (node.mixin) { + return concat$g([path.call(print, "selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); + } + + if (node.function) { + return concat$g([node.name, concat$g([path.call(print, "params")]), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); + } + + if (node.variable) { + return concat$g(["@", node.name, ": ", node.value ? concat$g([path.call(print, "value")]) : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? concat$g(["{", indent$a(concat$g([node.nodes.length > 0 ? softline$7 : "", printNodeSequence(path, options, print)])), softline$7, "}"]) : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); + } + } + + return concat$g(["@", // If a Less file ends up being parsed with the SCSS parser, Less + // variable declarations will be parsed as at-rules with names ending + // with a colon, so keep the original case then. + isDetachedRulesetCallNode$1(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase$1(node.name), node.params ? concat$g([isDetachedRulesetCallNode$1(node) ? "" : isTemplatePlaceholderNode$1(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? concat$g([hardline$a, hardline$a]) : /^\s*\n/.test(node.raws.afterName) ? hardline$a : " " : " ", path.call(print, "params")]) : "", node.selector ? indent$a(concat$g([" ", path.call(print, "selector")])) : "", node.value ? group$b(concat$g([" ", path.call(print, "value"), isSCSSControlDirectiveNode$1(node) ? hasParensAroundNode$1(node) ? " " : line$9 : ""])) : node.name === "else" ? " " : "", node.nodes ? concat$g([isSCSSControlDirectiveNode$1(node) ? "" : node.selector && !node.selector.nodes && typeof node.selector.value === "string" && lastLineHasInlineComment$1(node.selector.value) || !node.selector && typeof node.params === "string" && lastLineHasInlineComment$1(node.params) ? line$9 : " ", "{", indent$a(concat$g([node.nodes.length > 0 ? softline$7 : "", printNodeSequence(path, options, print)])), softline$7, "}"]) : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]); + } + // postcss-media-query-parser + + case "media-query-list": + { + const parts = []; + path.each(childPath => { + const node = childPath.getValue(); + + if (node.type === "media-query" && node.value === "") { + return; + } + + parts.push(childPath.call(print)); + }, "nodes"); + return group$b(indent$a(join$8(line$9, parts))); + } + + case "media-query": + { + return concat$g([join$8(" ", path.map(print, "nodes")), isLastNode$1(path, node) ? "" : ","]); + } + + case "media-type": + { + return adjustNumbers(adjustStrings(node.value, options)); + } + + case "media-feature-expression": + { + if (!node.nodes) { + return node.value; + } + + return concat$g(["(", concat$g(path.map(print, "nodes")), ")"]); + } + + case "media-feature": + { + return maybeToLowerCase$1(adjustStrings(node.value.replace(/ +/g, " "), options)); + } + + case "media-colon": + { + return concat$g([node.value, " "]); + } + + case "media-value": + { + return adjustNumbers(adjustStrings(node.value, options)); + } + + case "media-keyword": + { + return adjustStrings(node.value, options); + } + + case "media-url": + { + return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/gi, ")"), options); + } + + case "media-unknown": + { + return node.value; + } + // postcss-selector-parser + + case "selector-root": + { + return group$b(concat$g([insideAtRuleNode$1(path, "custom-selector") ? concat$g([getAncestorNode$1(path, "css-atrule").customSelector, line$9]) : "", join$8(concat$g([",", insideAtRuleNode$1(path, ["extend", "custom-selector", "nest"]) ? line$9 : hardline$a]), path.map(print, "nodes"))])); + } + + case "selector-selector": + { + return group$b(indent$a(concat$g(path.map(print, "nodes")))); + } + + case "selector-comment": + { + return node.value; + } + + case "selector-string": + { + return adjustStrings(node.value, options); + } + + case "selector-tag": + { + const parentNode = path.getParentNode(); + const index = parentNode && parentNode.nodes.indexOf(node); + const prevNode = index && parentNode.nodes[index - 1]; + return concat$g([node.namespace ? concat$g([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords$1(path, node.value) ? node.value.toLowerCase() : node.value)]); + } + + case "selector-id": + { + return concat$g(["#", node.value]); + } + + case "selector-class": + { + return concat$g([".", adjustNumbers(adjustStrings(node.value, options))]); + } + + case "selector-attribute": + { + return concat$g(["[", node.namespace ? concat$g([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]); + } + + case "selector-combinator": + { + if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") { + const parentNode = path.getParentNode(); + const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$9; + return concat$g([leading, node.value, isLastNode$1(path, node) ? "" : " "]); + } + + const leading = node.value.trim().startsWith("(") ? line$9 : ""; + const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$9; + return concat$g([leading, value]); + } + + case "selector-universal": + { + return concat$g([node.namespace ? concat$g([node.namespace === true ? "" : node.namespace.trim(), "|"]) : "", node.value]); + } + + case "selector-pseudo": + { + return concat$g([maybeToLowerCase$1(node.value), node.nodes && node.nodes.length > 0 ? concat$g(["(", join$8(", ", path.map(print, "nodes")), ")"]) : ""]); + } + + case "selector-nesting": + { + return node.value; + } + + case "selector-unknown": + { + const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property + + if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) { + return adjustNumbers(adjustStrings(maybeToLowerCase$1(node.value), options)); + } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js + + + const parentNode = path.getParentNode(); + + if (parentNode.raws && parentNode.raws.selector) { + const start = options.locStart(parentNode); + const end = start + parentNode.raws.selector.length; + return options.originalText.slice(start, end).trim(); + } // Same reason above + + + const grandParent = path.getParentNode(1); + + if (parentNode.type === "value-paren_group" && grandParent && grandParent.type === "value-func" && grandParent.value === "selector") { + const start = options.locStart(parentNode.open) + 1; + const end = options.locEnd(parentNode.close) - 1; + const selector = options.originalText.slice(start, end).trim(); + return lastLineHasInlineComment$1(selector) ? concat$g([breakParent$5, selector]) : selector; + } + + return node.value; + } + // postcss-values-parser + + case "value-value": + case "value-root": + { + return path.call(print, "group"); + } + + case "value-comment": + { + return options.originalText.slice(options.locStart(node), options.locEnd(node)); + } + + case "value-comma_group": + { + const parentNode = path.getParentNode(); + const parentParentNode = path.getParentNode(1); + const declAncestorProp = getPropOfDeclNode$1(path); + const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template")); + const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); + const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode$1(atRuleAncestorNode); + const printed = path.map(print, "groups"); + const parts = []; + const insideURLFunction = insideValueFunctionNode$1(path, "url"); + let insideSCSSInterpolationInString = false; + let didBreak = false; + + for (let i = 0; i < node.groups.length; ++i) { + parts.push(printed[i]); + const iPrevNode = node.groups[i - 1]; + const iNode = node.groups[i]; + const iNextNode = node.groups[i + 1]; + const iNextNextNode = node.groups[i + 2]; + + if (insideURLFunction) { + if (iNextNode && isAdditionNode$1(iNextNode) || isAdditionNode$1(iNode)) { + parts.push(" "); + } + + continue; + } // Ignore after latest node (i.e. before semicolon) + + + if (!iNextNode) { + continue; + } // styled.div` background: var(--${one}); ` + + + if (iNode.type === "value-word" && iNode.value.endsWith("-") && iNextNode.type === "value-atword" && iNextNode.value.startsWith("prettier-placeholder-")) { + continue; + } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`) + + + const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{"); + const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}"); + + if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) { + insideSCSSInterpolationInString = !insideSCSSInterpolationInString; + continue; + } + + if (insideSCSSInterpolationInString) { + continue; + } // Ignore colon (i.e. `:`) + + + if (isColonNode$1(iNode) || isColonNode$1(iNextNode)) { + continue; + } // Ignore `@` in Less (i.e. `@@var;`) + + + if (iNode.type === "value-atword" && iNode.value === "") { + continue; + } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`) + + + if (iNode.value === "~") { + continue; + } // Ignore escape `\` + + + if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") { + continue; + } // Ignore escaped `/` + + + if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") { + continue; + } // Ignore `\` (i.e. `$variable: \@small;`) + + + if (iNode.value === "\\") { + continue; + } // Ignore `$$` (i.e. `background-color: $$(style)Color;`) + + + if (isPostcssSimpleVarNode$1(iNode, iNextNode)) { + continue; + } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`) + + + if (isHashNode$1(iNode) || isLeftCurlyBraceNode$1(iNode) || isRightCurlyBraceNode$1(iNextNode) || isLeftCurlyBraceNode$1(iNextNode) && hasEmptyRawBefore$1(iNextNode) || isRightCurlyBraceNode$1(iNode) && hasEmptyRawBefore$1(iNextNode)) { + continue; + } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`) + + + if (iNode.value === "--" && isHashNode$1(iNextNode)) { + continue; + } // Formatting math operations + + + const isMathOperator = isMathOperatorNode$1(iNode); + const isNextMathOperator = isMathOperatorNode$1(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is + // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`) + // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`) + + if ((isMathOperator && isHashNode$1(iNextNode) || isNextMathOperator && isRightCurlyBraceNode$1(iNode)) && hasEmptyRawBefore$1(iNextNode)) { + continue; + } // Print spaces before and after addition and subtraction math operators as is in `calc` function + // due to the fact that it is not valid syntax + // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`) + + + if (insideValueFunctionNode$1(path, "calc") && (isAdditionNode$1(iNode) || isAdditionNode$1(iNextNode) || isSubtractionNode$1(iNode) || isSubtractionNode$1(iNextNode)) && hasEmptyRawBefore$1(iNextNode)) { + continue; + } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`) + // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is. + + + const isColorAdjusterNode = (isAdditionNode$1(iNode) || isSubtractionNode$1(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode$1(parentParentNode) && !hasEmptyRawBefore$1(iNextNode); + const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode$1(iNextNextNode) || iNode.type === "value-func" || isWordNode$1(iNode); + const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode$1(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode$1(iPrevNode); // Formatting `/`, `+`, `-` sign + + if (!(isMultiplicationNode$1(iNextNode) || isMultiplicationNode$1(iNode)) && !insideValueFunctionNode$1(path, "calc") && !isColorAdjusterNode && (isDivisionNode$1(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode$1(iNode) && !requireSpaceAfterOperator || isAdditionNode$1(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode$1(iNode) && !requireSpaceAfterOperator || isSubtractionNode$1(iNextNode) || isSubtractionNode$1(iNode)) && (hasEmptyRawBefore$1(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode$1(iPrevNode)))) { + continue; + } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`) + + + if (isInlineValueCommentNode$1(iNode)) { + if (parentNode.type === "value-paren_group") { + parts.push(dedent$2(hardline$a)); + continue; + } + + parts.push(hardline$a); + continue; + } // Handle keywords in SCSS control directive + + + if (isControlDirective && (isEqualityOperatorNode$1(iNextNode) || isRelationalOperatorNode$1(iNextNode) || isIfElseKeywordNode$1(iNextNode) || isEachKeywordNode$1(iNode) || isForKeywordNode$1(iNode))) { + parts.push(" "); + continue; + } // At-rule `namespace` should be in one line + + + if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") { + parts.push(" "); + continue; + } // Formatting `grid` property + + + if (isGridValue) { + if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) { + parts.push(hardline$a); + didBreak = true; + } else { + parts.push(" "); + } + + continue; + } // Add `space` before next math operation + // Note: `grip` property have `/` delimiter and it is not math operation, so + // `grid` property handles above + + + if (isNextMathOperator) { + parts.push(" "); + continue; + } // allow function(returns-list($list)...) + + + if (iNextNode && iNextNode.value === "...") { + continue; + } // Be default all values go through `line` + + + parts.push(line$9); + } + + if (didBreak) { + parts.unshift(hardline$a); + } + + if (isControlDirective) { + return group$b(indent$a(concat$g(parts))); + } // Indent is not needed for import url when url is very long + // and node has two groups + // when type is value-comma_group + // example @import url("verylongurl") projection,tv + + + if (insideURLFunctionInImportAtRuleNode$1(path)) { + return group$b(fill$4(parts)); + } + + return group$b(indent$a(fill$4(parts))); + } + + case "value-paren_group": + { + const parentNode = path.getParentNode(); + + if (parentNode && isURLFunctionNode$1(parentNode) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) { + return concat$g([node.open ? path.call(print, "open") : "", join$8(",", path.map(print, "groups")), node.close ? path.call(print, "close") : ""]); + } + + if (!node.open) { + const printed = path.map(print, "groups"); + const res = []; + + for (let i = 0; i < printed.length; i++) { + if (i !== 0) { + res.push(concat$g([",", line$9])); + } + + res.push(printed[i]); + } + + return group$b(indent$a(fill$4(res))); + } + + const isSCSSMapItem = isSCSSMapItemNode$1(path); + const lastItem = node.groups[node.groups.length - 1]; + const isLastItemComment = lastItem && lastItem.type === "value-comment"; + return group$b(concat$g([node.open ? path.call(print, "open") : "", indent$a(concat$g([softline$7, join$8(concat$g([",", line$9]), path.map(childPath => { + const node = childPath.getValue(); + const printed = print(childPath); // Key/Value pair in open paren already indented + + if (isKeyValuePairNode$1(node) && node.type === "value-comma_group" && node.groups && node.groups[2] && node.groups[2].type === "value-paren_group") { + printed.contents.contents.parts[1] = group$b(printed.contents.contents.parts[1]); + return group$b(dedent$2(printed)); + } + + return printed; + }, "groups"))])), ifBreak$5(!isLastItemComment && isSCSS$1(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma$4(options) ? "," : ""), softline$7, node.close ? path.call(print, "close") : ""]), { + shouldBreak: isSCSSMapItem + }); + } + + case "value-func": + { + return concat$g([node.value, insideAtRuleNode$1(path, "supports") && isMediaAndSupportsKeywords$1(node) ? " " : "", path.call(print, "group")]); + } + + case "value-paren": + { + return node.value; + } + + case "value-number": + { + return concat$g([printCssNumber(node.value), maybeToLowerCase$1(node.unit)]); + } + + case "value-operator": + { + return node.value; + } + + case "value-word": + { + if (node.isColor && node.isHex || isWideKeywords$1(node.value)) { + return node.value.toLowerCase(); + } + + return node.value; + } + + case "value-colon": + { + const parentNode = path.getParentNode(); + const index = parentNode && parentNode.groups.indexOf(node); + const prevNode = index && parentNode.groups[index - 1]; + return concat$g([node.value, // Don't add spaces on escaped colon `:`, e.g: grid-template-rows: [row-1-00\:00] auto; + prevNode && prevNode.value[prevNode.value.length - 1] === "\\" || // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`) + insideValueFunctionNode$1(path, "url") ? "" : line$9]); + } + // TODO: confirm this code is dead + + /* istanbul ignore next */ + + case "value-comma": + { + return concat$g([node.value, " "]); + } + + case "value-string": + { + return printString$2(node.raws.quote + node.value + node.raws.quote, options); + } + + case "value-atword": + { + return concat$g(["@", node.value]); + } + + case "value-unicode-range": + { + return node.value; + } + + case "value-unknown": + { + return node.value; + } + + default: + /* istanbul ignore next */ + throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`); + } +} + +function printNodeSequence(path, options, print) { + const node = path.getValue(); + const parts = []; + let i = 0; + path.map(pathChild => { + const prevNode = node.nodes[i - 1]; + + if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") { + const childNode = pathChild.getValue(); + parts.push(options.originalText.slice(options.locStart(childNode), options.locEnd(childNode))); + } else { + parts.push(pathChild.call(print)); + } + + if (i !== node.nodes.length - 1) { + if (node.nodes[i + 1].type === "css-comment" && !hasNewline$6(options.originalText, options.locStart(node.nodes[i + 1]), { + backwards: true + }) && !isFrontMatterNode$2(node.nodes[i]) || node.nodes[i + 1].type === "css-atrule" && node.nodes[i + 1].name === "else" && node.nodes[i].type !== "css-comment") { + parts.push(" "); + } else { + parts.push(options.__isHTMLStyleAttribute ? line$9 : hardline$a); + + if (isNextLineEmpty$5(options.originalText, pathChild.getValue(), options.locEnd) && !isFrontMatterNode$2(node.nodes[i])) { + parts.push(hardline$a); + } + } + } + + i++; + }, "nodes"); + return concat$g(parts); +} + +const STRING_REGEX$3 = /(["'])(?:(?!\1)[^\\]|\\[\S\s])*\1/g; +const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[Ee][+-]?\d+)?/g; +const STANDARD_UNIT_REGEX = /[A-Za-z]+/g; +const WORD_PART_REGEX = /[$@]?[A-Z_a-z\u0080-\uFFFF][\w\u0080-\uFFFF-]*/g; +const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX$3.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g"); + +function adjustStrings(value, options) { + return value.replace(STRING_REGEX$3, match => printString$2(match, options)); +} + +function quoteAttributeValue(value, options) { + const quote = options.singleQuote ? "'" : '"'; + return value.includes('"') || value.includes("'") ? value : quote + value + quote; +} + +function adjustNumbers(value) { + return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase$1(unit || "") : match); +} + +function printCssNumber(rawNumber) { + return printNumber$2(rawNumber) // Remove trailing `.0`. + .replace(/\.0(?=$|e)/, ""); +} + +var printerPostcss = { + print: genericPrint$2, + embed: embed_1$1, + insertPragma: insertPragma$3, + hasPrettierIgnore: hasIgnoreComment$3, + massageAstNode: clean_1$1 +}; + +var options$3 = { + singleQuote: commonOptions.singleQuote +}; + +var name$9 = "CSS"; +var type$7 = "markup"; +var tmScope$7 = "source.css"; +var aceMode$7 = "css"; +var codemirrorMode$7 = "css"; +var codemirrorMimeType$7 = "text/css"; +var color$2 = "#563d7c"; +var extensions$7 = [ + ".css" +]; +var languageId$7 = 50; +var CSS = { + name: name$9, + type: type$7, + tmScope: tmScope$7, + aceMode: aceMode$7, + codemirrorMode: codemirrorMode$7, + codemirrorMimeType: codemirrorMimeType$7, + color: color$2, + extensions: extensions$7, + languageId: languageId$7 +}; + +var CSS$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$9, + type: type$7, + tmScope: tmScope$7, + aceMode: aceMode$7, + codemirrorMode: codemirrorMode$7, + codemirrorMimeType: codemirrorMimeType$7, + color: color$2, + extensions: extensions$7, + languageId: languageId$7, + 'default': CSS +}); + +var name$a = "PostCSS"; +var type$8 = "markup"; +var tmScope$8 = "source.postcss"; +var group$c = "CSS"; +var extensions$8 = [ + ".pcss", + ".postcss" +]; +var aceMode$8 = "text"; +var languageId$8 = 262764437; +var PostCSS = { + name: name$a, + type: type$8, + tmScope: tmScope$8, + group: group$c, + extensions: extensions$8, + aceMode: aceMode$8, + languageId: languageId$8 +}; + +var PostCSS$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$a, + type: type$8, + tmScope: tmScope$8, + group: group$c, + extensions: extensions$8, + aceMode: aceMode$8, + languageId: languageId$8, + 'default': PostCSS +}); + +var name$b = "Less"; +var type$9 = "markup"; +var group$d = "CSS"; +var extensions$9 = [ + ".less" +]; +var tmScope$9 = "source.css.less"; +var aceMode$9 = "less"; +var codemirrorMode$8 = "css"; +var codemirrorMimeType$8 = "text/css"; +var languageId$9 = 198; +var Less = { + name: name$b, + type: type$9, + group: group$d, + extensions: extensions$9, + tmScope: tmScope$9, + aceMode: aceMode$9, + codemirrorMode: codemirrorMode$8, + codemirrorMimeType: codemirrorMimeType$8, + languageId: languageId$9 +}; + +var Less$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$b, + type: type$9, + group: group$d, + extensions: extensions$9, + tmScope: tmScope$9, + aceMode: aceMode$9, + codemirrorMode: codemirrorMode$8, + codemirrorMimeType: codemirrorMimeType$8, + languageId: languageId$9, + 'default': Less +}); + +var name$c = "SCSS"; +var type$a = "markup"; +var tmScope$a = "source.css.scss"; +var group$e = "CSS"; +var aceMode$a = "scss"; +var codemirrorMode$9 = "css"; +var codemirrorMimeType$9 = "text/x-scss"; +var extensions$a = [ + ".scss" +]; +var languageId$a = 329; +var SCSS = { + name: name$c, + type: type$a, + tmScope: tmScope$a, + group: group$e, + aceMode: aceMode$a, + codemirrorMode: codemirrorMode$9, + codemirrorMimeType: codemirrorMimeType$9, + extensions: extensions$a, + languageId: languageId$a +}; + +var SCSS$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$c, + type: type$a, + tmScope: tmScope$a, + group: group$e, + aceMode: aceMode$a, + codemirrorMode: codemirrorMode$9, + codemirrorMimeType: codemirrorMimeType$9, + extensions: extensions$a, + languageId: languageId$a, + 'default': SCSS +}); + +var require$$0$3 = getCjsExportFromNamespace(CSS$1); + +var require$$1$1 = getCjsExportFromNamespace(PostCSS$1); + +var require$$2$1 = getCjsExportFromNamespace(Less$1); + +var require$$3$1 = getCjsExportFromNamespace(SCSS$1); + +const languages$1 = [createLanguage(require$$0$3, () => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["css"] +})), createLanguage(require$$1$1, () => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["postcss"] +})), createLanguage(require$$2$1, () => ({ + since: "1.4.0", + parsers: ["less"], + vscodeLanguageIds: ["less"] +})), createLanguage(require$$3$1, () => ({ + since: "1.4.0", + parsers: ["scss"], + vscodeLanguageIds: ["scss"] +}))]; +const printers$1 = { + postcss: printerPostcss +}; +const parsers$1 = { + // TODO: switch these to just `postcss` and use `language` instead. + get css() { + return require("./parser-postcss").parsers.css; + }, + + get less() { + return require("./parser-postcss").parsers.less; + }, + + get scss() { + return require("./parser-postcss").parsers.scss; + } + +}; +var languageCss = { + languages: languages$1, + options: options$3, + printers: printers$1, + parsers: parsers$1 +}; + +var clean$3 = function (ast, newNode) { + delete newNode.loc; + delete newNode.selfClosing; // (Glimmer/HTML) ignore TextNode whitespace + + if (ast.type === "TextNode") { + const trimmed = ast.chars.trim(); + + if (!trimmed) { + return null; + } + + newNode.chars = trimmed; + } +}; + +var index = [ + "area", + "base", + "basefont", + "bgsound", + "br", + "col", + "command", + "embed", + "frame", + "hr", + "image", + "img", + "input", + "isindex", + "keygen", + "link", + "menuitem", + "meta", + "nextid", + "param", + "source", + "track", + "wbr" +]; + +var htmlVoidElements = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': index +}); + +var htmlVoidElements$1 = getCjsExportFromNamespace(htmlVoidElements); + +function isUppercase(string) { + return string.toUpperCase() === string; +} + +function isGlimmerComponent(node) { + return isNodeOfSomeType(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes(".")); +} + +const voidTags = new Set(htmlVoidElements$1); + +function isVoid(node) { + return isGlimmerComponent(node) && (node.children === 0 || node.children.every(n => isWhitespaceNode(n))) || voidTags.has(node.tag); +} + +function isWhitespaceNode(node) { + return isNodeOfSomeType(node, ["TextNode"]) && !/\S/.test(node.chars); +} + +function isNodeOfSomeType(node, types) { + return node && types.some(type => node.type === type); +} + +function isParentOfSomeType(path, types) { + const parentNode = path.getParentNode(0); + return isNodeOfSomeType(parentNode, types); +} + +function isPreviousNodeOfSomeType(path, types) { + const previousNode = getPreviousNode(path); + return isNodeOfSomeType(previousNode, types); +} + +function isNextNodeOfSomeType(path, types) { + const nextNode = getNextNode(path); + return isNodeOfSomeType(nextNode, types); +} + +function getSiblingNode(path, offset) { + const node = path.getValue(); + const parentNode = path.getParentNode(0) || {}; + const children = parentNode.children || parentNode.body || parentNode.parts || []; + const index = children.indexOf(node); + return index !== -1 && children[index + offset]; +} + +function getPreviousNode(path, lookBack = 1) { + return getSiblingNode(path, -lookBack); +} + +function getNextNode(path) { + return getSiblingNode(path, 1); +} + +function isPrettierIgnoreNode(node) { + return isNodeOfSomeType(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore"; +} + +function hasPrettierIgnore$2(path) { + const node = path.getValue(); + const previousPreviousNode = getPreviousNode(path, 2); + return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode); +} + +var utils$8 = { + getNextNode, + getPreviousNode, + hasPrettierIgnore: hasPrettierIgnore$2, + isNextNodeOfSomeType, + isNodeOfSomeType, + isParentOfSomeType, + isPreviousNodeOfSomeType, + isVoid, + isWhitespaceNode +}; + +const { + concat: concat$h, + group: group$f, + hardline: hardline$b, + ifBreak: ifBreak$6, + indent: indent$b, + join: join$9, + line: line$a, + softline: softline$8 +} = document.builders; +const { + getNextNode: getNextNode$1, + getPreviousNode: getPreviousNode$1, + hasPrettierIgnore: hasPrettierIgnore$3, + isNextNodeOfSomeType: isNextNodeOfSomeType$1, + isNodeOfSomeType: isNodeOfSomeType$1, + isParentOfSomeType: isParentOfSomeType$1, + isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1, + isVoid: isVoid$1, + isWhitespaceNode: isWhitespaceNode$1 +} = utils$8; // Formatter based on @glimmerjs/syntax's built-in test formatter: +// https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts + +function print$2(path, options, print) { + const n = path.getValue(); + /* istanbul ignore if*/ + + if (!n) { + return ""; + } + + if (hasPrettierIgnore$3(path)) { + const startOffset = locationToOffset(options.originalText, n.loc.start.line - 1, n.loc.start.column); + const endOffset = locationToOffset(options.originalText, n.loc.end.line - 1, n.loc.end.column); + const ignoredText = options.originalText.slice(startOffset, endOffset); + return ignoredText; + } + + switch (n.type) { + case "Block": + case "Program": + case "Template": + { + return group$f(concat$h(path.map(print, "body"))); + } + + case "ElementNode": + { + // TODO: make it whitespace sensitive + const bim = isNextNodeOfSomeType$1(path, ["ElementNode"]) ? hardline$b : ""; + + if (isVoid$1(n)) { + return concat$h([group$f(printStartingTag(path, print)), bim]); + } + + const isWhitespaceOnly = n.children.every(n => isWhitespaceNode$1(n)); + return concat$h([group$f(printStartingTag(path, print)), group$f(concat$h([isWhitespaceOnly ? "" : indent$b(printChildren(path, options, print)), n.children.length ? hardline$b : "", concat$h([""])])), bim]); + } + + case "BlockStatement": + { + const pp = path.getParentNode(1); + const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === n && pp.inverse.body[0].path.parts[0] === "if"; + + if (isElseIf) { + return concat$h([printElseIfBlock(path, print), printProgram(path, print), printInverse(path, print)]); + } + + return concat$h([printOpenBlock(path, print), group$f(concat$h([printProgram(path, print), printInverse(path, print), printCloseBlock(path, print)]))]); + } + + case "ElementModifierStatement": + { + return group$f(concat$h(["{{", printPathAndParams(path, print), softline$8, "}}"])); + } + + case "MustacheStatement": + { + const isParentOfSpecifiedTypes = isParentOfSomeType$1(path, ["AttrNode", "ConcatStatement"]); + const isChildOfElementNodeAndDoesNotHaveParams = isParentOfSomeType$1(path, ["ElementNode"]) && doesNotHaveHashParams(n) && doesNotHavePositionalParams(n); + const shouldBreakOpeningMustache = isParentOfSpecifiedTypes || isChildOfElementNodeAndDoesNotHaveParams; + return group$f(concat$h([printOpeningMustache(n), shouldBreakOpeningMustache ? indent$b(softline$8) : "", printPathAndParams(path, print), softline$8, printClosingMustache(n)])); + } + + case "SubExpression": + { + return group$f(concat$h(["(", printSubExpressionPathAndParams(path, print), softline$8, ")"])); + } + + case "AttrNode": + { + const isText = n.value.type === "TextNode"; + const isEmptyText = isText && n.value.chars === ""; // If the text is empty and the value's loc start and end columns are the + // same, there is no value for this AttrNode and it should be printed + // without the `=""`. Example: `` -> `` + + const isEmptyValue = isEmptyText && n.value.loc.start.column === n.value.loc.end.column; + + if (isEmptyValue) { + return concat$h([n.name]); + } + + const value = path.call(print, "value"); + const quotedValue = isText ? printStringLiteral(value.parts.join(), options) : value; + return concat$h([n.name, "=", quotedValue]); + } + + case "ConcatStatement": + { + const quote = options.singleQuote ? "'" : '"'; + return concat$h([quote, ...path.map(partPath => print(partPath), "parts"), quote]); + } + + case "Hash": + { + return concat$h([join$9(line$a, path.map(print, "pairs"))]); + } + + case "HashPair": + { + return concat$h([n.key, "=", path.call(print, "value")]); + } + + case "TextNode": + { + const maxLineBreaksToPreserve = 2; + const isFirstElement = !getPreviousNode$1(path); + const isLastElement = !getNextNode$1(path); + const isWhitespaceOnly = !/\S/.test(n.chars); + const lineBreaksCount = countNewLines(n.chars); + let leadingLineBreaksCount = countLeadingNewLines(n.chars); + let trailingLineBreaksCount = countTrailingNewLines(n.chars); + + if ((isFirstElement || isLastElement) && isWhitespaceOnly && isParentOfSomeType$1(path, ["Block", "ElementNode", "Template"])) { + return ""; + } + + if (isWhitespaceOnly && lineBreaksCount) { + leadingLineBreaksCount = Math.min(lineBreaksCount, maxLineBreaksToPreserve); + trailingLineBreaksCount = 0; + } else { + if (isNextNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) { + trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1); + } + + if (isPreviousNodeOfSomeType$1(path, ["BlockStatement", "ElementNode"])) { + leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1); + } + } + + const inAttrNode = path.stack.includes("attributes"); + + if (inAttrNode) { + // TODO: format style and srcset attributes + // and cleanup concat that is not necessary + if (!isInAttributeOfName(path, "class")) { + return concat$h([n.chars]); + } + + let leadingSpace = ""; + let trailingSpace = ""; + + if (isParentOfSomeType$1(path, ["ConcatStatement"])) { + if (isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) { + leadingSpace = " "; + } + + if (isNextNodeOfSomeType$1(path, ["MustacheStatement"])) { + trailingSpace = " "; + } + } + + return concat$h([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), n.chars.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]); + } + + let leadingSpace = ""; + let trailingSpace = ""; + + if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType$1(path, ["MustacheStatement"])) { + trailingSpace = " "; + } + + if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType$1(path, ["MustacheStatement"])) { + leadingSpace = " "; + } + + if (isFirstElement) { + leadingLineBreaksCount = 0; + leadingSpace = ""; + } + + if (isLastElement) { + trailingLineBreaksCount = 0; + trailingSpace = ""; + } + + let text = n.chars; + /* if `{{my-component}}` (or any text starting with a mustache) + * makes it to the TextNode, + * it means it was escaped, + * so let's print it escaped, ie.; `\{{my-component}}` */ + + if (text.startsWith("{{") && text.includes("}}")) { + text = "\\" + text; + } + + return concat$h([...generateHardlines(leadingLineBreaksCount, maxLineBreaksToPreserve), text.replace(/^\s+/g, leadingSpace).replace(/\s+$/, trailingSpace), ...generateHardlines(trailingLineBreaksCount, maxLineBreaksToPreserve)]); + } + + case "MustacheCommentStatement": + { + const dashes = n.value.includes("}}") ? "--" : ""; + return concat$h(["{{!", dashes, n.value, dashes, "}}"]); + } + + case "PathExpression": + { + return n.original; + } + + case "BooleanLiteral": + { + return String(n.value); + } + + case "CommentStatement": + { + return concat$h([""]); + } + + case "StringLiteral": + { + return printStringLiteral(n.value, options); + } + + case "NumberLiteral": + { + return String(n.value); + } + + case "UndefinedLiteral": + { + return "undefined"; + } + + case "NullLiteral": + { + return "null"; + } + + /* istanbul ignore next */ + + default: + throw new Error("unknown glimmer type: " + JSON.stringify(n.type)); + } +} +/* ElementNode print helpers */ + + +function printStartingTag(path, print) { + const node = path.getValue(); + return concat$h(["<", node.tag, printAttributesLike(path, print), printBlockParams(node), printStartingTagEndMarker(node)]); +} + +function printAttributesLike(path, print) { + const node = path.getValue(); + return indent$b(concat$h([node.attributes.length ? line$a : "", join$9(line$a, path.map(print, "attributes")), node.modifiers.length ? line$a : "", join$9(line$a, path.map(print, "modifiers")), node.comments.length ? line$a : "", join$9(line$a, path.map(print, "comments"))])); +} + +function printChildren(path, options, print) { + return concat$h(path.map((childPath, childIndex) => { + if (childIndex === 0) { + return concat$h([softline$8, print(childPath, options, print)]); + } + + return print(childPath, options, print); + }, "children")); +} + +function printStartingTagEndMarker(node) { + if (isVoid$1(node)) { + return ifBreak$6(concat$h([softline$8, "/>"]), concat$h([" />", softline$8])); + } + + return ifBreak$6(concat$h([softline$8, ">"]), ">"); +} +/* MustacheStatement print helpers */ + + +function printOpeningMustache(node) { + const mustache = node.escaped === false ? "{{{" : "{{"; + const strip = node.strip && node.strip.open ? "~" : ""; + return concat$h([mustache, strip]); +} + +function printClosingMustache(node) { + const mustache = node.escaped === false ? "}}}" : "}}"; + const strip = node.strip && node.strip.close ? "~" : ""; + return concat$h([strip, mustache]); +} +/* BlockStatement print helpers */ + + +function printOpeningBlockOpeningMustache(node) { + const opening = printOpeningMustache(node); + const strip = node.openStrip.open ? "~" : ""; + return concat$h([opening, strip, "#"]); +} + +function printOpeningBlockClosingMustache(node) { + const closing = printClosingMustache(node); + const strip = node.openStrip.close ? "~" : ""; + return concat$h([strip, closing]); +} + +function printClosingBlockOpeningMustache(node) { + const opening = printOpeningMustache(node); + const strip = node.closeStrip.open ? "~" : ""; + return concat$h([opening, strip, "/"]); +} + +function printClosingBlockClosingMustache(node) { + const closing = printClosingMustache(node); + const strip = node.closeStrip.close ? "~" : ""; + return concat$h([strip, closing]); +} + +function printInverseBlockOpeningMustache(node) { + const opening = printOpeningMustache(node); + const strip = node.inverseStrip.open ? "~" : ""; + return concat$h([opening, strip]); +} + +function printInverseBlockClosingMustache(node) { + const closing = printClosingMustache(node); + const strip = node.inverseStrip.close ? "~" : ""; + return concat$h([strip, closing]); +} + +function printOpenBlock(path, print) { + const node = path.getValue(); + return group$f(concat$h([printOpeningBlockOpeningMustache(node), printPathAndParams(path, print), printBlockParams(node.program), softline$8, printOpeningBlockClosingMustache(node)])); +} + +function printElseBlock(node) { + return concat$h([hardline$b, printInverseBlockOpeningMustache(node), "else", printInverseBlockClosingMustache(node)]); +} + +function printElseIfBlock(path, print) { + const parentNode = path.getParentNode(1); + return concat$h([printInverseBlockOpeningMustache(parentNode), "else ", printPathAndParams(path, print), printInverseBlockClosingMustache(parentNode)]); +} + +function printCloseBlock(path, print) { + const node = path.getValue(); + return concat$h([blockStatementHasOnlyWhitespaceInProgram(node) ? softline$8 : hardline$b, printClosingBlockOpeningMustache(node), path.call(print, "path"), printClosingBlockClosingMustache(node)]); +} + +function blockStatementHasOnlyWhitespaceInProgram(node) { + return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.program.body.every(n => isWhitespaceNode$1(n)); +} + +function blockStatementHasElseIf(node) { + return blockStatementHasElse(node) && node.inverse.body.length === 1 && isNodeOfSomeType$1(node.inverse.body[0], ["BlockStatement"]) && node.inverse.body[0].path.parts[0] === "if"; +} + +function blockStatementHasElse(node) { + return isNodeOfSomeType$1(node, ["BlockStatement"]) && node.inverse; +} + +function printProgram(path, print) { + const node = path.getValue(); + + if (blockStatementHasOnlyWhitespaceInProgram(node)) { + return ""; + } + + const program = path.call(print, "program"); + return indent$b(concat$h([hardline$b, program])); +} + +function printInverse(path, print) { + const node = path.getValue(); + const inverse = path.call(print, "inverse"); + const parts = concat$h([hardline$b, inverse]); + + if (blockStatementHasElseIf(node)) { + return parts; + } + + if (blockStatementHasElse(node)) { + return concat$h([printElseBlock(node), indent$b(parts)]); + } + + return ""; +} +/* TextNode print helpers */ + + +function isInAttributeOfName(path, type) { + return isParentOfSomeType$1(path, ["AttrNode"]) && path.getParentNode().name.toLowerCase() === type || isParentOfSomeType$1(path, ["ConcatStatement"]) && path.getParentNode(1).name.toLowerCase() === type; +} + +function countNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + return string.split("\n").length - 1; +} + +function countLeadingNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/g) || [])[0] || ""; + return countNewLines(newLines); +} + +function countTrailingNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/g) || [])[0] || ""; + return countNewLines(newLines); +} + +function generateHardlines(number = 0, max = 0) { + return new Array(Math.min(number, max)).fill(hardline$b); +} +/* StringLiteral print helpers */ + +/** + * Prints a string literal with the correct surrounding quotes based on + * `options.singleQuote` and the number of escaped quotes contained in + * the string literal. This function is the glimmer equivalent of `printString` + * in `common/util`, but has differences because of the way escaped characters + * are treated in hbs string literals. + * @param {string} stringLiteral - the string literal value + * @param {object} options - the prettier options object + */ + + +function printStringLiteral(stringLiteral, options) { + const double = { + quote: '"', + regex: /"/g + }; + const single = { + quote: "'", + regex: /'/g + }; + const preferred = options.singleQuote ? single : double; + const alternate = preferred === single ? double : single; + let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for + // enclosing the string, we might want to enclose with the alternate quote + // instead, to minimize the number of escaped quotes. + + if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) { + const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length; + const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length; + shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes; + } + + const enclosingQuote = shouldUseAlternateQuote ? alternate : preferred; + const escapedStringLiteral = stringLiteral.replace(enclosingQuote.regex, `\\${enclosingQuote.quote}`); + return concat$h([enclosingQuote.quote, escapedStringLiteral, enclosingQuote.quote]); +} +/* SubExpression print helpers */ + + +function printSubExpressionPathAndParams(path, print) { + const p = printPath(path, print); + const params = printParams(path, print); + + if (!params) { + return p; + } + + return indent$b(concat$h([p, line$a, group$f(params)])); +} +/* misc. print helpers */ + + +function printPathAndParams(path, print) { + const p = printPath(path, print); + const params = printParams(path, print); + + if (!params) { + return p; + } + + return indent$b(group$f(concat$h([p, line$a, params]))); +} + +function printPath(path, print) { + return path.call(print, "path"); +} + +function printParams(path, print) { + const node = path.getValue(); + const parts = []; + + if (node.params.length) { + const params = path.map(print, "params"); + parts.push(...params); + } + + if (node.hash && node.hash.pairs.length > 0) { + const hash = path.call(print, "hash"); + parts.push(hash); + } + + if (!parts.length) { + return ""; + } + + return join$9(line$a, parts); +} + +function printBlockParams(node) { + if (!node || !node.blockParams.length) { + return ""; + } + + return concat$h([" as |", node.blockParams.join(" "), "|"]); +} +/* istanbul ignore next + https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/compiler/lib/location.ts#L5-L29 +*/ + + +function locationToOffset(source, line, column) { + let seenLines = 0; + let seenChars = 0; // eslint-disable-next-line no-constant-condition + + while (true) { + if (seenChars === source.length) { + return null; + } + + let nextLine = source.indexOf("\n", seenChars); + + if (nextLine === -1) { + nextLine = source.length; + } + + if (seenLines === line) { + if (seenChars + column > nextLine) { + return null; + } + + return seenChars + column; + } else if (nextLine === -1) { + return null; + } + + seenLines += 1; + seenChars = nextLine + 1; + } +} + +function doesNotHaveHashParams(node) { + return node.hash.pairs.length === 0; +} + +function doesNotHavePositionalParams(node) { + return node.params.length === 0; +} + +var printerGlimmer = { + print: print$2, + massageAstNode: clean$3 +}; + +var name$d = "Handlebars"; +var type$b = "markup"; +var group$g = "HTML"; +var aliases$3 = [ + "hbs", + "htmlbars" +]; +var extensions$b = [ + ".handlebars", + ".hbs" +]; +var tmScope$b = "text.html.handlebars"; +var aceMode$b = "handlebars"; +var languageId$b = 155; +var Handlebars = { + name: name$d, + type: type$b, + group: group$g, + aliases: aliases$3, + extensions: extensions$b, + tmScope: tmScope$b, + aceMode: aceMode$b, + languageId: languageId$b +}; + +var Handlebars$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$d, + type: type$b, + group: group$g, + aliases: aliases$3, + extensions: extensions$b, + tmScope: tmScope$b, + aceMode: aceMode$b, + languageId: languageId$b, + 'default': Handlebars +}); + +var require$$0$4 = getCjsExportFromNamespace(Handlebars$1); + +const languages$2 = [createLanguage(require$$0$4, () => ({ + since: null, + // unreleased + parsers: ["glimmer"], + vscodeLanguageIds: ["handlebars"] +}))]; +const printers$2 = { + glimmer: printerGlimmer +}; +const parsers$2 = { + get glimmer() { + return require("./parser-glimmer").parsers.glimmer; + } + +}; +var languageHandlebars = { + languages: languages$2, + printers: printers$2, + parsers: parsers$2 +}; + +function hasPragma$2(text) { + return /^\s*#[^\S\n]*@(format|prettier)\s*(\n|$)/.test(text); +} + +function insertPragma$4(text) { + return "# @format\n\n" + text; +} + +var pragma$2 = { + hasPragma: hasPragma$2, + insertPragma: insertPragma$4 +}; + +const { + concat: concat$i, + join: join$a, + hardline: hardline$c, + line: line$b, + softline: softline$9, + group: group$h, + indent: indent$c, + ifBreak: ifBreak$7 +} = document.builders; +const { + hasIgnoreComment: hasIgnoreComment$4, + isNextLineEmpty: isNextLineEmpty$6 +} = util; +const { + insertPragma: insertPragma$5 +} = pragma$2; + +function genericPrint$3(path, options, print) { + const n = path.getValue(); + + if (!n) { + return ""; + } + + if (typeof n === "string") { + return n; + } + + switch (n.kind) { + case "Document": + { + const parts = []; + path.map((pathChild, index) => { + parts.push(concat$i([pathChild.call(print)])); + + if (index !== n.definitions.length - 1) { + parts.push(hardline$c); + + if (isNextLineEmpty$6(options.originalText, pathChild.getValue(), options.locEnd)) { + parts.push(hardline$c); + } + } + }, "definitions"); + return concat$i([concat$i(parts), hardline$c]); + } + + case "OperationDefinition": + { + const hasOperation = options.originalText[options.locStart(n)] !== "{"; + const hasName = !!n.name; + return concat$i([hasOperation ? n.operation : "", hasOperation && hasName ? concat$i([" ", path.call(print, "name")]) : "", n.variableDefinitions && n.variableDefinitions.length ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.map(print, "variableDefinitions"))])), softline$9, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? !hasOperation && !hasName ? "" : " " : "", path.call(print, "selectionSet")]); + } + + case "FragmentDefinition": + { + return concat$i(["fragment ", path.call(print, "name"), n.variableDefinitions && n.variableDefinitions.length ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.map(print, "variableDefinitions"))])), softline$9, ")"])) : "", " on ", path.call(print, "typeCondition"), printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); + } + + case "SelectionSet": + { + return concat$i(["{", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))])), hardline$c, "}"]); + } + + case "Field": + { + return group$h(concat$i([n.alias ? concat$i([path.call(print, "alias"), ": "]) : "", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", printDirectives(path, print, n), n.selectionSet ? " " : "", path.call(print, "selectionSet")])); + } + + case "Name": + { + return n.value; + } + + case "StringValue": + { + if (n.block) { + return concat$i(['"""', hardline$c, join$a(hardline$c, n.value.replace(/"""/g, "\\$&").split("\n")), hardline$c, '"""']); + } + + return concat$i(['"', n.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']); + } + + case "IntValue": + case "FloatValue": + case "EnumValue": + { + return n.value; + } + + case "BooleanValue": + { + return n.value ? "true" : "false"; + } + + case "NullValue": + { + return "null"; + } + + case "Variable": + { + return concat$i(["$", path.call(print, "name")]); + } + + case "ListValue": + { + return group$h(concat$i(["[", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.map(print, "values"))])), softline$9, "]"])); + } + + case "ObjectValue": + { + return group$h(concat$i(["{", options.bracketSpacing && n.fields.length > 0 ? " " : "", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.map(print, "fields"))])), softline$9, ifBreak$7("", options.bracketSpacing && n.fields.length > 0 ? " " : ""), "}"])); + } + + case "ObjectField": + case "Argument": + { + return concat$i([path.call(print, "name"), ": ", path.call(print, "value")]); + } + + case "Directive": + { + return concat$i(["@", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : ""]); + } + + case "NamedType": + { + return path.call(print, "name"); + } + + case "VariableDefinition": + { + return concat$i([path.call(print, "variable"), ": ", path.call(print, "type"), n.defaultValue ? concat$i([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); + } + + case "ObjectTypeExtension": + case "ObjectTypeDefinition": + { + return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "ObjectTypeExtension" ? "extend " : "", "type ", path.call(print, "name"), n.interfaces.length > 0 ? concat$i([" implements ", concat$i(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$i([" {", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]); + } + + case "FieldDefinition": + { + return concat$i([path.call(print, "description"), n.description ? hardline$c : "", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", ": ", path.call(print, "type"), printDirectives(path, print, n)]); + } + + case "DirectiveDefinition": + { + return concat$i([path.call(print, "description"), n.description ? hardline$c : "", "directive ", "@", path.call(print, "name"), n.arguments.length > 0 ? group$h(concat$i(["(", indent$c(concat$i([softline$9, join$a(concat$i([ifBreak$7("", ", "), softline$9]), path.call(argsPath => printSequence(argsPath, options, print), "arguments"))])), softline$9, ")"])) : "", n.repeatable ? " repeatable" : "", concat$i([" on ", join$a(" | ", path.map(print, "locations"))])]); + } + + case "EnumTypeExtension": + case "EnumTypeDefinition": + { + return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "EnumTypeExtension" ? "extend " : "", "enum ", path.call(print, "name"), printDirectives(path, print, n), n.values.length > 0 ? concat$i([" {", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))])), hardline$c, "}"]) : ""]); + } + + case "EnumValueDefinition": + { + return concat$i([path.call(print, "description"), n.description ? hardline$c : "", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "InputValueDefinition": + { + return concat$i([path.call(print, "description"), n.description ? n.description.block ? hardline$c : line$b : "", path.call(print, "name"), ": ", path.call(print, "type"), n.defaultValue ? concat$i([" = ", path.call(print, "defaultValue")]) : "", printDirectives(path, print, n)]); + } + + case "InputObjectTypeExtension": + case "InputObjectTypeDefinition": + { + return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", path.call(print, "name"), printDirectives(path, print, n), n.fields.length > 0 ? concat$i([" {", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]); + } + + case "SchemaDefinition": + { + return concat$i(["schema", printDirectives(path, print, n), " {", n.operationTypes.length > 0 ? indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))])) : "", hardline$c, "}"]); + } + + case "OperationTypeDefinition": + { + return concat$i([path.call(print, "operation"), ": ", path.call(print, "type")]); + } + + case "InterfaceTypeExtension": + case "InterfaceTypeDefinition": + { + return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", path.call(print, "name"), n.interfaces.length > 0 ? concat$i([" implements ", concat$i(printInterfaces(path, options, print))]) : "", printDirectives(path, print, n), n.fields.length > 0 ? concat$i([" {", indent$c(concat$i([hardline$c, join$a(hardline$c, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))])), hardline$c, "}"]) : ""]); + } + + case "FragmentSpread": + { + return concat$i(["...", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "InlineFragment": + { + return concat$i(["...", n.typeCondition ? concat$i([" on ", path.call(print, "typeCondition")]) : "", printDirectives(path, print, n), " ", path.call(print, "selectionSet")]); + } + + case "UnionTypeExtension": + case "UnionTypeDefinition": + { + return group$h(concat$i([path.call(print, "description"), n.description ? hardline$c : "", group$h(concat$i([n.kind === "UnionTypeExtension" ? "extend " : "", "union ", path.call(print, "name"), printDirectives(path, print, n), n.types.length > 0 ? concat$i([" =", ifBreak$7("", " "), indent$c(concat$i([ifBreak$7(concat$i([line$b, " "])), join$a(concat$i([line$b, "| "]), path.map(print, "types"))]))]) : ""]))])); + } + + case "ScalarTypeExtension": + case "ScalarTypeDefinition": + { + return concat$i([path.call(print, "description"), n.description ? hardline$c : "", n.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", path.call(print, "name"), printDirectives(path, print, n)]); + } + + case "NonNullType": + { + return concat$i([path.call(print, "type"), "!"]); + } + + case "ListType": + { + return concat$i(["[", path.call(print, "type"), "]"]); + } + + default: + /* istanbul ignore next */ + throw new Error("unknown graphql type: " + JSON.stringify(n.kind)); + } +} + +function printDirectives(path, print, n) { + if (n.directives.length === 0) { + return ""; + } + + const printed = join$a(line$b, path.map(print, "directives")); + + if (n.kind === "FragmentDefinition" || n.kind === "OperationDefinition") { + return group$h(concat$i([line$b, printed])); + } + + return concat$i([" ", group$h(indent$c(concat$i([softline$9, printed])))]); +} + +function printSequence(sequencePath, options, print) { + const count = sequencePath.getValue().length; + return sequencePath.map((path, i) => { + const printed = print(path); + + if (isNextLineEmpty$6(options.originalText, path.getValue(), options.locEnd) && i < count - 1) { + return concat$i([printed, hardline$c]); + } + + return printed; + }); +} + +function canAttachComment$1(node) { + return node.kind && node.kind !== "Comment"; +} + +function printComment$2(commentPath) { + const comment = commentPath.getValue(); + + if (comment.kind === "Comment") { + return "#" + comment.value.trimEnd(); + } + /* istanbul ignore next */ + + + throw new Error("Not a comment: " + JSON.stringify(comment)); +} + +function printInterfaces(path, options, print) { + const node = path.getNode(); + const parts = []; + const { + interfaces + } = node; + const printed = path.map(node => print(node), "interfaces"); + + for (let index = 0; index < interfaces.length; index++) { + const interfaceNode = interfaces[index]; + parts.push(printed[index]); + const nextInterfaceNode = interfaces[index + 1]; + + if (nextInterfaceNode) { + const textBetween = options.originalText.slice(interfaceNode.loc.end, nextInterfaceNode.loc.start); + const hasComment = textBetween.includes("#"); + const separator = textBetween.replace(/#.*/g, "").trim(); + parts.push(separator === "," ? "," : " &"); + parts.push(hasComment ? line$b : " "); + } + } + + return parts; +} + +function clean$4(node, newNode +/*, parent*/ +) { + delete newNode.loc; + delete newNode.comments; +} + +var printerGraphql = { + print: genericPrint$3, + massageAstNode: clean$4, + hasPrettierIgnore: hasIgnoreComment$4, + insertPragma: insertPragma$5, + printComment: printComment$2, + canAttachComment: canAttachComment$1 +}; + +var options$4 = { + bracketSpacing: commonOptions.bracketSpacing +}; + +var name$e = "GraphQL"; +var type$c = "data"; +var extensions$c = [ + ".graphql", + ".gql", + ".graphqls" +]; +var tmScope$c = "source.graphql"; +var aceMode$c = "text"; +var languageId$c = 139; +var GraphQL = { + name: name$e, + type: type$c, + extensions: extensions$c, + tmScope: tmScope$c, + aceMode: aceMode$c, + languageId: languageId$c +}; + +var GraphQL$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$e, + type: type$c, + extensions: extensions$c, + tmScope: tmScope$c, + aceMode: aceMode$c, + languageId: languageId$c, + 'default': GraphQL +}); + +var require$$0$5 = getCjsExportFromNamespace(GraphQL$1); + +const languages$3 = [createLanguage(require$$0$5, () => ({ + since: "1.5.0", + parsers: ["graphql"], + vscodeLanguageIds: ["graphql"] +}))]; +const printers$3 = { + graphql: printerGraphql +}; +const parsers$3 = { + get graphql() { + return require("./parser-graphql").parsers.graphql; + } + +}; +var languageGraphql = { + languages: languages$3, + options: options$4, + printers: printers$3, + parsers: parsers$3 +}; + +var json = { + "cjkPattern": "(?:[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u3000-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d])(?:[\\ufe00-\\ufe0f]|\\udb40[\\udd00-\\uddef])?", + "kPattern": "[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]", + "punctuationPattern": "[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c77\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e4f\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud803[\\udf55-\\udf59]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc8\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\udc3b\\udde2\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71\\udef7-\\udef8\\udfff]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud81b[\\ude97-\\ude9a\\udfe2]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]" +}; + +const { + getLast: getLast$6 +} = util; +const { + cjkPattern, + kPattern, + punctuationPattern +} = json; +const INLINE_NODE_TYPES = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"]; +const INLINE_NODE_WRAPPER_TYPES = INLINE_NODE_TYPES.concat(["tableCell", "paragraph", "heading"]); +const kRegex = new RegExp(kPattern); +const punctuationRegex = new RegExp(punctuationPattern); +/** + * split text into whitespaces and words + * @param {string} text + * @return {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>} + */ + +function splitText(text, options) { + const KIND_NON_CJK = "non-cjk"; + const KIND_CJ_LETTER = "cj-letter"; + const KIND_K_LETTER = "k-letter"; + const KIND_CJK_PUNCTUATION = "cjk-punctuation"; + const nodes = []; + (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([\t\n ]+)/).forEach((token, index, tokens) => { + // whitespace + if (index % 2 === 1) { + nodes.push({ + type: "whitespace", + value: /\n/.test(token) ? "\n" : " " + }); + return; + } // word separated by whitespace + + + if ((index === 0 || index === tokens.length - 1) && token === "") { + return; + } + + token.split(new RegExp(`(${cjkPattern})`)).forEach((innerToken, innerIndex, innerTokens) => { + if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") { + return; + } // non-CJK word + + + if (innerIndex % 2 === 0) { + if (innerToken !== "") { + appendNode({ + type: "word", + value: innerToken, + kind: KIND_NON_CJK, + hasLeadingPunctuation: punctuationRegex.test(innerToken[0]), + hasTrailingPunctuation: punctuationRegex.test(getLast$6(innerToken)) + }); + } + + return; + } // CJK character + + + appendNode(punctuationRegex.test(innerToken) ? { + type: "word", + value: innerToken, + kind: KIND_CJK_PUNCTUATION, + hasLeadingPunctuation: true, + hasTrailingPunctuation: true + } : { + type: "word", + value: innerToken, + kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER, + hasLeadingPunctuation: false, + hasTrailingPunctuation: false + }); + }); + }); + return nodes; + + function appendNode(node) { + const lastNode = getLast$6(nodes); + + if (lastNode && lastNode.type === "word") { + if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) { + nodes.push({ + type: "whitespace", + value: " " + }); + } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace + ![lastNode.value, node.value].some(value => /\u3000/.test(value))) { + nodes.push({ + type: "whitespace", + value: "" + }); + } + } + + nodes.push(node); + + function isBetween(kind1, kind2) { + return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1; + } + } +} + +function getOrderedListItemInfo(orderListItem, originalText) { + const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/); + return { + numberText, + marker, + leadingSpaces + }; +} + +function hasGitDiffFriendlyOrderedList(node, options) { + if (!node.ordered) { + return false; + } + + if (node.children.length < 2) { + return false; + } + + const firstNumber = Number(getOrderedListItemInfo(node.children[0], options.originalText).numberText); + const secondNumber = Number(getOrderedListItemInfo(node.children[1], options.originalText).numberText); + + if (firstNumber === 0 && node.children.length > 2) { + const thirdNumber = Number(getOrderedListItemInfo(node.children[2], options.originalText).numberText); + return secondNumber === 1 && thirdNumber === 1; + } + + return secondNumber === 1; +} // workaround for https://github.com/remarkjs/remark/issues/351 +// leading and trailing newlines are stripped by remark + + +function getFencedCodeBlockValue(node, originalText) { + const text = originalText.trimEnd().slice(node.position.start.offset, node.position.end.offset); + const leadingSpaceCount = text.match(/^\s*/)[0].length; + const replaceRegex = new RegExp(`^\\s{0,${leadingSpaceCount}}`); + const lineContents = text.split("\n"); + const markerStyle = text[leadingSpaceCount]; // ` or ~ + + const marker = text.slice(leadingSpaceCount).match(new RegExp(`^[${markerStyle}]+`))[0]; // https://spec.commonmark.org/0.28/#example-104: Closing fences may be indented by 0-3 spaces + // https://spec.commonmark.org/0.28/#example-93: The closing code fence must be at least as long as the opening fence + + const hasEndMarker = new RegExp(`^\\s{0,3}${marker}`).test(lineContents[lineContents.length - 1].slice(getIndent(lineContents.length - 1))); + return lineContents.slice(1, hasEndMarker ? -1 : undefined).map((x, i) => x.slice(getIndent(i + 1)).replace(replaceRegex, "")).join("\n"); + + function getIndent(lineIndex) { + return node.position.indent[lineIndex - 1] - 1; + } +} + +function mapAst(ast, handler) { + return function preorder(node, index, parentStack) { + parentStack = parentStack || []; + const newNode = Object.assign({}, handler(node, index, parentStack)); + + if (newNode.children) { + newNode.children = newNode.children.map((child, index) => { + return preorder(child, index, [newNode].concat(parentStack)); + }); + } + + return newNode; + }(ast, null, null); +} + +function isAutolink(node, options) { + if (!node || node.type !== "link" || node.children.length !== 1) { + return false; + } + + const child = node.children[0]; + return child && options.locStart(node) === options.locStart(child) && options.locEnd(node) === options.locEnd(child); +} + +var utils$9 = { + mapAst, + splitText, + punctuationPattern, + getFencedCodeBlockValue, + getOrderedListItemInfo, + hasGitDiffFriendlyOrderedList, + INLINE_NODE_TYPES, + INLINE_NODE_WRAPPER_TYPES, + isAutolink +}; + +const { + getParserName: getParserName$1, + getMaxContinuousCount: getMaxContinuousCount$2 +} = util; +const { + builders: { + hardline: hardline$d, + concat: concat$j, + markAsRoot: markAsRoot$2 + }, + utils: { + replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$2 + } +} = document; +const { + print: printFrontMatter$1 +} = frontMatter; +const { + getFencedCodeBlockValue: getFencedCodeBlockValue$1 +} = utils$9; + +function embed$2(path, print, textToDoc, options) { + const node = path.getValue(); + + if (node.type === "code" && node.lang !== null) { + // only look for the first string so as to support [markdown-preview-enhanced](https://shd101wyy.github.io/markdown-preview-enhanced/#/code-chunk) + const langMatch = node.lang.match(/^[\w-]+/); + const lang = langMatch ? langMatch[0] : ""; + const parser = getParserName$1(lang, options); + + if (parser) { + const styleUnit = options.__inJsTemplate ? "~" : "`"; + const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$2(node.value, styleUnit) + 1)); + const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), { + parser + }, { + stripTrailingHardline: true + }); + return markAsRoot$2(concat$j([style, node.lang, node.meta ? " " + node.meta : "", hardline$d, replaceNewlinesWithLiterallines$2(doc), hardline$d, style])); + } + } + + switch (node.type) { + case "front-matter": + return printFrontMatter$1(node, textToDoc); + // MDX + + case "importExport": + return concat$j([textToDoc(node.value, { + parser: "babel" + }, { + stripTrailingHardline: true + }), hardline$d]); + + case "jsx": + return textToDoc(`<$>${node.value}`, { + parser: "__js_expression", + rootMarker: "mdx" + }, { + stripTrailingHardline: true + }); + } + + return null; +} + +var embed_1$2 = embed$2; + +const { + parse: parseFrontMatter$1 +} = frontMatter; +const pragmas = ["format", "prettier"]; + +function startWithPragma(text) { + const pragma = `@(${pragmas.join("|")})`; + const regex = new RegExp([``, ``].join("|"), "m"); + const matched = text.match(regex); + return matched && matched.index === 0; +} + +var pragma$3 = { + startWithPragma, + hasPragma: text => startWithPragma(parseFrontMatter$1(text).content.trimStart()), + insertPragma: text => { + const extracted = parseFrontMatter$1(text); + const pragma = ``; + return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`; + } +}; + +const { + getOrderedListItemInfo: getOrderedListItemInfo$1, + mapAst: mapAst$1, + splitText: splitText$1 +} = utils$9; // 0x0 ~ 0x10ffff +// eslint-disable-next-line no-control-regex + +const isSingleCharRegex = /^([\u0000-\uffff]|[\ud800-\udbff][\udc00-\udfff])$/; + +function preprocess$1(ast, options) { + ast = restoreUnescapedCharacter(ast, options); + ast = mergeContinuousTexts(ast); + ast = transformInlineCode(ast); + ast = transformIndentedCodeblockAndMarkItsParentList(ast, options); + ast = markAlignedList(ast, options); + ast = splitTextIntoSentences(ast, options); + ast = transformImportExport(ast); + ast = mergeContinuousImportExport(ast); + return ast; +} + +function transformImportExport(ast) { + return mapAst$1(ast, node => { + if (node.type !== "import" && node.type !== "export") { + return node; + } + + return Object.assign({}, node, { + type: "importExport" + }); + }); +} + +function transformInlineCode(ast) { + return mapAst$1(ast, node => { + if (node.type !== "inlineCode") { + return node; + } + + return Object.assign({}, node, { + value: node.value.replace(/\s+/g, " ") + }); + }); +} + +function restoreUnescapedCharacter(ast, options) { + return mapAst$1(ast, node => { + return node.type !== "text" ? node : Object.assign({}, node, { + value: node.value !== "*" && node.value !== "_" && node.value !== "$" && // handle these cases in printer + isSingleCharRegex.test(node.value) && node.position.end.offset - node.position.start.offset !== node.value.length ? options.originalText.slice(node.position.start.offset, node.position.end.offset) : node.value + }); + }); +} + +function mergeContinuousImportExport(ast) { + return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({ + type: "importExport", + value: prevNode.value + "\n\n" + node.value, + position: { + start: prevNode.position.start, + end: node.position.end + } + })); +} + +function mergeChildren(ast, shouldMerge, mergeNode) { + return mapAst$1(ast, node => { + if (!node.children) { + return node; + } + + const children = node.children.reduce((current, child) => { + const lastChild = current[current.length - 1]; + + if (lastChild && shouldMerge(lastChild, child)) { + current.splice(-1, 1, mergeNode(lastChild, child)); + } else { + current.push(child); + } + + return current; + }, []); + return Object.assign({}, node, { + children + }); + }); +} + +function mergeContinuousTexts(ast) { + return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({ + type: "text", + value: prevNode.value + node.value, + position: { + start: prevNode.position.start, + end: node.position.end + } + })); +} + +function splitTextIntoSentences(ast, options) { + return mapAst$1(ast, (node, index, [parentNode]) => { + if (node.type !== "text") { + return node; + } + + let { + value + } = node; + + if (parentNode.type === "paragraph") { + if (index === 0) { + value = value.trimStart(); + } + + if (index === parentNode.children.length - 1) { + value = value.trimEnd(); + } + } + + return { + type: "sentence", + position: node.position, + children: splitText$1(value, options) + }; + }); +} + +function transformIndentedCodeblockAndMarkItsParentList(ast, options) { + return mapAst$1(ast, (node, index, parentStack) => { + if (node.type === "code") { + // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it + const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset)); + node.isIndented = isIndented; + + if (isIndented) { + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; // no need to check checked items + + if (parent.hasIndentedCodeblock) { + break; + } + + if (parent.type === "list") { + parent.hasIndentedCodeblock = true; + } + } + } + } + + return node; + }); +} + +function markAlignedList(ast, options) { + return mapAst$1(ast, (node, index, parentStack) => { + if (node.type === "list" && node.children.length !== 0) { + // if one of its parents is not aligned, it's not possible to be aligned in sub-lists + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; + + if (parent.type === "list" && !parent.isAligned) { + node.isAligned = false; + return node; + } + } + + node.isAligned = isAligned(node); + } + + return node; + }); + + function getListItemStart(listItem) { + return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1; + } + + function isAligned(list) { + if (!list.ordered) { + /** + * - 123 + * - 123 + */ + return true; + } + + const [firstItem, secondItem] = list.children; + const firstInfo = getOrderedListItemInfo$1(firstItem, options.originalText); + + if (firstInfo.leadingSpaces.length > 1) { + /** + * 1. 123 + * + * 1. 123 + * 1. 123 + */ + return true; + } + + const firstStart = getListItemStart(firstItem); + + if (firstStart === -1) { + /** + * 1. + * + * 1. + * 1. + */ + return false; + } + + if (list.children.length === 1) { + /** + * aligned: + * + * 11. 123 + * + * not aligned: + * + * 1. 123 + */ + return firstStart % options.tabWidth === 0; + } + + const secondStart = getListItemStart(secondItem); + + if (firstStart !== secondStart) { + /** + * 11. 123 + * 1. 123 + * + * 1. 123 + * 11. 123 + */ + return false; + } + + if (firstStart % options.tabWidth === 0) { + /** + * 11. 123 + * 12. 123 + */ + return true; + } + /** + * aligned: + * + * 11. 123 + * 1. 123 + * + * not aligned: + * + * 1. 123 + * 2. 123 + */ + + + const secondInfo = getOrderedListItemInfo$1(secondItem, options.originalText); + return secondInfo.leadingSpaces.length > 1; + } +} + +var preprocess_1$1 = preprocess$1; + +const { + getLast: getLast$7, + getMinNotPresentContinuousCount: getMinNotPresentContinuousCount$1, + getMaxContinuousCount: getMaxContinuousCount$3, + getStringWidth: getStringWidth$4 +} = util; +const { + builders: { + breakParent: breakParent$6, + concat: concat$k, + join: join$b, + line: line$c, + literalline: literalline$4, + markAsRoot: markAsRoot$3, + hardline: hardline$e, + softline: softline$a, + ifBreak: ifBreak$8, + fill: fill$5, + align: align$3, + indent: indent$d, + group: group$i + }, + utils: { + normalizeDoc: normalizeDoc$1 + }, + printer: { + printDocToString: printDocToString$3 + } +} = document; +const { + replaceEndOfLineWith: replaceEndOfLineWith$1, + isFrontMatterNode: isFrontMatterNode$3 +} = util; +const { + getFencedCodeBlockValue: getFencedCodeBlockValue$2, + hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1, + splitText: splitText$2, + punctuationPattern: punctuationPattern$1, + INLINE_NODE_TYPES: INLINE_NODE_TYPES$1, + INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1, + isAutolink: isAutolink$1 +} = utils$9; +const TRAILING_HARDLINE_NODES = new Set(["importExport"]); +const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link"]; +const SIBLING_NODE_TYPES = new Set(["listItem", "definition", "footnoteDefinition"]); + +function genericPrint$4(path, options, print) { + const node = path.getValue(); + + if (shouldRemainTheSameContent(path)) { + return concat$k(splitText$2(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options))); + } + + switch (node.type) { + case "front-matter": + return options.originalText.slice(node.position.start.offset, node.position.end.offset); + + case "root": + if (node.children.length === 0) { + return ""; + } + + return concat$k([normalizeDoc$1(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.has(getLastDescendantNode(node).type) ? hardline$e : ""]); + + case "paragraph": + return printChildren$1(path, options, print, { + postprocessor: fill$5 + }); + + case "sentence": + return printChildren$1(path, options, print); + + case "word": + { + let escapedValue = node.value.replace(/[$*]/g, "\\$&") // escape all `*` and `$` (math) + .replace(new RegExp([`(^|${punctuationPattern$1})(_+)`, `(_+)(${punctuationPattern$1}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_")); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis + + const isFirstSentence = (node, name, index) => node.type === "sentence" && index === 0; + + const isLastChildAutolink = (node, name, index) => isAutolink$1(node.children[index - 1], options); + + if (escapedValue !== node.value && (path.match(undefined, isFirstSentence, isLastChildAutolink) || path.match(undefined, isFirstSentence, (node, name, index) => node.type === "emphasis" && index === 0, isLastChildAutolink))) { + // backslash is parsed as part of autolinks, so we need to remove it + escapedValue = escapedValue.replace(/^(\\?[*_])+/, prefix => prefix.replace(/\\/g, "")); + } + + return escapedValue; + } + + case "whitespace": + { + const parentNode = path.getParentNode(); + const index = parentNode.children.indexOf(node); + const nextNode = parentNode.children[index + 1]; + const proseWrap = // leading char that may cause different syntax + nextNode && /^>|^([*+-]|#{1,6}|\d+[).])$/.test(nextNode.value) ? "never" : options.proseWrap; + return printLine(path, node.value, { + proseWrap + }); + } + + case "emphasis": + { + let style; + + if (isAutolink$1(node.children[0], options)) { + style = options.originalText[node.position.start.offset]; + } else { + const parentNode = path.getParentNode(); + const index = parentNode.children.indexOf(node); + const prevNode = parentNode.children[index - 1]; + const nextNode = parentNode.children[index + 1]; + const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not + prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && getLast$7(prevNode.children).type === "word" && !getLast$7(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation; + style = hasPrevOrNextWord || getAncestorNode$2(path, "emphasis") ? "*" : "_"; + } + + return concat$k([style, printChildren$1(path, options, print), style]); + } + + case "strong": + return concat$k(["**", printChildren$1(path, options, print), "**"]); + + case "delete": + return concat$k(["~~", printChildren$1(path, options, print), "~~"]); + + case "inlineCode": + { + const backtickCount = getMinNotPresentContinuousCount$1(node.value, "`"); + const style = "`".repeat(backtickCount || 1); + const gap = backtickCount && !/^\s/.test(node.value) ? " " : ""; + return concat$k([style, gap, node.value, gap, style]); + } + + case "link": + switch (options.originalText[node.position.start.offset]) { + case "<": + { + const mailto = "mailto:"; + const url = // is parsed as { url: "mailto:hello@example.com" } + node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url; + return concat$k(["<", url, ">"]); + } + + case "[": + return concat$k(["[", printChildren$1(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]); + + default: + return options.originalText.slice(node.position.start.offset, node.position.end.offset); + } + + case "image": + return concat$k(["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]); + + case "blockquote": + return concat$k(["> ", align$3("> ", printChildren$1(path, options, print))]); + + case "heading": + return concat$k(["#".repeat(node.depth) + " ", printChildren$1(path, options, print)]); + + case "code": + { + if (node.isIndented) { + // indented code block + const alignment = " ".repeat(4); + return align$3(alignment, concat$k([alignment, concat$k(replaceEndOfLineWith$1(node.value, hardline$e))])); + } // fenced code block + + + const styleUnit = options.__inJsTemplate ? "~" : "`"; + const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$3(node.value, styleUnit) + 1)); + return concat$k([style, node.lang || "", node.meta ? " " + node.meta : "", hardline$e, concat$k(replaceEndOfLineWith$1(getFencedCodeBlockValue$2(node, options.originalText), hardline$e)), hardline$e, style]); + } + + case "html": + { + const parentNode = path.getParentNode(); + const value = parentNode.type === "root" && getLast$7(parentNode.children) === node ? node.value.trimEnd() : node.value; + const isHtmlComment = /^$/.test(value); + return concat$k(replaceEndOfLineWith$1(value, isHtmlComment ? hardline$e : markAsRoot$3(literalline$4))); + } + + case "list": + { + const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode()); + const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList$1(node, options); + return printChildren$1(path, options, print, { + processor: (childPath, index) => { + const prefix = getPrefix(); + const childNode = childPath.getValue(); + + if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) { + return concat$k([prefix, printListItem(childPath, options, print, prefix)]); + } + + return concat$k([prefix, align$3(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]); + + function getPrefix() { + const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* "; + return node.isAligned || + /* workaround for https://github.com/remarkjs/remark/issues/315 */ + node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix; + } + } + }); + } + + case "thematicBreak": + { + const counter = getAncestorCounter$1(path, "list"); + + if (counter === -1) { + return "---"; + } + + const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1)); + return nthSiblingIndex % 2 === 0 ? "***" : "---"; + } + + case "linkReference": + return concat$k(["[", printChildren$1(path, options, print), "]", node.referenceType === "full" ? concat$k(["[", node.identifier, "]"]) : node.referenceType === "collapsed" ? "[]" : ""]); + + case "imageReference": + switch (node.referenceType) { + case "full": + return concat$k(["![", node.alt || "", "][", node.identifier, "]"]); + + default: + return concat$k(["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]); + } + + case "definition": + { + const lineOrSpace = options.proseWrap === "always" ? line$c : " "; + return group$i(concat$k([concat$k(["[", node.identifier, "]:"]), indent$d(concat$k([lineOrSpace, printUrl(node.url), node.title === null ? "" : concat$k([lineOrSpace, printTitle(node.title, options, false)])]))])); + } + // `footnote` requires `.use(footnotes, {inlineNotes: true})`, we are not using this option + // https://github.com/remarkjs/remark-footnotes#optionsinlinenotes + + /* istanbul ignore next */ + + case "footnote": + return concat$k(["[^", printChildren$1(path, options, print), "]"]); + + case "footnoteReference": + return concat$k(["[^", node.identifier, "]"]); + + case "footnoteDefinition": + { + const nextNode = path.getParentNode().children[path.getName() + 1]; + const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line); + return concat$k(["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$1(path, options, print) : group$i(concat$k([align$3(" ".repeat(4), printChildren$1(path, options, print, { + processor: (childPath, index) => { + return index === 0 ? group$i(concat$k([softline$a, childPath.call(print)])) : childPath.call(print); + } + })), nextNode && nextNode.type === "footnoteDefinition" ? softline$a : ""]))]); + } + + case "table": + return printTable(path, options, print); + + case "tableCell": + return printChildren$1(path, options, print); + + case "break": + return /\s/.test(options.originalText[node.position.start.offset]) ? concat$k([" ", markAsRoot$3(literalline$4)]) : concat$k(["\\", hardline$e]); + + case "liquidNode": + return concat$k(replaceEndOfLineWith$1(node.value, hardline$e)); + // MDX + + case "importExport": + case "jsx": + // fallback to the original text if multiparser failed + // or `embeddedLanguageFormatting: "off"` + return concat$k([node.value, hardline$e]); + + case "math": + return concat$k(["$$", hardline$e, node.value ? concat$k([concat$k(replaceEndOfLineWith$1(node.value, hardline$e)), hardline$e]) : "", "$$"]); + + case "inlineMath": + { + // remark-math trims content but we don't want to remove whitespaces + // since it's very possible that it's recognized as math accidentally + return options.originalText.slice(options.locStart(node), options.locEnd(node)); + } + + case "tableRow": // handled in "table" + + case "listItem": // handled in "list" + + default: + /* istanbul ignore next */ + throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`); + } +} + +function printListItem(path, options, print, listPrefix) { + const node = path.getValue(); + const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] "; + return concat$k([prefix, printChildren$1(path, options, print, { + processor: (childPath, index) => { + if (index === 0 && childPath.getValue().type !== "list") { + return align$3(" ".repeat(prefix.length), childPath.call(print)); + } + + const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block + ); + return concat$k([alignment, align$3(alignment, childPath.call(print))]); + } + })]); +} + +function alignListPrefix(prefix, options) { + const additionalSpaces = getAdditionalSpaces(); + return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block + ); + + function getAdditionalSpaces() { + const restSpaces = prefix.length % options.tabWidth; + return restSpaces === 0 ? 0 : options.tabWidth - restSpaces; + } +} + +function getNthListSiblingIndex(node, parentNode) { + return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered); +} + +function getNthSiblingIndex(node, parentNode, condition) { + condition = condition || (() => true); + + let index = -1; + + for (const childNode of parentNode.children) { + if (childNode.type === node.type && condition(childNode)) { + index++; + } else { + index = -1; + } + + if (childNode === node) { + return index; + } + } +} + +function getAncestorCounter$1(path, typeOrTypes) { + const types = [].concat(typeOrTypes); + let counter = -1; + let ancestorNode; + + while (ancestorNode = path.getParentNode(++counter)) { + if (types.includes(ancestorNode.type)) { + return counter; + } + } + + return -1; +} + +function getAncestorNode$2(path, typeOrTypes) { + const counter = getAncestorCounter$1(path, typeOrTypes); + return counter === -1 ? null : path.getParentNode(counter); +} + +function printLine(path, value, options) { + if (options.proseWrap === "preserve" && value === "\n") { + return hardline$e; + } + + const isBreakable = options.proseWrap === "always" && !getAncestorNode$2(path, SINGLE_LINE_NODE_TYPES); + return value !== "" ? isBreakable ? line$c : " " : isBreakable ? softline$a : ""; +} + +function printTable(path, options, print) { + const hardlineWithoutBreakParent = hardline$e.parts[0]; + const node = path.getValue(); + const contents = []; // { [rowIndex: number]: { [columnIndex: number]: string } } + + path.map(rowPath => { + const rowContents = []; + rowPath.map(cellPath => { + rowContents.push(printDocToString$3(cellPath.call(print), options).formatted); + }, "children"); + contents.push(rowContents); + }, "children"); // Get the width of each column + + const columnMaxWidths = contents.reduce((currentWidths, rowContents) => currentWidths.map((width, columnIndex) => Math.max(width, getStringWidth$4(rowContents[columnIndex]))), contents[0].map(() => 3) // minimum width = 3 (---, :--, :-:, --:) + ); + const alignedTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0]), printSeparator(), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents)))]); + + if (options.proseWrap !== "never") { + return concat$k([breakParent$6, alignedTable]); + } // Only if the --prose-wrap never is set and it exceeds the print width. + + + const compactTable = join$b(hardlineWithoutBreakParent, [printRow(contents[0], + /* isCompact */ + true), printSeparator( + /* isCompact */ + true), join$b(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents, + /* isCompact */ + true)))]); + return concat$k([breakParent$6, group$i(ifBreak$8(compactTable, alignedTable))]); + + function printSeparator(isCompact) { + return concat$k(["| ", join$b(" | ", columnMaxWidths.map((width, index) => { + const spaces = isCompact ? 3 : width; + + switch (node.align[index]) { + case "left": + return ":" + "-".repeat(spaces - 1); + + case "right": + return "-".repeat(spaces - 1) + ":"; + + case "center": + return ":" + "-".repeat(spaces - 2) + ":"; + + default: + return "-".repeat(spaces); + } + })), " |"]); + } + + function printRow(rowContents, isCompact) { + return concat$k(["| ", join$b(" | ", isCompact ? rowContents : rowContents.map((rowContent, columnIndex) => { + switch (node.align[columnIndex]) { + case "right": + return alignRight(rowContent, columnMaxWidths[columnIndex]); + + case "center": + return alignCenter(rowContent, columnMaxWidths[columnIndex]); + + default: + return alignLeft(rowContent, columnMaxWidths[columnIndex]); + } + })), " |"]); + } + + function alignLeft(text, width) { + const spaces = width - getStringWidth$4(text); + return concat$k([text, " ".repeat(spaces)]); + } + + function alignRight(text, width) { + const spaces = width - getStringWidth$4(text); + return concat$k([" ".repeat(spaces), text]); + } + + function alignCenter(text, width) { + const spaces = width - getStringWidth$4(text); + const left = Math.floor(spaces / 2); + const right = spaces - left; + return concat$k([" ".repeat(left), text, " ".repeat(right)]); + } +} + +function printRoot(path, options, print) { + /** @typedef {{ index: number, offset: number }} IgnorePosition */ + + /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */ + const ignoreRanges = []; + /** @type {IgnorePosition | null} */ + + let ignoreStart = null; + const { + children + } = path.getValue(); + children.forEach((childNode, index) => { + switch (isPrettierIgnore(childNode)) { + case "start": + if (ignoreStart === null) { + ignoreStart = { + index, + offset: childNode.position.end.offset + }; + } + + break; + + case "end": + if (ignoreStart !== null) { + ignoreRanges.push({ + start: ignoreStart, + end: { + index, + offset: childNode.position.start.offset + } + }); + ignoreStart = null; + } + + break; + } + }); + return printChildren$1(path, options, print, { + processor: (childPath, index) => { + if (ignoreRanges.length !== 0) { + const ignoreRange = ignoreRanges[0]; + + if (index === ignoreRange.start.index) { + return concat$k([children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]); + } + + if (ignoreRange.start.index < index && index < ignoreRange.end.index) { + return false; + } + + if (index === ignoreRange.end.index) { + ignoreRanges.shift(); + return false; + } + } + + return childPath.call(print); + } + }); +} + +function printChildren$1(path, options, print, events) { + events = events || {}; + const postprocessor = events.postprocessor || concat$k; + + const processor = events.processor || (childPath => childPath.call(print)); + + const node = path.getValue(); + const parts = []; + let lastChildNode; + path.map((childPath, index) => { + const childNode = childPath.getValue(); + const result = processor(childPath, index); + + if (result !== false) { + const data = { + parts, + prevNode: lastChildNode, + parentNode: node, + options + }; + + if (!shouldNotPrePrintHardline(childNode, data)) { + parts.push(hardline$e); // Can't find a case to pass `shouldPrePrintTripleHardline` + + /* istanbul ignore next */ + + if (lastChildNode && TRAILING_HARDLINE_NODES.has(lastChildNode.type)) { + if (shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$e); + } + } else { + if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$e); + } + + if (shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$e); + } + } + } + + parts.push(result); + lastChildNode = childNode; + } + }, "children"); + return postprocessor(parts); +} + +function getLastDescendantNode(node) { + let current = node; + + while (current.children && current.children.length !== 0) { + current = current.children[current.children.length - 1]; + } + + return current; +} +/** @return {false | 'next' | 'start' | 'end'} */ + + +function isPrettierIgnore(node) { + if (node.type !== "html") { + return false; + } + + const match = node.value.match(/^$/); + return match === null ? false : match[1] ? match[1] : "next"; +} + +function shouldNotPrePrintHardline(node, data) { + const isFirstNode = data.parts.length === 0; + const isInlineNode = INLINE_NODE_TYPES$1.includes(node.type); + const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES$1.includes(data.parentNode.type); + return isFirstNode || isInlineNode || isInlineHTML; +} + +function shouldPrePrintDoubleHardline(node, data) { + const isSequence = (data.prevNode && data.prevNode.type) === node.type; + const isSiblingNode = isSequence && SIBLING_NODE_TYPES.has(node.type); + const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose; + const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose; + const isPrevNodePrettierIgnore = isPrettierIgnore(data.prevNode) === "next"; + const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line; + const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line; + return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem); +} + +function shouldPrePrintTripleHardline(node, data) { + const isPrevNodeList = data.prevNode && data.prevNode.type === "list"; + const isIndentedCode = node.type === "code" && node.isIndented; + return isPrevNodeList && isIndentedCode; +} + +function shouldRemainTheSameContent(path) { + const ancestorNode = getAncestorNode$2(path, ["linkReference", "imageReference"]); + return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full"); +} + +function printUrl(url, dangerousCharOrChars) { + const dangerousChars = [" "].concat(dangerousCharOrChars || []); + return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url; +} + +function printTitle(title, options, printSpace) { + if (printSpace == null) { + printSpace = true; + } + + if (!title) { + return ""; + } + + if (printSpace) { + return " " + printTitle(title, options, false); + } // title is escaped after `remark-parse` v7 + + + title = title.replace(/\\(["')])/g, "$1"); + + if (title.includes('"') && title.includes("'") && !title.includes(")")) { + return `(${title})`; // avoid escaped quotes + } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split + + + const singleCount = title.split("'").length - 1; + const doubleCount = title.split('"').length - 1; + const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"'; + title = title.replace(/\\/, "\\\\"); + title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1"); + return `${quote}${title}${quote}`; +} + +function clamp(value, min, max) { + return value < min ? min : value > max ? max : value; +} + +function clean$5(ast, newObj, parent) { + delete newObj.position; + delete newObj.raw; // front-matter + // for codeblock + + if (ast.type === "front-matter" || ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") { + delete newObj.value; + } + + if (ast.type === "list") { + delete newObj.isAligned; + } + + if (ast.type === "list" || ast.type === "listItem") { + delete newObj.spread; + delete newObj.loose; + } // texts can be splitted or merged + + + if (ast.type === "text") { + return null; + } + + if (ast.type === "inlineCode") { + newObj.value = ast.value.replace(/[\t\n ]+/g, " "); + } + + if (ast.type === "definition" || ast.type === "linkReference") { + newObj.label = ast.label.trim().replace(/[\t\n ]+/g, " ").toLowerCase(); + } + + if ((ast.type === "definition" || ast.type === "link" || ast.type === "image") && ast.title) { + newObj.title = ast.title.replace(/\\(["')])/g, "$1"); + } // for insert pragma + + + if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || isFrontMatterNode$3(parent.children[0]) && parent.children[1] === ast) && ast.type === "html" && pragma$3.startWithPragma(ast.value)) { + return null; + } +} + +function hasPrettierIgnore$4(path) { + const index = +path.getName(); + + if (index === 0) { + return false; + } + + const prevNode = path.getParentNode().children[index - 1]; + return isPrettierIgnore(prevNode) === "next"; +} + +var printerMarkdown = { + preprocess: preprocess_1$1, + print: genericPrint$4, + embed: embed_1$2, + massageAstNode: clean$5, + hasPrettierIgnore: hasPrettierIgnore$4, + insertPragma: pragma$3.insertPragma +}; + +var options$5 = { + proseWrap: commonOptions.proseWrap, + singleQuote: commonOptions.singleQuote +}; + +var name$f = "Markdown"; +var type$d = "prose"; +var aliases$4 = [ + "pandoc" +]; +var aceMode$d = "markdown"; +var codemirrorMode$a = "gfm"; +var codemirrorMimeType$a = "text/x-gfm"; +var wrap = true; +var extensions$d = [ + ".md", + ".markdown", + ".mdown", + ".mdwn", + ".mdx", + ".mkd", + ".mkdn", + ".mkdown", + ".ronn", + ".workbook" +]; +var filenames$3 = [ + "contents.lr" +]; +var tmScope$d = "source.gfm"; +var languageId$d = 222; +var Markdown = { + name: name$f, + type: type$d, + aliases: aliases$4, + aceMode: aceMode$d, + codemirrorMode: codemirrorMode$a, + codemirrorMimeType: codemirrorMimeType$a, + wrap: wrap, + extensions: extensions$d, + filenames: filenames$3, + tmScope: tmScope$d, + languageId: languageId$d +}; + +var Markdown$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + name: name$f, + type: type$d, + aliases: aliases$4, + aceMode: aceMode$d, + codemirrorMode: codemirrorMode$a, + codemirrorMimeType: codemirrorMimeType$a, + wrap: wrap, + extensions: extensions$d, + filenames: filenames$3, + tmScope: tmScope$d, + languageId: languageId$d, + 'default': Markdown +}); + +var require$$0$6 = getCjsExportFromNamespace(Markdown$1); + +const languages$4 = [createLanguage(require$$0$6, data => ({ + since: "1.8.0", + parsers: ["markdown"], + vscodeLanguageIds: ["markdown"], + filenames: data.filenames.concat(["README"]), + extensions: data.extensions.filter(extension => extension !== ".mdx") +})), createLanguage(require$$0$6, () => ({ + name: "MDX", + since: "1.15.0", + parsers: ["mdx"], + vscodeLanguageIds: ["mdx"], + filenames: [], + extensions: [".mdx"] +}))]; +const printers$4 = { + mdast: printerMarkdown +}; +const parsers$4 = { + /* istanbul ignore next */ + get remark() { + return require("./parser-markdown").parsers.remark; + }, + + get markdown() { + return require("./parser-markdown").parsers.remark; + }, + + get mdx() { + return require("./parser-markdown").parsers.mdx; + } + +}; +var languageMarkdown = { + languages: languages$4, + options: options$5, + printers: printers$4, + parsers: parsers$4 +}; + +const { + isFrontMatterNode: isFrontMatterNode$4 +} = util; + +var clean$6 = function (ast, newNode) { + delete newNode.sourceSpan; + delete newNode.startSourceSpan; + delete newNode.endSourceSpan; + delete newNode.nameSpan; + delete newNode.valueSpan; + + if (ast.type === "text" || ast.type === "comment") { + return null; + } // may be formatted by multiparser + + + if (isFrontMatterNode$4(ast) || ast.type === "yaml" || ast.type === "toml") { + return null; + } + + if (ast.type === "attribute") { + delete newNode.value; + } + + if (ast.type === "docType") { + delete newNode.value; + } +}; + +var index$1 = [ + "a", + "abbr", + "acronym", + "address", + "applet", + "area", + "article", + "aside", + "audio", + "b", + "base", + "basefont", + "bdi", + "bdo", + "bgsound", + "big", + "blink", + "blockquote", + "body", + "br", + "button", + "canvas", + "caption", + "center", + "cite", + "code", + "col", + "colgroup", + "command", + "content", + "data", + "datalist", + "dd", + "del", + "details", + "dfn", + "dialog", + "dir", + "div", + "dl", + "dt", + "element", + "em", + "embed", + "fieldset", + "figcaption", + "figure", + "font", + "footer", + "form", + "frame", + "frameset", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hgroup", + "hr", + "html", + "i", + "iframe", + "image", + "img", + "input", + "ins", + "isindex", + "kbd", + "keygen", + "label", + "legend", + "li", + "link", + "listing", + "main", + "map", + "mark", + "marquee", + "math", + "menu", + "menuitem", + "meta", + "meter", + "multicol", + "nav", + "nextid", + "nobr", + "noembed", + "noframes", + "noscript", + "object", + "ol", + "optgroup", + "option", + "output", + "p", + "param", + "picture", + "plaintext", + "pre", + "progress", + "q", + "rb", + "rbc", + "rp", + "rt", + "rtc", + "ruby", + "s", + "samp", + "script", + "section", + "select", + "shadow", + "slot", + "small", + "source", + "spacer", + "span", + "strike", + "strong", + "style", + "sub", + "summary", + "sup", + "svg", + "table", + "tbody", + "td", + "template", + "textarea", + "tfoot", + "th", + "thead", + "time", + "title", + "tr", + "track", + "tt", + "u", + "ul", + "var", + "video", + "wbr", + "xmp" +]; + +var htmlTagNames = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': index$1 +}); + +var a = [ + "accesskey", + "charset", + "coords", + "download", + "href", + "hreflang", + "name", + "ping", + "referrerpolicy", + "rel", + "rev", + "shape", + "tabindex", + "target", + "type" +]; +var abbr = [ + "title" +]; +var applet = [ + "align", + "alt", + "archive", + "code", + "codebase", + "height", + "hspace", + "name", + "object", + "vspace", + "width" +]; +var area = [ + "accesskey", + "alt", + "coords", + "download", + "href", + "hreflang", + "nohref", + "ping", + "referrerpolicy", + "rel", + "shape", + "tabindex", + "target", + "type" +]; +var audio = [ + "autoplay", + "controls", + "crossorigin", + "loop", + "muted", + "preload", + "src" +]; +var base = [ + "href", + "target" +]; +var basefont = [ + "color", + "face", + "size" +]; +var bdo = [ + "dir" +]; +var blockquote = [ + "cite" +]; +var body = [ + "alink", + "background", + "bgcolor", + "link", + "text", + "vlink" +]; +var br = [ + "clear" +]; +var button = [ + "accesskey", + "autofocus", + "disabled", + "form", + "formaction", + "formenctype", + "formmethod", + "formnovalidate", + "formtarget", + "name", + "tabindex", + "type", + "value" +]; +var canvas = [ + "height", + "width" +]; +var caption = [ + "align" +]; +var col = [ + "align", + "char", + "charoff", + "span", + "valign", + "width" +]; +var colgroup = [ + "align", + "char", + "charoff", + "span", + "valign", + "width" +]; +var data$1 = [ + "value" +]; +var del$1 = [ + "cite", + "datetime" +]; +var details = [ + "open" +]; +var dfn = [ + "title" +]; +var dialog = [ + "open" +]; +var dir = [ + "compact" +]; +var div = [ + "align" +]; +var dl = [ + "compact" +]; +var embed$3 = [ + "height", + "src", + "type", + "width" +]; +var fieldset = [ + "disabled", + "form", + "name" +]; +var font = [ + "color", + "face", + "size" +]; +var form = [ + "accept", + "accept-charset", + "action", + "autocomplete", + "enctype", + "method", + "name", + "novalidate", + "target" +]; +var frame = [ + "frameborder", + "longdesc", + "marginheight", + "marginwidth", + "name", + "noresize", + "scrolling", + "src" +]; +var frameset = [ + "cols", + "rows" +]; +var h1 = [ + "align" +]; +var h2 = [ + "align" +]; +var h3 = [ + "align" +]; +var h4 = [ + "align" +]; +var h5 = [ + "align" +]; +var h6 = [ + "align" +]; +var head = [ + "profile" +]; +var hr = [ + "align", + "noshade", + "size", + "width" +]; +var html = [ + "manifest", + "version" +]; +var iframe = [ + "align", + "allow", + "allowfullscreen", + "allowpaymentrequest", + "allowusermedia", + "frameborder", + "height", + "longdesc", + "marginheight", + "marginwidth", + "name", + "referrerpolicy", + "sandbox", + "scrolling", + "src", + "srcdoc", + "width" +]; +var img = [ + "align", + "alt", + "border", + "crossorigin", + "decoding", + "height", + "hspace", + "ismap", + "longdesc", + "name", + "referrerpolicy", + "sizes", + "src", + "srcset", + "usemap", + "vspace", + "width" +]; +var input = [ + "accept", + "accesskey", + "align", + "alt", + "autocomplete", + "autofocus", + "checked", + "dirname", + "disabled", + "form", + "formaction", + "formenctype", + "formmethod", + "formnovalidate", + "formtarget", + "height", + "ismap", + "list", + "max", + "maxlength", + "min", + "minlength", + "multiple", + "name", + "pattern", + "placeholder", + "readonly", + "required", + "size", + "src", + "step", + "tabindex", + "title", + "type", + "usemap", + "value", + "width" +]; +var ins = [ + "cite", + "datetime" +]; +var isindex = [ + "prompt" +]; +var label = [ + "accesskey", + "for", + "form" +]; +var legend = [ + "accesskey", + "align" +]; +var li = [ + "type", + "value" +]; +var link$3 = [ + "as", + "charset", + "color", + "crossorigin", + "href", + "hreflang", + "imagesizes", + "imagesrcset", + "integrity", + "media", + "nonce", + "referrerpolicy", + "rel", + "rev", + "sizes", + "target", + "title", + "type" +]; +var map$1 = [ + "name" +]; +var menu = [ + "compact" +]; +var meta = [ + "charset", + "content", + "http-equiv", + "name", + "scheme" +]; +var meter = [ + "high", + "low", + "max", + "min", + "optimum", + "value" +]; +var object = [ + "align", + "archive", + "border", + "classid", + "codebase", + "codetype", + "data", + "declare", + "form", + "height", + "hspace", + "name", + "standby", + "tabindex", + "type", + "typemustmatch", + "usemap", + "vspace", + "width" +]; +var ol = [ + "compact", + "reversed", + "start", + "type" +]; +var optgroup = [ + "disabled", + "label" +]; +var option = [ + "disabled", + "label", + "selected", + "value" +]; +var output = [ + "for", + "form", + "name" +]; +var p = [ + "align" +]; +var param = [ + "name", + "type", + "value", + "valuetype" +]; +var pre = [ + "width" +]; +var progress = [ + "max", + "value" +]; +var q = [ + "cite" +]; +var script = [ + "async", + "charset", + "crossorigin", + "defer", + "integrity", + "language", + "nomodule", + "nonce", + "referrerpolicy", + "src", + "type" +]; +var select = [ + "autocomplete", + "autofocus", + "disabled", + "form", + "multiple", + "name", + "required", + "size", + "tabindex" +]; +var slot = [ + "name" +]; +var source$2 = [ + "media", + "sizes", + "src", + "srcset", + "type" +]; +var style = [ + "media", + "nonce", + "title", + "type" +]; +var table = [ + "align", + "bgcolor", + "border", + "cellpadding", + "cellspacing", + "frame", + "rules", + "summary", + "width" +]; +var tbody = [ + "align", + "char", + "charoff", + "valign" +]; +var td = [ + "abbr", + "align", + "axis", + "bgcolor", + "char", + "charoff", + "colspan", + "headers", + "height", + "nowrap", + "rowspan", + "scope", + "valign", + "width" +]; +var textarea = [ + "accesskey", + "autocomplete", + "autofocus", + "cols", + "dirname", + "disabled", + "form", + "maxlength", + "minlength", + "name", + "placeholder", + "readonly", + "required", + "rows", + "tabindex", + "wrap" +]; +var tfoot = [ + "align", + "char", + "charoff", + "valign" +]; +var th = [ + "abbr", + "align", + "axis", + "bgcolor", + "char", + "charoff", + "colspan", + "headers", + "height", + "nowrap", + "rowspan", + "scope", + "valign", + "width" +]; +var thead = [ + "align", + "char", + "charoff", + "valign" +]; +var time = [ + "datetime" +]; +var tr = [ + "align", + "bgcolor", + "char", + "charoff", + "valign" +]; +var track = [ + "default", + "kind", + "label", + "src", + "srclang" +]; +var ul = [ + "compact", + "type" +]; +var video = [ + "autoplay", + "controls", + "crossorigin", + "height", + "loop", + "muted", + "playsinline", + "poster", + "preload", + "src", + "width" +]; +var index$2 = { + "*": [ + "accesskey", + "autocapitalize", + "autofocus", + "class", + "contenteditable", + "dir", + "draggable", + "enterkeyhint", + "hidden", + "id", + "inputmode", + "is", + "itemid", + "itemprop", + "itemref", + "itemscope", + "itemtype", + "lang", + "nonce", + "slot", + "spellcheck", + "style", + "tabindex", + "title", + "translate" +], + a: a, + abbr: abbr, + applet: applet, + area: area, + audio: audio, + base: base, + basefont: basefont, + bdo: bdo, + blockquote: blockquote, + body: body, + br: br, + button: button, + canvas: canvas, + caption: caption, + col: col, + colgroup: colgroup, + data: data$1, + del: del$1, + details: details, + dfn: dfn, + dialog: dialog, + dir: dir, + div: div, + dl: dl, + embed: embed$3, + fieldset: fieldset, + font: font, + form: form, + frame: frame, + frameset: frameset, + h1: h1, + h2: h2, + h3: h3, + h4: h4, + h5: h5, + h6: h6, + head: head, + hr: hr, + html: html, + iframe: iframe, + img: img, + input: input, + ins: ins, + isindex: isindex, + label: label, + legend: legend, + li: li, + link: link$3, + map: map$1, + menu: menu, + meta: meta, + meter: meter, + object: object, + ol: ol, + optgroup: optgroup, + option: option, + output: output, + p: p, + param: param, + pre: pre, + progress: progress, + q: q, + script: script, + select: select, + slot: slot, + source: source$2, + style: style, + table: table, + tbody: tbody, + td: td, + textarea: textarea, + tfoot: tfoot, + th: th, + thead: thead, + time: time, + tr: tr, + track: track, + ul: ul, + video: video +}; + +var htmlElementAttributes = /*#__PURE__*/Object.freeze({ + __proto__: null, + a: a, + abbr: abbr, + applet: applet, + area: area, + audio: audio, + base: base, + basefont: basefont, + bdo: bdo, + blockquote: blockquote, + body: body, + br: br, + button: button, + canvas: canvas, + caption: caption, + col: col, + colgroup: colgroup, + data: data$1, + del: del$1, + details: details, + dfn: dfn, + dialog: dialog, + dir: dir, + div: div, + dl: dl, + embed: embed$3, + fieldset: fieldset, + font: font, + form: form, + frame: frame, + frameset: frameset, + h1: h1, + h2: h2, + h3: h3, + h4: h4, + h5: h5, + h6: h6, + head: head, + hr: hr, + html: html, + iframe: iframe, + img: img, + input: input, + ins: ins, + isindex: isindex, + label: label, + legend: legend, + li: li, + link: link$3, + map: map$1, + menu: menu, + meta: meta, + meter: meter, + object: object, + ol: ol, + optgroup: optgroup, + option: option, + output: output, + p: p, + param: param, + pre: pre, + progress: progress, + q: q, + script: script, + select: select, + slot: slot, + source: source$2, + style: style, + table: table, + tbody: tbody, + td: td, + textarea: textarea, + tfoot: tfoot, + th: th, + thead: thead, + time: time, + tr: tr, + track: track, + ul: ul, + video: video, + 'default': index$2 +}); + +var json$1 = { + "CSS_DISPLAY_TAGS": { + "area": "none", + "base": "none", + "basefont": "none", + "datalist": "none", + "head": "none", + "link": "none", + "meta": "none", + "noembed": "none", + "noframes": "none", + "param": "block", + "rp": "none", + "script": "block", + "source": "block", + "style": "none", + "template": "inline", + "track": "block", + "title": "none", + "html": "block", + "body": "block", + "address": "block", + "blockquote": "block", + "center": "block", + "div": "block", + "figure": "block", + "figcaption": "block", + "footer": "block", + "form": "block", + "header": "block", + "hr": "block", + "legend": "block", + "listing": "block", + "main": "block", + "p": "block", + "plaintext": "block", + "pre": "block", + "xmp": "block", + "slot": "contents", + "ruby": "ruby", + "rt": "ruby-text", + "article": "block", + "aside": "block", + "h1": "block", + "h2": "block", + "h3": "block", + "h4": "block", + "h5": "block", + "h6": "block", + "hgroup": "block", + "nav": "block", + "section": "block", + "dir": "block", + "dd": "block", + "dl": "block", + "dt": "block", + "ol": "block", + "ul": "block", + "li": "list-item", + "table": "table", + "caption": "table-caption", + "colgroup": "table-column-group", + "col": "table-column", + "thead": "table-header-group", + "tbody": "table-row-group", + "tfoot": "table-footer-group", + "tr": "table-row", + "td": "table-cell", + "th": "table-cell", + "fieldset": "block", + "button": "inline-block", + "details": "block", + "summary": "block", + "dialog": "block", + "meter": "inline-block", + "progress": "inline-block", + "object": "inline-block", + "video": "inline-block", + "audio": "inline-block", + "select": "inline-block", + "option": "block", + "optgroup": "block" + }, + "CSS_DISPLAY_DEFAULT": "inline", + "CSS_WHITE_SPACE_TAGS": { + "listing": "pre", + "plaintext": "pre", + "pre": "pre", + "xmp": "pre", + "nobr": "nowrap", + "table": "initial", + "textarea": "pre-wrap" + }, + "CSS_WHITE_SPACE_DEFAULT": "normal" +}; + +var htmlTagNames$1 = getCjsExportFromNamespace(htmlTagNames); + +var htmlElementAttributes$1 = getCjsExportFromNamespace(htmlElementAttributes); + +const { + getParserName: getParserName$2, + isFrontMatterNode: isFrontMatterNode$5 +} = util; +const { + CSS_DISPLAY_TAGS, + CSS_DISPLAY_DEFAULT, + CSS_WHITE_SPACE_TAGS, + CSS_WHITE_SPACE_DEFAULT +} = json$1; +const HTML_TAGS = arrayToMap(htmlTagNames$1); +const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes$1, arrayToMap); // https://infra.spec.whatwg.org/#ascii-whitespace + +const HTML_WHITESPACE = new Set(["\t", "\n", "\f", "\r", " "]); + +const htmlTrimStart = string => string.replace(/^[\t\n\f\r ]+/, ""); + +const htmlTrimEnd = string => string.replace(/[\t\n\f\r ]+$/, ""); + +const htmlTrim = string => htmlTrimStart(htmlTrimEnd(string)); + +const htmlTrimLeadingBlankLines = string => string.replace(/^[\t\f\r ]*?\n/g, ""); + +const htmlTrimPreserveIndentation = string => htmlTrimLeadingBlankLines(htmlTrimEnd(string)); + +const splitByHtmlWhitespace = string => string.split(/[\t\n\f\r ]+/); + +const getLeadingHtmlWhitespace = string => string.match(/^[\t\n\f\r ]*/)[0]; + +const getLeadingAndTrailingHtmlWhitespace = string => { + const [, leadingWhitespace, text, trailingWhitespace] = string.match(/^([\t\n\f\r ]*)([\S\s]*?)([\t\n\f\r ]*)$/); + return { + leadingWhitespace, + trailingWhitespace, + text + }; +}; + +const hasHtmlWhitespace = string => /[\t\n\f\r ]/.test(string); + +function arrayToMap(array) { + const map = Object.create(null); + + for (const value of array) { + map[value] = true; + } + + return map; +} + +function mapObject(object, fn) { + const newObject = Object.create(null); + + for (const key of Object.keys(object)) { + newObject[key] = fn(object[key], key); + } + + return newObject; +} + +function shouldPreserveContent(node, options) { + // unterminated node in ie conditional comment + // e.g. + if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) { + return true; + } // incomplete html in ie conditional comment + // e.g. + + + if (node.type === "ieConditionalComment" && !node.complete) { + return true; + } // TODO: handle non-text children in
+
+
+  if (isPreLikeNode(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
+    return true;
+  }
+
+  if (isVueNonHtmlBlock(node, options) && !isScriptLikeTag(node) && node.type !== "interpolation") {
+    return true;
+  }
+
+  return false;
+}
+
+function hasPrettierIgnore$5(node) {
+  /* istanbul ignore next */
+  if (node.type === "attribute") {
+    return false;
+  }
+  /* istanbul ignore next */
+
+
+  if (!node.parent) {
+    return false;
+  }
+
+  if (typeof node.index !== "number" || node.index === 0) {
+    return false;
+  }
+
+  const prevNode = node.parent.children[node.index - 1];
+  return isPrettierIgnore$1(prevNode);
+}
+
+function isPrettierIgnore$1(node) {
+  return node.type === "comment" && node.value.trim() === "prettier-ignore";
+}
+
+function getPrettierIgnoreAttributeCommentData(value) {
+  const match = value.trim().match(/^prettier-ignore-attribute(?:\s+([^]+))?$/);
+
+  if (!match) {
+    return false;
+  }
+
+  if (!match[1]) {
+    return true;
+  }
+
+  return match[1].split(/\s+/);
+}
+/** there's no opening/closing tag or it's considered not breakable */
+
+
+function isTextLikeNode(node) {
+  return node.type === "text" || node.type === "comment";
+}
+
+function isScriptLikeTag(node) {
+  return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
+}
+
+function canHaveInterpolation(node) {
+  return node.children && !isScriptLikeTag(node);
+}
+
+function isWhitespaceSensitiveNode(node) {
+  return isScriptLikeTag(node) || node.type === "interpolation" || isIndentationSensitiveNode(node);
+}
+
+function isIndentationSensitiveNode(node) {
+  return getNodeCssStyleWhiteSpace(node).startsWith("pre");
+}
+
+function isLeadingSpaceSensitiveNode(node, options) {
+  const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
+
+  if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
+    return node.type === "interpolation";
+  }
+
+  return isLeadingSpaceSensitive;
+
+  function _isLeadingSpaceSensitiveNode() {
+    if (isFrontMatterNode$5(node)) {
+      return false;
+    }
+
+    if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
+      return true;
+    }
+
+    if (!node.parent || node.parent.cssDisplay === "none") {
+      return false;
+    }
+
+    if (isPreLikeNode(node.parent)) {
+      return true;
+    }
+
+    if (!node.prev && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
+      return false;
+    }
+
+    if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
+      return false;
+    }
+
+    return true;
+  }
+}
+
+function isTrailingSpaceSensitiveNode(node, options) {
+  if (isFrontMatterNode$5(node)) {
+    return false;
+  }
+
+  if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
+    return true;
+  }
+
+  if (!node.parent || node.parent.cssDisplay === "none") {
+    return false;
+  }
+
+  if (isPreLikeNode(node.parent)) {
+    return true;
+  }
+
+  if (!node.next && (node.parent.type === "root" || isPreLikeNode(node) && node.parent || isScriptLikeTag(node.parent) || isVueCustomBlock(node.parent, options) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
+    return false;
+  }
+
+  if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
+    return false;
+  }
+
+  return true;
+}
+
+function isDanglingSpaceSensitiveNode(node) {
+  return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag(node);
+}
+
+function forceNextEmptyLine(node) {
+  return isFrontMatterNode$5(node) || node.next && node.sourceSpan.end && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
+}
+/** firstChild leadingSpaces and lastChild trailingSpaces */
+
+
+function forceBreakContent(node) {
+  return forceBreakChildren(node) || node.type === "element" && node.children.length !== 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && node.firstChild.type !== "text" && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
+}
+/** spaces between children */
+
+
+function forceBreakChildren(node) {
+  return node.type === "element" && node.children.length !== 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
+}
+
+function preferHardlineAsLeadingSpaces(node) {
+  return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
+}
+
+function preferHardlineAsTrailingSpaces(node) {
+  return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
+}
+
+function hasSurroundingLineBreak(node) {
+  return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
+}
+
+function hasLeadingLineBreak(node) {
+  return node.hasLeadingSpaces && (node.prev ? node.prev.sourceSpan.end.line < node.sourceSpan.start.line : node.parent.type === "root" || node.parent.startSourceSpan.end.line < node.sourceSpan.start.line);
+}
+
+function hasTrailingLineBreak(node) {
+  return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan && node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
+}
+
+function preferHardlineAsSurroundingSpaces(node) {
+  switch (node.type) {
+    case "ieConditionalComment":
+    case "comment":
+    case "directive":
+      return true;
+
+    case "element":
+      return ["script", "select"].includes(node.name);
+  }
+
+  return false;
+}
+
+function getLastDescendant(node) {
+  return node.lastChild ? getLastDescendant(node.lastChild) : node;
+}
+
+function hasNonTextChild(node) {
+  return node.children && node.children.some(child => child.type !== "text");
+}
+
+function _inferScriptParser(node) {
+  const {
+    type,
+    lang
+  } = node.attrMap;
+
+  if (type === "module" || type === "text/javascript" || type === "text/babel" || type === "application/javascript" || lang === "jsx") {
+    return "babel";
+  }
+
+  if (type === "application/x-typescript" || lang === "ts" || lang === "tsx") {
+    return "typescript";
+  }
+
+  if (type === "text/markdown") {
+    return "markdown";
+  }
+
+  if (type === "text/html") {
+    return "html";
+  }
+
+  if (type && (type.endsWith("json") || type.endsWith("importmap"))) {
+    return "json";
+  }
+
+  if (type === "text/x-handlebars-template") {
+    return "glimmer";
+  }
+}
+
+function inferStyleParser(node) {
+  const {
+    lang
+  } = node.attrMap;
+
+  if (!lang || lang === "postcss" || lang === "css") {
+    return "css";
+  }
+
+  if (lang === "scss") {
+    return "scss";
+  }
+
+  if (lang === "less") {
+    return "less";
+  }
+}
+
+function inferScriptParser(node, options) {
+  if (node.name === "script" && !node.attrMap.src) {
+    if (!node.attrMap.lang && !node.attrMap.type) {
+      return "babel";
+    }
+
+    return _inferScriptParser(node);
+  }
+
+  if (node.name === "style") {
+    return inferStyleParser(node);
+  }
+
+  if (options && isVueNonHtmlBlock(node, options)) {
+    return _inferScriptParser(node) || !("src" in node.attrMap) && getParserName$2(node.attrMap.lang, options);
+  }
+}
+
+function isBlockLikeCssDisplay(cssDisplay) {
+  return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
+}
+
+function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
+}
+
+function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
+}
+
+function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay);
+}
+
+function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay);
+}
+
+function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
+}
+
+function isPreLikeNode(node) {
+  return getNodeCssStyleWhiteSpace(node).startsWith("pre");
+}
+
+function countParents(path, predicate) {
+  let counter = 0;
+
+  for (let i = path.stack.length - 1; i >= 0; i--) {
+    const value = path.stack[i];
+
+    if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
+      counter++;
+    }
+  }
+
+  return counter;
+}
+
+function hasParent(node, fn) {
+  let current = node;
+
+  while (current) {
+    if (fn(current)) {
+      return true;
+    }
+
+    current = current.parent;
+  }
+
+  return false;
+}
+
+function getNodeCssStyleDisplay(node, options) {
+  if (node.prev && node.prev.type === "comment") {
+    // 
+    const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
+
+    if (match) {
+      return match[1];
+    }
+  }
+
+  let isInSvgForeignObject = false;
+
+  if (node.type === "element" && node.namespace === "svg") {
+    if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) {
+      isInSvgForeignObject = true;
+    } else {
+      return node.name === "svg" ? "inline-block" : "block";
+    }
+  }
+
+  switch (options.htmlWhitespaceSensitivity) {
+    case "strict":
+      return "inline";
+
+    case "ignore":
+      return "block";
+
+    default:
+      {
+        // See https://github.com/prettier/prettier/issues/8151
+        if (options.parser === "vue" && node.parent && node.parent.type === "root") {
+          return "block";
+        }
+
+        return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
+      }
+  }
+}
+
+function isUnknownNamespace(node) {
+  return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace);
+}
+
+function getNodeCssStyleWhiteSpace(node) {
+  return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
+}
+
+function getMinIndentation(text) {
+  let minIndentation = Infinity;
+
+  for (const lineText of text.split("\n")) {
+    if (lineText.length === 0) {
+      continue;
+    }
+
+    if (!HTML_WHITESPACE.has(lineText[0])) {
+      return 0;
+    }
+
+    const indentation = getLeadingHtmlWhitespace(lineText).length;
+
+    if (lineText.length === indentation) {
+      continue;
+    }
+
+    if (indentation < minIndentation) {
+      minIndentation = indentation;
+    }
+  }
+
+  return minIndentation === Infinity ? 0 : minIndentation;
+}
+
+function dedentString(text, minIndent = getMinIndentation(text)) {
+  return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
+}
+
+function shouldNotPrintClosingTag(node, options) {
+  return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$5(node) || shouldPreserveContent(node.parent, options));
+}
+
+function countChars(text, char) {
+  let counter = 0;
+
+  for (let i = 0; i < text.length; i++) {
+    if (text[i] === char) {
+      counter++;
+    }
+  }
+
+  return counter;
+}
+
+function unescapeQuoteEntities(text) {
+  return text.replace(/'/g, "'").replace(/"/g, '"');
+} // top-level elements (excluding